1 package org.ibex.nestedvm;
3 import org.ibex.nestedvm.util.*;
7 // FIXME: Make plain old "mips-unknown-elf-gcc -o foo foo.c" work (modify spec file or whatever)
9 // FEATURE: Remove System.{out,err}.printlns and throw Errors where applicable
11 public abstract class UnixRuntime extends Runtime implements Cloneable {
12 /** The pid of this "process" */
14 private UnixRuntime parent;
15 public final int getPid() { return pid; }
17 private static final GlobalState defaultGD = new GlobalState();
18 private GlobalState gd = defaultGD;
20 /** proceses' current working directory - absolute path WITHOUT leading slash
21 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
24 /** The runtime that should be run next when in state == EXECED */
25 private UnixRuntime execedRuntime;
27 private Object children; // used only for synchronizatin
28 private Vector activeChildren;
29 private Vector exitedChildren;
31 protected UnixRuntime(int pageSize, int totalPages) {
32 super(pageSize,totalPages);
34 // FEATURE: Do the proper mangling for non-unix hosts
35 String userdir = getSystemProperty("user.dir");
36 cwd = userdir != null && userdir.startsWith("/") && File.separatorChar == '/' ? userdir.substring(1) : "";
39 // NOTE: getDisplayName() is a Java2 function
40 private static String posixTZ() {
41 StringBuffer sb = new StringBuffer();
42 TimeZone zone = TimeZone.getDefault();
43 int off = zone.getRawOffset() / 1000;
44 sb.append(zone.getDisplayName(false,TimeZone.SHORT));
45 if(off > 0) sb.append("-");
47 sb.append(off/3600); off = off%3600;
48 if(off > 0) sb.append(":").append(off/60); off=off%60;
49 if(off > 0) sb.append(":").append(off);
50 if(zone.useDaylightTime())
51 sb.append(zone.getDisplayName(true,TimeZone.SHORT));
55 private static boolean envHas(String key,String[] environ) {
56 for(int i=0;i<environ.length;i++)
57 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
61 String[] createEnv(String[] extra) {
62 String[] defaults = new String[5];
64 if(extra == null) extra = new String[0];
65 if(!envHas("USER",extra) && getSystemProperty("user.name") != null)
66 defaults[n++] = "USER=" + getSystemProperty("user.name");
67 if(!envHas("HOME",extra) && getSystemProperty("user.name") != null)
68 defaults[n++] = "HOME=" + getSystemProperty("user.home");
69 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
70 if(!envHas("TERM",extra)) defaults[n++] = "TERM=vt100";
71 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
72 String[] env = new String[extra.length+n];
73 for(int i=0;i<n;i++) env[i] = defaults[i];
74 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
78 private static class ProcessTableFullExn extends RuntimeException { }
81 UnixRuntime[] tasks = gd.tasks;
84 if(tasks[pid] == null || tasks[pid].pid != pid) throw new Error("should never happen");
87 int nextPID = gd.nextPID;
88 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
89 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
90 if(newpid == -1) throw new ProcessTableFullExn();
92 gd.nextPID = newpid + 1;
98 int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
100 case SYS_kill: return sys_kill(a,b);
101 case SYS_fork: return sys_fork();
102 case SYS_pipe: return sys_pipe(a);
103 case SYS_dup2: return sys_dup2(a,b);
104 case SYS_waitpid: return sys_waitpid(a,b,c);
105 case SYS_stat: return sys_stat(a,b);
106 case SYS_lstat: return sys_lstat(a,b);
107 case SYS_mkdir: return sys_mkdir(a,b);
108 case SYS_getcwd: return sys_getcwd(a,b);
109 case SYS_chdir: return sys_chdir(a);
110 case SYS_exec: return sys_exec(a,b,c);
111 case SYS_getdents: return sys_getdents(a,b,c,d);
113 default: return super._syscall(syscall,a,b,c,d);
117 FD _open(String path, int flags, int mode) throws ErrnoException {
118 return gd.open(this,normalizePath(path),flags,mode);
121 /** The kill syscall.
122 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
123 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
124 Anything else terminates the process. */
125 private int sys_kill(int pid, int signal) {
126 // This will only be called by raise() in newlib to invoke the default handler
127 // We don't have to worry about actually delivering the signal
128 if(pid != pid) return -ESRCH;
129 if(signal < 0 || signal >= 32) return -EINVAL;
144 return syscall(SYS_exit,128+signal,0,0,0);
149 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
150 System.err.println("PID: " + this.pid + " is waiting on " + pid);
151 final int WNOHANG = 1;
152 if((options & ~(WNOHANG)) != 0) return -EINVAL;
153 if(pid == 0 || pid < -1) {
154 System.err.println("WARNING: waitpid called with a pid of " + pid);
157 boolean blocking = (options&WNOHANG)==0;
159 if(pid !=-1 && (pid <= 0 || pid >= gd.tasks.length)) return -ECHILD;
160 if(children == null) return blocking ? -ECHILD : 0;
162 UnixRuntime done = null;
164 synchronized(children) {
167 if(exitedChildren.size() > 0) done = (UnixRuntime)exitedChildren.remove(exitedChildren.size() - 1);
169 UnixRuntime t = gd.tasks[pid];
170 if(t.parent != this) return -ECHILD;
171 if(t.state == EXITED) {
172 if(!exitedChildren.remove(t)) throw new Error("should never happen");
176 // process group stuff, EINVAL returned above
177 throw new Error("should never happen");
180 if(!blocking) return 0;
181 try { children.wait(); } catch(InterruptedException e) {}
182 System.err.println("waitpid woke up: " + exitedChildren.size());
184 gd.tasks[done.pid] = null;
189 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
195 if(children != null) synchronized(children) {
196 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
197 UnixRuntime child = (UnixRuntime) e.nextElement();
198 gd.tasks[child.pid] = null;
200 exitedChildren.clear();
201 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
202 UnixRuntime child = (UnixRuntime) e.nextElement();
205 activeChildren.clear();
208 UnixRuntime _parent = parent;
209 if(_parent == null) {
210 gd.tasks[pid] = null;
212 synchronized(_parent.children) {
214 gd.tasks[pid] = null;
216 parent.activeChildren.remove(this);
217 parent.exitedChildren.add(this);
218 parent.children.notify();
224 protected Object clone() throws CloneNotSupportedException {
225 UnixRuntime r = (UnixRuntime) super.clone();
229 r.activeChildren = r.exitedChildren = null;
233 private int sys_fork() {
234 CPUState state = new CPUState();
236 int sp = state.r[SP];
240 r = (UnixRuntime) clone();
241 } catch(Exception e) {
250 } catch(ProcessTableFullExn e) {
254 System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
255 if(children == null) {
256 children = new Object();
257 activeChildren = new Vector();
258 exitedChildren = new Vector();
260 activeChildren.add(r);
262 state.r[V0] = 0; // return 0 to child
263 state.pc += 4; // skip over syscall instruction
264 r.setCPUState(state);
267 new ForkedProcess(r);
272 public static final class ForkedProcess extends Thread {
273 private final UnixRuntime initial;
274 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
275 public void run() { UnixRuntime.executeAndExec(initial); }
278 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
279 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
281 public static int executeAndExec(UnixRuntime r) {
284 if(r.execute()) break;
285 System.err.println("WARNING: Pause requested while executing runAndExec()");
287 if(r.state != EXECED) return r.exitStatus();
292 private String[] readStringArray(int addr) throws ReadFaultException {
294 for(int p=addr;memRead(p) != 0;p+=4) count++;
295 String[] a = new String[count];
296 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
300 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
301 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
304 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
305 if(argv.length == 0) argv = new String[]{""};
307 Object o = gd.exec(this,normalizedPath);
308 if(o == null) return -ENOENT;
310 if(o instanceof Class) {
313 return exec((UnixRuntime) c.newInstance(),argv,envp);
314 } catch(Exception e) {
319 String[] command = (String[]) o;
320 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
321 int p = command[0].lastIndexOf('/');
322 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
324 if(command[1] != null) newArgv[p++] = command[1];
325 newArgv[p++] = "/" + normalizedPath;
326 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
327 return exec(command[0],newArgv,envp);
331 private int exec(UnixRuntime r, String[] argv, String[] envp) {
333 System.err.println("Execing " + r);
334 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
336 r.closeOnExec = closeOnExec;
337 // make sure this doesn't get messed with these since we didn't copy them
354 // FEATURE: Use custom PipeFD - be sure to support PIPE_BUF of data
355 private int sys_pipe(int addr) throws FaultException {
356 PipedOutputStream writerStream = new PipedOutputStream();
357 PipedInputStream readerStream;
359 readerStream = new PipedInputStream(writerStream);
360 } catch(IOException e) {
363 FD reader = new InputStreamFD(readerStream);
364 FD writer = new OutputStreamFD(writerStream);
365 int fd1 = addFD(reader);
366 if(fd1 < 0) return -ENFILE;
367 int fd2 = addFD(writer);
368 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
371 memWrite(addr+4,fd2);
372 } catch(FaultException e) {
380 private int sys_dup2(int oldd, int newd) {
381 if(oldd == newd) return 0;
382 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
383 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
384 if(fds[oldd] == null) return -EBADFD;
385 if(fds[newd] != null) fds[newd].close();
386 fds[newd] = fds[oldd].dup();
390 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
391 FStat s = gd.stat(this,normalizePath(cstring(cstring)));
392 if(s == null) return -ENOENT;
396 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
397 FStat s = gd.lstat(this,normalizePath(cstring(cstring)));
398 if(s == null) return -ENOENT;
402 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
403 gd.mkdir(this,normalizePath(cstring(cstring)),mode);
407 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
408 byte[] b = getBytes(cwd);
409 if(size == 0) return -EINVAL;
410 if(size < b.length+2) return -ERANGE;
412 copyout(b,addr+1,b.length);
413 memset(addr+b.length+1,0,1);
417 private int sys_chdir(int addr) throws ErrnoException, FaultException {
418 String path = normalizePath(cstring(addr));
419 System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
420 if(gd.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
422 System.err.println("Now: [" + cwd + "]");
426 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
427 count = Math.min(count,MAX_CHUNK);
428 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
429 if(fds[fdn] == null) return -EBADFD;
430 byte[] buf = byteBuf(count);
431 int n = fds[fdn].getdents(buf,0,count);
436 // FEATURE: Run through the fork/wait stuff one more time
437 public static class GlobalState {
438 protected static final int OPEN = 1;
439 protected static final int STAT = 2;
440 protected static final int LSTAT = 3;
441 protected static final int MKDIR = 4;
443 final UnixRuntime[] tasks;
446 private MP[] mps = new MP[0];
449 public GlobalState() { this(255); }
450 public GlobalState(int maxProcs) { this(maxProcs,true); }
451 public GlobalState(int maxProcs, boolean defaultMounts) {
452 tasks = new UnixRuntime[maxProcs+1];
454 addMount("/",new HostFS());
455 addMount("/dev",new DevFS());
459 private static class MP {
460 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
463 public int compareTo(Object o) {
464 if(!(o instanceof MP)) return 1;
465 return -path.compareTo(((MP)o).path);
469 public synchronized FS getMount(String path) {
470 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
471 if(path.equals("/")) return root;
472 path = path.substring(1);
473 for(int i=0;i<mps.length;i++)
474 if(mps[i].path.equals(path)) return mps[i].fs;
478 public synchronized void addMount(String path, FS fs) {
479 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
480 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
482 if(fs.owner != null) fs.owner.removeMount(fs);
485 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
486 path = path.substring(1);
487 int oldLength = mps.length;
488 MP[] newMPS = new MP[oldLength + 1];
489 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
490 newMPS[oldLength] = new MP(path,fs);
494 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
495 fs.devno = highdevno + 2;
498 public synchronized void removeMount(FS fs) {
499 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
500 throw new IllegalArgumentException("mount point doesn't exist");
503 public synchronized void removeMount(String path) {
504 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
505 if(path.equals("/")) {
508 path = path.substring(1);
510 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
511 if(p == mps.length) throw new Error("mount point doesn't exist");
516 private void removeMount(int index) {
517 if(index == -1) { root.owner = null; root = null; return; }
518 MP[] newMPS = new MP[mps.length - 1];
519 System.arraycopy(mps,0,newMPS,0,index);
520 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
524 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
525 int pl = normalizedPath.length();
528 synchronized(this) { list = mps; }
529 for(int i=0;i<list.length;i++) {
531 int mpl = mp.path.length();
532 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
533 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
536 return dispatch(root,op,r,normalizedPath,arg1,arg2);
539 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
541 case OPEN: return fs.open(r,path,arg1,arg2);
542 case STAT: return fs.stat(r,path);
543 case LSTAT: return fs.lstat(r,path);
544 case MKDIR: fs.mkdir(r,path,arg1); return null;
545 default: throw new Error("should never happen");
549 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
550 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
551 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
552 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
554 private Hashtable execCache = new Hashtable();
555 private static class CacheEnt {
556 public final long time;
557 public final long size;
558 public final Object o;
559 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
562 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
563 FStat fstat = stat(r,path);
564 if(fstat == null) return null;
565 long mtime = fstat.mtime();
566 long size = fstat.size();
567 CacheEnt ent = (CacheEnt) execCache.get(path);
569 System.err.println("Found cached entry for " + path);
570 if(ent.time == mtime && ent.size == size) return ent.o;
571 System.err.println("Cache was out of date");
572 execCache.remove(path);
574 FD fd = open(r,path,RD_ONLY,0);
575 if(fd == null) return null;
576 Seekable s = fd.seekable();
578 String[] command = null;
580 if(s == null) throw new ErrnoException(EACCES);
581 byte[] buf = new byte[4096];
584 int n = s.read(buf,0,buf.length);
585 if(n == -1) throw new Error("zero length file");
588 case '\177': // possible ELF
589 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
590 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
594 int n2 = s.read(buf,1,buf.length-1);
595 if(n2 == -1) throw new ErrnoException(ENOEXEC);
598 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
602 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
604 if(p == buf.length) break OUTER;
605 n = s.read(buf,p,buf.length-p);
607 command = new String[2];
609 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
612 while(arg < p && buf[arg] == ' ') arg++;
613 command[0] = new String(buf,2,cmdEnd);
614 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
616 command[0] = new String(buf,2,p-2);
618 System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
621 throw new ErrnoException(ENOEXEC);
623 } catch(IOException e) {
625 throw new ErrnoException(EIO);
628 if(command == null) {
632 Class c = RuntimeCompiler.compile(s);
633 System.err.println("Compile succeeded: " + c);
634 ent = new CacheEnt(mtime,size,c);
635 } catch(Compiler.Exn e) {
636 throw new ErrnoException(ENOEXEC);
637 } catch(IOException e) {
638 throw new ErrnoException(EIO);
641 ent = new CacheEnt(mtime,size,command);
646 execCache.put(path,ent);
651 public abstract static class FS {
655 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
657 // If this returns null it'll be truned into an ENOENT
658 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
659 // If this returns null it'll be turned into an ENOENT
660 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
661 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
664 // FEATURE: chroot support in here
665 private String normalizePath(String path) {
666 boolean absolute = path.startsWith("/");
667 int cwdl = cwd.length();
668 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
669 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
670 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
672 char[] in = new char[path.length()+1];
673 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
677 do { inp++; } while(in[inp] == '/');
678 } else if(cwdl != 0) {
679 cwd.getChars(0,cwdl,out,0);
683 path.getChars(0,path.length(),in,0);
684 while(in[inp] != 0) {
686 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
687 while(in[inp] == '/') inp++;
689 if(in[inp] == '\0') continue;
690 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
691 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
692 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
695 while(outp > 0 && out[outp] != '/') outp--;
696 System.err.println("After ..: " + new String(out,0,outp));
703 if(outp > 0 && out[outp-1] == '/') outp--;
704 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
705 return new String(out,0,outp);
708 FStat hostFStat(final File f, Object data) {
711 FileInputStream fis = new FileInputStream(f);
713 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
714 case '#': e = fis.read() == '!';
717 } catch(IOException e2) { }
718 HostFS fs = (HostFS) data;
719 final int inode = fs.inodes.get(f.getAbsolutePath());
720 final int devno = fs.devno;
721 return new HostFStat(f,e) {
722 public int inode() { return inode; }
723 public int dev() { return devno; }
727 FD hostFSDirFD(File f, Object _fs) {
728 HostFS fs = (HostFS) _fs;
729 return fs.new HostDirFD(f);
732 public static class HostFS extends FS {
733 InodeCache inodes = new InodeCache(4000);
735 public File getRoot() { return root; }
737 private static File hostRootDir() {
738 String cwd = getSystemProperty("user.dir");
739 File f = new File(cwd != null ? cwd : ".");
740 f = new File(f.getAbsolutePath());
741 while(f.getParent() != null) f = new File(f.getParent());
745 private File hostFile(String path) {
746 char sep = File.separatorChar;
748 char buf[] = path.toCharArray();
749 for(int i=0;i<buf.length;i++) {
751 if(c == '/') buf[i] = sep;
752 else if(c == sep) buf[i] = '/';
754 path = new String(buf);
756 return new File(root,path);
759 public HostFS() { this(hostRootDir()); }
760 public HostFS(String root) { this(new File(root)); }
761 public HostFS(File root) { this.root = root; }
764 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
765 final File f = hostFile(path);
766 return r.hostFSOpen(f,flags,mode,this);
769 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
770 File f = hostFile(path);
771 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
772 if(!f.exists()) return null;
773 return r.hostFStat(f,this);
776 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
777 File f = hostFile(path);
778 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
779 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
780 if(f.exists()) throw new ErrnoException(ENOTDIR);
781 File parent = f.getParentFile();
782 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
783 if(!f.mkdir()) throw new ErrnoException(EIO);
786 public class HostDirFD extends DirFD {
787 private final File f;
788 private final File[] children;
789 public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
790 public int size() { return children.length; }
791 public String name(int n) { return children[n].getName(); }
792 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
793 public int parentInode() {
794 File parent = f.getParentFile();
795 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
797 public int myInode() { return inodes.get(f.getAbsolutePath()); }
798 public int myDev() { return devno; }
802 private static void putInt(byte[] buf, int off, int n) {
803 buf[off+0] = (byte)((n>>>24)&0xff);
804 buf[off+1] = (byte)((n>>>16)&0xff);
805 buf[off+2] = (byte)((n>>> 8)&0xff);
806 buf[off+3] = (byte)((n>>> 0)&0xff);
809 public static abstract class DirFD extends FD {
810 private int pos = -2;
812 protected abstract int size();
813 protected abstract String name(int n);
814 protected abstract int inode(int n);
815 protected abstract int myDev();
816 protected int parentInode() { return -1; }
817 protected int myInode() { return -1; }
819 public int getdents(byte[] buf, int off, int len) {
823 OUTER: for(;len > 0 && pos < size();pos++){
827 ino = pos == -1 ? parentInode() : myInode();
828 if(ino == -1) continue;
829 reclen = 9 + (pos == -1 ? 2 : 1);
830 if(reclen > len) break OUTER;
832 if(pos == -1) buf[off+9] = '.';
835 String f = name(pos);
836 byte[] fb = getBytes(f);
837 reclen = fb.length + 9;
838 if(reclen > len) break OUTER;
840 System.arraycopy(fb,0,buf,off+8,fb.length);
843 buf[off+reclen-1] = 0; // null terminate
844 reclen = (reclen + 3) & ~3; // add padding
845 putInt(buf,off,reclen);
846 putInt(buf,off+4,ino);
853 protected FStat _fstat() {
855 public int type() { return S_IFDIR; }
856 public int inode() { return myInode(); }
857 public int dev() { return myDev(); }
862 public static class DevFS extends FS {
863 private static final int ROOT_INODE = 1;
864 private static final int NULL_INODE = 2;
865 private static final int ZERO_INODE = 3;
866 private static final int FD_INODE = 4;
867 private static final int FD_INODES = 32;
869 private class DevFStat extends FStat {
870 public int dev() { return devno; }
871 public int mode() { return 0666; }
872 public int type() { return S_IFCHR; }
873 public int nlink() { return 1; }
876 private abstract class DevDirFD extends DirFD {
877 public int myDev() { return devno; }
880 private FD devZeroFD = new FD() {
881 public boolean readable() { return true; }
882 public boolean writable() { return true; }
883 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
884 public int write(byte[] a, int off, int length) { return length; }
885 public int seek(int n, int whence) { return 0; }
886 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
888 private FD devNullFD = new FD() {
889 public boolean readable() { return true; }
890 public boolean writable() { return true; }
891 public int read(byte[] a, int off, int length) { return 0; }
892 public int write(byte[] a, int off, int length) { return length; }
893 public int seek(int n, int whence) { return 0; }
894 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
897 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
898 if(path.equals("null")) return devNullFD;
899 if(path.equals("zero")) return devZeroFD;
900 if(path.startsWith("fd/")) {
903 n = Integer.parseInt(path.substring(4));
904 } catch(NumberFormatException e) {
907 if(n < 0 || n >= OPEN_MAX) return null;
908 if(r.fds[n] == null) return null;
909 return r.fds[n].dup();
911 if(path.equals("fd")) {
913 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
914 final int[] files = new int[count];
916 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
917 return new DevDirFD() {
918 public int myInode() { return FD_INODE; }
919 public int parentInode() { return ROOT_INODE; }
920 public int inode(int n) { return FD_INODES + n; }
921 public String name(int n) { return Integer.toString(files[n]); }
922 public int size() { return files.length; }
925 if(path.equals("")) {
926 return new DevDirFD() {
927 public int myInode() { return ROOT_INODE; }
928 // FEATURE: Get the real parent inode somehow
929 public int parentInode() { return -1; }
930 public int inode(int n) {
932 case 0: return NULL_INODE;
933 case 1: return ZERO_INODE;
934 case 2: return FD_INODE;
939 public String name(int n) {
941 case 0: return "null";
942 case 1: return "zero";
944 default: return null;
947 public int size() { return 3; }
953 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
954 if(path.equals("null")) return devNullFD.fstat();
955 if(path.equals("zero")) return devZeroFD.fstat();
956 if(path.startsWith("fd/")) {
959 n = Integer.parseInt(path.substring(4));
960 } catch(NumberFormatException e) {
963 if(n < 0 || n >= OPEN_MAX) return null;
964 if(r.fds[n] == null) return null;
965 return r.fds[n].fstat();
967 // FEATURE: inode stuff
968 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
969 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
973 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EACCES); }