f5b8745196c5c3427dfddfb6d6f8493ed852c4c9
[nestedvm.git] / src / org / ibex / nestedvm / UnixRuntime.java
1 package org.ibex.nestedvm;
2
3 import org.ibex.nestedvm.util.*;
4 // HACK: This is ugly, this stuff needs to be in org.ibex.util or something
5 import org.ibex.classgen.util.Sort;
6 import java.io.*;
7 import java.util.*;
8 import java.net.*;
9 import java.lang.reflect.*; // For lazily linked RuntimeCompiler
10
11 // FEATURE: vfork
12
13 public abstract class UnixRuntime extends Runtime implements Cloneable {
14     /** The pid of this "process" */
15     private int pid;
16     private UnixRuntime parent;
17     public final int getPid() { return pid; }
18     
19     private static final GlobalState defaultGS = new GlobalState();
20     private GlobalState gs;
21     public void setGlobalState(GlobalState gs) {
22         if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running");
23         if(gs == null) throw new NullPointerException("gs is null");
24         this.gs = gs;
25     }
26     
27     /** proceses' current working directory - absolute path WITHOUT leading slash
28         "" = root, "bin" = /bin "usr/bin" = /usr/bin */
29     private String cwd;
30     
31     /** The runtime that should be run next when in state == EXECED */
32     private UnixRuntime execedRuntime;
33
34     private Object children; // used only for synchronizatin
35     private Vector activeChildren;
36     private Vector exitedChildren;
37     
38     protected UnixRuntime(int pageSize, int totalPages) { this(pageSize,totalPages,false); }
39     protected UnixRuntime(int pageSize, int totalPages, boolean exec) {
40         super(pageSize,totalPages,exec);
41                 
42         if(!exec) {
43             gs = defaultGS;
44             String userdir = Platform.getProperty("user.dir");
45             String nvroot = Platform.getProperty("nestedvm.root");
46             cwd = "";
47             if(userdir != null && nvroot == null) {
48                 if(userdir.startsWith("/") && File.separatorChar == '/') {
49                     cwd = userdir.substring(1);
50                 } else {
51                     Vector vec = new Vector();
52                     File root = HostFS.hostRootDir();
53                     String s = new File(userdir).getAbsolutePath();
54                     File d = new File(s);
55                     System.err.println(s);
56                     System.err.println(d);
57                     while(!d.equals(root)) {
58                         System.err.println("Got " + d.getName());
59                         vec.addElement(d.getName());
60                         if((s = d.getParent()) == null) break;
61                         d = new File(s);
62                     }
63                     if(s != null)
64                         for(int i=vec.size()-1;i>=0;i--) cwd += (String) vec.elementAt(i) + (i==0?"":"/");
65                 }
66             }
67         }
68     }
69     
70     private static String posixTZ() {
71         StringBuffer sb = new StringBuffer();
72         TimeZone zone = TimeZone.getDefault();
73         int off = zone.getRawOffset() / 1000;
74         sb.append(Platform.timeZoneGetDisplayName(zone,false,false));
75         if(off > 0) sb.append("-");
76         else off = -off;
77         sb.append(off/3600); off = off%3600;
78         if(off > 0) sb.append(":").append(off/60); off=off%60;
79         if(off > 0) sb.append(":").append(off);
80         if(zone.useDaylightTime())
81             sb.append(Platform.timeZoneGetDisplayName(zone,true,false));
82         return sb.toString();
83     }
84     
85     private static boolean envHas(String key,String[] environ) {
86         for(int i=0;i<environ.length;i++)
87             if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
88         return false;
89     }
90     
91     String[] createEnv(String[] extra) {
92         String[] defaults = new String[6];
93         int n=0;
94         if(extra == null) extra = new String[0];
95         if(!envHas("USER",extra) && Platform.getProperty("user.name") != null)
96             defaults[n++] = "USER=" + Platform.getProperty("user.name");
97         if(!envHas("HOME",extra) && Platform.getProperty("user.home") != null)
98             defaults[n++] = "HOME=" + Platform.getProperty("user.home");
99         if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
100         if(!envHas("TERM",extra) && !win32Hacks)  defaults[n++] = "TERM=vt100";
101         if(!envHas("TZ",extra))    defaults[n++] = "TZ=" + posixTZ();
102         if(!envHas("PATH",extra))  defaults[n++] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin";
103         String[] env = new String[extra.length+n];
104         for(int i=0;i<n;i++) env[i] = defaults[i];
105         for(int i=0;i<extra.length;i++) env[n++] = extra[i];
106         return env;
107     }
108     
109     private static class ProcessTableFullExn extends RuntimeException { }
110     
111     void _started() {
112         UnixRuntime[] tasks = gs.tasks;
113         synchronized(gs) {
114             if(pid != 0) {
115                 UnixRuntime prev = tasks[pid];
116                 if(prev == null || prev == this || prev.pid != pid || prev.parent != parent)
117                     throw new Error("should never happen");
118                 synchronized(parent.children) {
119                     int i = parent.activeChildren.indexOf(prev);
120                     if(i == -1) throw new Error("should never happen");
121                     parent.activeChildren.setElementAt(this,i);
122                 }
123             } else {
124                 int newpid = -1;
125                 int nextPID = gs.nextPID;
126                 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
127                 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
128                 if(newpid == -1) throw new ProcessTableFullExn();
129                 pid = newpid;
130                 gs.nextPID = newpid + 1;
131             }
132             tasks[pid] = this;
133         }
134     }
135     
136     int _syscall(int syscall, int a, int b, int c, int d, int e, int f) throws ErrnoException, FaultException {
137         switch(syscall) {
138             case SYS_kill: return sys_kill(a,b);
139             case SYS_fork: return sys_fork();
140             case SYS_pipe: return sys_pipe(a);
141             case SYS_dup2: return sys_dup2(a,b);
142             case SYS_dup: return sys_dup(a);
143             case SYS_waitpid: return sys_waitpid(a,b,c);
144             case SYS_stat: return sys_stat(a,b);
145             case SYS_lstat: return sys_lstat(a,b);
146             case SYS_mkdir: return sys_mkdir(a,b);
147             case SYS_getcwd: return sys_getcwd(a,b);
148             case SYS_chdir: return sys_chdir(a);
149             case SYS_exec: return sys_exec(a,b,c);
150             case SYS_getdents: return sys_getdents(a,b,c,d);
151             case SYS_unlink: return sys_unlink(a);
152             case SYS_getppid: return sys_getppid();
153             case SYS_socket: return sys_socket(a,b,c);
154             case SYS_connect: return sys_connect(a,b,c);
155             case SYS_resolve_hostname: return sys_resolve_hostname(a,b,c);
156             case SYS_setsockopt: return sys_setsockopt(a,b,c,d,e);
157             case SYS_getsockopt: return sys_getsockopt(a,b,c,d,e);
158             case SYS_bind: return sys_bind(a,b,c);
159             case SYS_listen: return sys_listen(a,b);
160             case SYS_accept: return sys_accept(a,b,c);
161             case SYS_shutdown: return sys_shutdown(a,b);
162             case SYS_sysctl: return sys_sysctl(a,b,c,d,e,f);
163             case SYS_sendto: return sys_sendto(a,b,c,d,e,f);
164             case SYS_recvfrom: return sys_recvfrom(a,b,c,d,e,f);
165             case SYS_select: return sys_select(a,b,c,d,e);
166
167             default: return super._syscall(syscall,a,b,c,d,e,f);
168         }
169     }
170     
171     FD _open(String path, int flags, int mode) throws ErrnoException {
172         return gs.open(this,normalizePath(path),flags,mode);
173     }
174     
175     private int sys_getppid() {
176         return parent == null ? 1 : parent.pid;
177     }
178
179     // FEATURE: Signal handling
180     // check flag only on backwards jumps to basic blocks without compulsatory checks 
181     // (see A Portable Research Framework for the Execution of Java Bytecode - Etienne Gagnon, Chapter 2)
182     
183     /** The kill syscall.
184        SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
185        SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
186        Anything else terminates the process. */
187     private int sys_kill(int pid, int signal) {
188         // This will only be called by raise() in newlib to invoke the default handler
189         // We don't have to worry about actually delivering the signal
190         if(pid != pid) return -ESRCH;
191         if(signal < 0 || signal >= 32) return -EINVAL;
192         switch(signal) {
193             case 0: return 0;
194             case 17: // SIGSTOP
195             case 18: // SIGTSTP
196             case 21: // SIGTTIN
197             case 22: // SIGTTOU
198             case 19: // SIGCONT
199             case 20: // SIGCHLD
200             case 23: // SIGIO
201             case 28: // SIGWINCH
202                 break;
203             default:
204                 exit(128+signal, true);
205         }
206         return 0;
207     }
208
209     private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
210         final int WNOHANG = 1;
211         if((options & ~(WNOHANG)) != 0) return -EINVAL;
212         if(pid == 0 || pid < -1) {
213             if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
214             return -ECHILD;
215         }
216         boolean blocking = (options&WNOHANG)==0;
217         
218         if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
219         if(children == null) return blocking ? -ECHILD : 0;
220         
221         UnixRuntime done = null;
222         
223         synchronized(children) {
224             for(;;) {
225                 if(pid == -1) {
226                     if(exitedChildren.size() > 0) {
227                         done = (UnixRuntime)exitedChildren.elementAt(exitedChildren.size() - 1);
228                         exitedChildren.removeElementAt(exitedChildren.size() - 1);
229                     }
230                 } else if(pid > 0) {
231                     if(pid >= gs.tasks.length) return -ECHILD;
232                     UnixRuntime t = gs.tasks[pid];
233                     if(t.parent != this) return -ECHILD;
234                     if(t.state == EXITED) {
235                         if(!exitedChildren.removeElement(t)) throw new Error("should never happen");
236                         done = t;
237                     }
238                 } else {
239                     // process group stuff, EINVAL returned above
240                         throw new Error("should never happen");
241                 }
242                 if(done == null) {
243                     if(!blocking) return 0;
244                     try { children.wait(); } catch(InterruptedException e) {}
245                     //System.err.println("waitpid woke up: " + exitedChildren.size());
246                 } else {
247                     gs.tasks[done.pid] = null;
248                     break;
249                 }
250             }
251         }
252         if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
253         return done.pid;
254     }
255     
256     
257     void _exited() {
258         if(children != null) synchronized(children) {
259             for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
260                 UnixRuntime child = (UnixRuntime) e.nextElement();
261                 gs.tasks[child.pid] = null;
262             }
263             exitedChildren.removeAllElements();
264             for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
265                 UnixRuntime child = (UnixRuntime) e.nextElement();
266                 child.parent = null;
267             }
268             activeChildren.removeAllElements();
269         }
270         
271         UnixRuntime _parent = parent;
272         if(_parent == null) {
273             gs.tasks[pid] = null;
274         } else {
275             synchronized(_parent.children) {
276                 if(parent == null) {
277                     gs.tasks[pid] = null;
278                 } else {
279                     if(!parent.activeChildren.removeElement(this)) throw new Error("should never happen _exited: pid: " + pid);
280                     parent.exitedChildren.addElement(this);
281                     parent.children.notify();
282                 }
283             }
284         }
285     }
286     
287     protected Object clone() throws CloneNotSupportedException {
288         UnixRuntime r = (UnixRuntime) super.clone();
289         r.pid = 0;
290         r.parent = null;
291         r.children = null;
292         r.activeChildren = r.exitedChildren = null;
293         return r;
294     }
295
296     private int sys_fork() {
297         final UnixRuntime r;
298         
299         try {
300             r = (UnixRuntime) clone();
301         } catch(Exception e) {
302             e.printStackTrace();
303             return -ENOMEM;
304         }
305
306         r.parent = this;
307
308         try {
309             r._started();
310         } catch(ProcessTableFullExn e) {
311             return -ENOMEM;
312         }
313
314         //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
315         if(children == null) {
316             children = new Object();
317             activeChildren = new Vector();
318             exitedChildren = new Vector();
319         }
320         activeChildren.addElement(r);
321         
322         CPUState state = new CPUState();
323         getCPUState(state);
324         state.r[V0] = 0; // return 0 to child
325         state.pc += 4; // skip over syscall instruction
326         r.setCPUState(state);
327         r.state = PAUSED;
328         
329         new ForkedProcess(r);
330         
331         return r.pid;
332     }
333     
334     public static final class ForkedProcess extends Thread {
335         private final UnixRuntime initial;
336         public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
337         public void run() { UnixRuntime.executeAndExec(initial); }
338     }
339     
340     public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
341     public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
342     
343     public static int executeAndExec(UnixRuntime r) {
344         for(;;) {
345             for(;;) {
346                 if(r.execute()) break;
347                 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
348             }
349             if(r.state != EXECED) return r.exitStatus();
350             r = r.execedRuntime;
351         }
352     }
353      
354     private String[] readStringArray(int addr) throws ReadFaultException {
355         int count = 0;
356         for(int p=addr;memRead(p) != 0;p+=4) count++;
357         String[] a = new String[count];
358         for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
359         return a;
360     }
361     
362     private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
363         return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
364     }
365     
366     private final static Method runtimeCompilerCompile;
367     static {
368         Method m;
369         try {
370             m = Class.forName("org.ibex.nestedvm.RuntimeCompiler").getMethod("compile",new Class[]{Seekable.class,String.class});
371         } catch(NoSuchMethodException e) {
372             m = null;
373         } catch(ClassNotFoundException e) {
374             m = null;
375         }
376         runtimeCompilerCompile = m;
377     }
378             
379     public Class runtimeCompile(Seekable s) throws IOException {
380         if(runtimeCompilerCompile == null) {
381             if(STDERR_DIAG) System.err.println("WARNING: Exec attempted but RuntimeCompiler not found!");
382             return null;
383         }
384         
385         try {
386             return (Class) runtimeCompilerCompile.invoke(null,new Object[]{s,"unixruntime"});
387         } catch(IllegalAccessException e) {
388             e.printStackTrace();
389             return null;
390         } catch(InvocationTargetException e) {
391             Throwable t = e.getTargetException();
392             if(t instanceof IOException) throw (IOException) t;
393             if(t instanceof RuntimeException) throw (RuntimeException) t;
394             if(t instanceof Error) throw (Error) t;
395             if(STDERR_DIAG) t.printStackTrace();
396             return null;
397         }
398     }
399         
400     private int exec(String path, String[] argv, String[] envp) throws ErrnoException {
401         if(argv.length == 0) argv = new String[]{""};
402         // HACK: Hideous hack to make a standalone busybox possible
403         if(path.equals("bin/busybox") && getClass().getName().endsWith("BusyBox"))
404             return execClass(getClass(),argv,envp);
405         
406         // NOTE: For this little hack to work nestedvm.root MUST be "."
407         /*try {
408             System.err.println("Execing normalized path: " + normalizedPath);
409             if(true) return exec(new Interpreter(normalizedPath),argv,envp);
410         } catch(IOException e) { throw new Error(e); }*/
411         
412         FStat fstat = gs.stat(this,path);
413         if(fstat == null) return -ENOENT;
414         GlobalState.CacheEnt ent = (GlobalState.CacheEnt) gs.execCache.get(path);
415         long mtime = fstat.mtime();
416         long size = fstat.size();
417         if(ent != null) {
418             //System.err.println("Found cached entry for " + path);
419             if(ent.time ==mtime && ent.size == size) {
420                 if(ent.o instanceof Class)
421                     return execClass((Class) ent.o,argv,envp);
422                 if(ent.o instanceof String[]) 
423                     return execScript(path,(String[]) ent.o,argv,envp);
424                 throw new Error("should never happen");
425             }
426             //System.err.println("Cache was out of date");
427             gs.execCache.remove(path);
428         }
429         
430         FD fd = gs.open(this,path,RD_ONLY,0);
431         if(fd == null) throw new ErrnoException(ENOENT);
432         Seekable s = fd.seekable();        
433         if(s == null) throw new ErrnoException(EACCES);
434         
435         byte[] buf = new byte[4096];
436         
437         try {
438             int n = s.read(buf,0,buf.length);
439             if(n == -1) throw new ErrnoException(ENOEXEC);
440             
441             switch(buf[0]) {
442                 case '\177': // possible ELF
443                     if(n < 4) s.tryReadFully(buf,n,4-n);
444                     if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') return -ENOEXEC;
445                     s.seek(0);
446                     Class c = runtimeCompile(s);
447                     if(c == null) throw new ErrnoException(ENOEXEC);
448                     gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,c));
449                     return execClass(c,argv,envp);
450                 case '#':
451                     if(n == 1) {
452                         int n2 = s.read(buf,1,buf.length-1);
453                         if(n2 == -1) return -ENOEXEC;
454                         n += n2;
455                     }
456                     if(buf[1] != '!') return -ENOEXEC;
457                     int p = 2;
458                     n -= 2;
459                     OUTER: for(;;) {
460                         for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
461                             p += n;
462                         if(p == buf.length) break OUTER;
463                         n = s.read(buf,p,buf.length-p);
464                     }
465                     int arg;
466                     for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
467                     int cmdEnd = arg;
468                     while(arg < p && buf[arg] == ' ') arg++;
469                     String[] command = new String[] {
470                         new String(buf,2,cmdEnd),
471                         arg < p ? new String(buf,arg,p-arg) : null
472                     };
473                     gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,command));
474                     return execScript(path,command,argv,envp);
475                 default:
476                     return -ENOEXEC;
477             }
478         } catch(IOException e) {
479             return -EIO;
480         } finally {
481             fd.close();
482         }        
483     }
484     
485     public int execScript(String path, String[] command, String[] argv, String[] envp) throws ErrnoException {
486         String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
487         int p = command[0].lastIndexOf('/');
488         newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
489         p = 1;
490         if(command[1] != null) newArgv[p++] = command[1];
491         newArgv[p++] = "/" + path;
492         for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
493         return exec(command[0],newArgv,envp);
494     }
495     
496     public int execClass(Class c,String[] argv, String[] envp) {
497         try {
498             UnixRuntime r = (UnixRuntime) c.getDeclaredConstructor(new Class[]{Boolean.TYPE}).newInstance(new Object[]{Boolean.TRUE});
499             return exec(r,argv,envp);
500         } catch(Exception e) {
501             e.printStackTrace();
502             return -ENOEXEC;
503         }
504     }
505     
506     private int exec(UnixRuntime r, String[] argv, String[] envp) {     
507         //System.err.println("Execing " + r);
508         for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
509         r.fds = fds;
510         r.closeOnExec = closeOnExec;
511         // make sure this doesn't get messed with these since we didn't copy them
512         fds = null;
513         closeOnExec = null;
514         
515         r.gs = gs;
516         r.sm = sm;
517         r.cwd = cwd;
518         r.pid = pid;
519         r.parent = parent;
520         r.start(argv,envp);
521                 
522         state = EXECED;
523         execedRuntime = r;
524         
525         return 0;   
526     }
527     
528     static class Pipe {
529         private final byte[] pipebuf = new byte[PIPE_BUF*4];
530         private int readPos;
531         private int writePos;
532         
533         public final FD reader = new Reader();
534         public final FD writer = new Writer();
535         
536         public class Reader extends FD {
537             protected FStat _fstat() { return new SocketFStat(); }
538             public int read(byte[] buf, int off, int len) throws ErrnoException {
539                 if(len == 0) return 0;
540                 synchronized(Pipe.this) {
541                     while(writePos != -1 && readPos == writePos) {
542                         try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
543                     }
544                     if(writePos == -1) return 0; // eof
545                     len = Math.min(len,writePos-readPos);
546                     System.arraycopy(pipebuf,readPos,buf,off,len);
547                     readPos += len;
548                     if(readPos == writePos) Pipe.this.notify();
549                     return len;
550                 }
551             }
552             public int flags() { return O_RDONLY; }
553             public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
554         }
555         
556         public class Writer extends FD {   
557             protected FStat _fstat() { return new SocketFStat(); }
558             public int write(byte[] buf, int off, int len) throws ErrnoException {
559                 if(len == 0) return 0;
560                 synchronized(Pipe.this) {
561                     if(readPos == -1) throw new ErrnoException(EPIPE);
562                     if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
563                         // not enough space to atomicly write the data
564                         while(readPos != -1 && readPos != writePos) {
565                             try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
566                         }
567                         if(readPos == -1) throw new ErrnoException(EPIPE);
568                         readPos = writePos = 0;
569                     }
570                     len = Math.min(len,pipebuf.length - writePos);
571                     System.arraycopy(buf,off,pipebuf,writePos,len);
572                     if(readPos == writePos) Pipe.this.notify();
573                     writePos += len;
574                     return len;
575                 }
576             }
577             public int flags() { return O_WRONLY; }
578             public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
579         }
580     }
581     
582     private int sys_pipe(int addr) {
583         Pipe pipe = new Pipe();
584         
585         int fd1 = addFD(pipe.reader);
586         if(fd1 < 0) return -ENFILE;
587         int fd2 = addFD(pipe.writer);
588         if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
589         
590         try {
591             memWrite(addr,fd1);
592             memWrite(addr+4,fd2);
593         } catch(FaultException e) {
594             closeFD(fd1);
595             closeFD(fd2);
596             return -EFAULT;
597         }
598         return 0;
599     }
600     
601     private int sys_dup2(int oldd, int newd) {
602         if(oldd == newd) return 0;
603         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
604         if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
605         if(fds[oldd] == null) return -EBADFD;
606         if(fds[newd] != null) fds[newd].close();
607         fds[newd] = fds[oldd].dup();
608         return 0;
609     }
610     
611     private int sys_dup(int oldd) {
612         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
613         if(fds[oldd] == null) return -EBADFD;
614         FD fd = fds[oldd].dup();
615         int newd = addFD(fd);
616         if(newd < 0) { fd.close(); return -ENFILE; }
617         return newd;
618     }
619     
620     private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
621         FStat s = gs.stat(this,normalizePath(cstring(cstring)));
622         if(s == null) return -ENOENT;
623         return stat(s,addr);
624     }
625     
626     private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
627         FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
628         if(s == null) return -ENOENT;
629         return stat(s,addr);
630     }
631     
632     private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
633         gs.mkdir(this,normalizePath(cstring(cstring)),mode);
634         return 0;
635     }
636    
637     private int sys_unlink(int cstring) throws FaultException, ErrnoException {
638         gs.unlink(this,normalizePath(cstring(cstring)));
639         return 0;
640     }
641     
642     private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
643         byte[] b = getBytes(cwd);
644         if(size == 0) return -EINVAL;
645         if(size < b.length+2) return -ERANGE;
646         memset(addr,'/',1);
647         copyout(b,addr+1,b.length);
648         memset(addr+b.length+1,0,1);
649         return addr;
650     }
651     
652     private int sys_chdir(int addr) throws ErrnoException, FaultException {
653         String path = normalizePath(cstring(addr));
654         FStat st = gs.stat(this,path);
655         if(st == null) return -ENOENT;
656         if(st.type() != FStat.S_IFDIR) return -ENOTDIR;
657         cwd = path;
658         return 0;
659     }
660     
661     private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
662         count = Math.min(count,MAX_CHUNK);
663         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
664         if(fds[fdn] == null) return -EBADFD;
665         byte[] buf = byteBuf(count);
666         int n = fds[fdn].getdents(buf,0,count);
667         copyout(buf,addr,n);
668         return n;
669     }
670     
671     static class SocketFD extends FD {
672         public static final int TYPE_STREAM = 0;
673         public static final int TYPE_DGRAM = 1;
674         public static final int LISTEN = 2;
675         public int type() { return flags & 1; }
676         public boolean listen() { return (flags & 2) != 0; }
677         
678         int flags;
679         int options;
680         
681         Socket s;
682         ServerSocket ss;
683         DatagramSocket ds;
684         
685         InetAddress bindAddr;
686         int bindPort = -1;
687         InetAddress connectAddr;
688         int connectPort = -1;
689         
690         DatagramPacket dp;
691         InputStream is;
692         OutputStream os; 
693         
694         private static final byte[] EMPTY = new byte[0];
695         public SocketFD(int type) {
696                 flags = type;
697                 if(type == TYPE_DGRAM)
698                         dp = new DatagramPacket(EMPTY,0);
699         }
700         
701         public void setOptions() {
702             try {
703                 if(s != null && type() == TYPE_STREAM && !listen()) {
704                     Platform.socketSetKeepAlive(s,(options & SO_KEEPALIVE) != 0);
705                 }
706             } catch(SocketException e) {
707                 if(STDERR_DIAG) e.printStackTrace();
708             }
709         }
710         
711         public void _close() {
712             try {
713                if(s != null) s.close();
714                if(ss != null) ss.close();
715                if(ds != null) ds.close();
716             } catch(IOException e) {
717                 /* ignore */
718             }
719         }
720         
721         public int read(byte[] a, int off, int length) throws ErrnoException {
722             if(type() == TYPE_DGRAM) return recvfrom(a,off,length,null,null);
723             if(is == null) throw new ErrnoException(EPIPE);
724             try {
725                 int n = is.read(a,off,length);
726                 return n < 0 ? 0 : n;
727             } catch(IOException e) {
728                 throw new ErrnoException(EIO);
729             }
730         }    
731         
732         public int recvfrom(byte[] a, int off, int length, InetAddress[] sockAddr, int[] port) throws ErrnoException {
733                 if(type() == TYPE_STREAM) return read(a,off,length);
734                 
735                 if(off != 0) throw new IllegalArgumentException("off must be 0");
736                 dp.setData(a);
737                 dp.setLength(length);
738                 try {
739                         if(ds == null) ds = new DatagramSocket();
740                         ds.receive(dp);
741                 } catch(IOException e) {
742                         if(STDERR_DIAG) e.printStackTrace();
743                         throw new ErrnoException(EIO);
744                 }
745                 if(sockAddr != null) {
746                         sockAddr[0] = dp.getAddress();
747                         port[0] = dp.getPort();
748                 }
749                 return dp.getLength();
750         }
751         
752         public int write(byte[] a, int off, int length) throws ErrnoException {
753             if(type() == TYPE_DGRAM) return  sendto(a,off,length,null,-1);
754
755             if(os == null) throw new ErrnoException(EPIPE);
756             try {
757                 os.write(a,off,length);
758                 return length;
759             } catch(IOException e) {
760                 throw new ErrnoException(EIO);
761             }
762         }
763         
764         public int sendto(byte[] a, int off, int length, InetAddress destAddr, int destPort) throws ErrnoException {
765                 if(off != 0) throw new IllegalArgumentException("off must be 0");
766                 if(type() == TYPE_STREAM) return write(a,off,length);
767                 
768                 if(destAddr == null) {
769                         destAddr = connectAddr;
770                         destPort = connectPort;
771                         
772                         if(destAddr == null) throw new ErrnoException(ENOTCONN);
773                 }
774                 
775                 dp.setAddress(destAddr);
776                 dp.setPort(destPort);
777                 dp.setData(a);
778                 dp.setLength(length);
779                 
780                 try {
781                         if(ds == null) ds = new DatagramSocket();
782                         ds.send(dp);
783                 } catch(IOException e) {
784                         if(STDERR_DIAG) e.printStackTrace();
785                         if("Network is unreachable".equals(e.getMessage())) throw new ErrnoException(EHOSTUNREACH);
786                         throw new ErrnoException(EIO);
787                 }
788                 return dp.getLength();
789         }
790
791         public int flags() { return O_RDWR; }
792         public FStat _fstat() { return new SocketFStat(); }
793     }
794     
795     private int sys_socket(int domain, int type, int proto) {
796         if(domain != AF_INET || (type != SOCK_STREAM && type != SOCK_DGRAM)) return -EPROTONOSUPPORT;
797         return addFD(new SocketFD(type == SOCK_STREAM ? SocketFD.TYPE_STREAM : SocketFD.TYPE_DGRAM));
798     }
799     
800     private SocketFD getSocketFD(int fdn) throws ErrnoException {
801         if(fdn < 0 || fdn >= OPEN_MAX) throw new ErrnoException(EBADFD);
802         if(fds[fdn] == null) throw new ErrnoException(EBADFD);
803         if(!(fds[fdn] instanceof SocketFD)) throw new ErrnoException(ENOTSOCK);
804         
805         return (SocketFD) fds[fdn];
806     }
807     
808     private int sys_connect(int fdn, int addr, int namelen) throws ErrnoException, FaultException {
809         SocketFD fd = getSocketFD(fdn);
810         
811         if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
812         int word1 = memRead(addr);
813         if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
814         int port = word1 & 0xffff;
815         byte[] ip = new byte[4];
816         copyin(addr+4,ip,4);
817         
818         InetAddress inetAddr;
819         try {
820             inetAddr = Platform.inetAddressFromBytes(ip);
821         } catch(UnknownHostException e) {
822             return -EADDRNOTAVAIL;
823         }
824         
825         fd.connectAddr = inetAddr;
826         fd.connectPort = port;
827         
828         try {
829             switch(fd.type()) {
830                 case SocketFD.TYPE_STREAM: {
831                     Socket s = new Socket(inetAddr,port);
832                     fd.s = s;
833                     fd.setOptions();
834                     fd.is = s.getInputStream();
835                     fd.os = s.getOutputStream();
836                     break;
837                 }
838                 case SocketFD.TYPE_DGRAM:
839                     break;
840                 default:
841                     throw new Error("should never happen");
842             }
843         } catch(IOException e) {
844             return -ECONNREFUSED;
845         }
846         
847         return 0;
848     }
849     
850     private int sys_resolve_hostname(int chostname, int addr, int sizeAddr) throws FaultException {
851         String hostname = cstring(chostname);
852         int size = memRead(sizeAddr);
853         InetAddress[] inetAddrs;
854         try {
855             inetAddrs = InetAddress.getAllByName(hostname);
856         } catch(UnknownHostException e) {
857             return HOST_NOT_FOUND;
858         }
859         int count = min(size/4,inetAddrs.length);
860         for(int i=0;i<count;i++,addr+=4) {
861             byte[] b = inetAddrs[i].getAddress();
862             copyout(b,addr,4);
863         }
864         memWrite(sizeAddr,count*4);
865         return 0;
866     }
867     
868     private int sys_setsockopt(int fdn, int level, int name, int valaddr, int len) throws ReadFaultException, ErrnoException {
869         SocketFD fd = getSocketFD(fdn);
870         switch(level) {
871             case SOL_SOCKET:
872                 switch(name) {
873                     case SO_REUSEADDR:
874                     case SO_KEEPALIVE: {
875                         if(len != 4) return -EINVAL;
876                         int val = memRead(valaddr);
877                         if(val != 0) fd.options |= name;
878                         else fd.options &= ~name;
879                         fd.setOptions();
880                         return 0;
881                     }
882                     default:
883                         if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
884                         return -ENOPROTOOPT;
885                 }
886             default:
887                 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
888                 return -ENOPROTOOPT;
889         }                   
890     }
891     
892     private int sys_getsockopt(int fdn, int level, int name, int valaddr, int lenaddr) throws ErrnoException, FaultException {
893         SocketFD fd = getSocketFD(fdn);
894         switch(level) {
895             case SOL_SOCKET:
896                 switch(name) {
897                     case SO_REUSEADDR:
898                     case SO_KEEPALIVE: {
899                         int len = memRead(lenaddr);
900                         if(len < 4) return -EINVAL;
901                         int val = (fd.options & name) != 0 ? 1 : 0;
902                         memWrite(valaddr,val);
903                         memWrite(lenaddr,4);
904                         return 0;
905                     }
906                     default:
907                         if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
908                         return -ENOPROTOOPT;
909                 }
910             default:
911                 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
912                 return -ENOPROTOOPT;
913         } 
914     }
915     
916     private int sys_bind(int fdn, int addr, int namelen) throws FaultException, ErrnoException {
917         SocketFD fd = getSocketFD(fdn);
918         
919         if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
920         int word1 = memRead(addr);
921         if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
922         int port = word1 & 0xffff;
923         InetAddress inetAddr = null;
924         if(memRead(addr+4) != 0) {
925             byte[] ip = new byte[4];
926             copyin(addr+4,ip,4);
927         
928             try {
929                 inetAddr = Platform.inetAddressFromBytes(ip);
930             } catch(UnknownHostException e) {
931                 return -EADDRNOTAVAIL;
932             }
933         }
934         
935         switch(fd.type()) {
936             case SocketFD.TYPE_STREAM: {
937                 fd.bindAddr = inetAddr;
938                 fd.bindPort = port;
939                 return 0;
940             }
941             case SocketFD.TYPE_DGRAM: {
942                 if(fd.ds != null) fd.ds.close();
943                 try {
944                     fd.ds = inetAddr != null ? new DatagramSocket(port,inetAddr) : new DatagramSocket(port);
945                 } catch(IOException e) {
946                     return -EADDRINUSE;
947                 }
948                 return 0;
949             }
950             default:
951                 throw new Error("should never happen");
952         }
953     }
954     
955     private int sys_listen(int fdn, int backlog) throws ErrnoException {
956         SocketFD fd = getSocketFD(fdn);
957         if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
958         if(fd.ss != null || fd.s != null) return -EISCONN;
959         if(fd.bindPort < 0) return -EOPNOTSUPP;
960         
961         try {
962             fd.ss = new ServerSocket(fd.bindPort,backlog,fd.bindAddr);
963             fd.flags |= SocketFD.LISTEN;
964             return 0;
965         } catch(IOException e) {
966             return -EADDRINUSE;
967         }
968         
969     }
970     
971     private int sys_accept(int fdn, int addr, int lenaddr) throws ErrnoException, FaultException {
972         SocketFD fd = getSocketFD(fdn);
973         if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
974         if(!fd.listen()) return -EOPNOTSUPP;
975
976         int size = memRead(lenaddr);
977         
978         ServerSocket s = fd.ss;
979         Socket client;
980         try {
981             client = s.accept();
982         } catch(IOException e) {
983             return -EIO;
984         }
985         
986         if(size >= 8) {
987             memWrite(addr,(6 << 24) | (AF_INET << 16) | client.getPort());
988             byte[] b = client.getInetAddress().getAddress();
989             copyout(b,addr+4,4);
990             memWrite(lenaddr,8);
991         }
992         
993         SocketFD clientFD = new SocketFD(SocketFD.TYPE_STREAM);
994         clientFD.s = client;
995         try {
996             clientFD.is = client.getInputStream();
997             clientFD.os = client.getOutputStream();
998         } catch(IOException e) {
999             return -EIO;
1000         }
1001         int n = addFD(clientFD);
1002         if(n == -1) { clientFD.close(); return -ENFILE; }
1003         return n;
1004     }
1005     
1006     private int sys_shutdown(int fdn, int how) throws ErrnoException {
1007         SocketFD fd = getSocketFD(fdn);
1008         if(fd.type() != SocketFD.TYPE_STREAM || fd.listen()) return -EOPNOTSUPP;
1009         if(fd.s == null) return -ENOTCONN;
1010         
1011         Socket s = fd.s;
1012         
1013         try {
1014             if(how == SHUT_RD || how == SHUT_RDWR) Platform.socketHalfClose(s,false);
1015             if(how == SHUT_WR || how == SHUT_RDWR) Platform.socketHalfClose(s,true);
1016         } catch(IOException e) {
1017             return -EIO;
1018         }
1019         
1020         return 0;
1021     }
1022     
1023     private int sys_sendto(int fdn, int addr, int count, int flags, int destAddr, int socklen) throws ErrnoException,ReadFaultException {
1024         SocketFD fd = getSocketFD(fdn);
1025         if(flags != 0) throw new ErrnoException(EINVAL);
1026         
1027         int word1 = memRead(destAddr);
1028         if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
1029         int port = word1 & 0xffff;
1030         InetAddress inetAddr;
1031                 byte[] ip = new byte[4];
1032                 copyin(destAddr+4,ip,4);
1033                 try {
1034                         inetAddr = Platform.inetAddressFromBytes(ip);
1035                 } catch(UnknownHostException e) {
1036                         return -EADDRNOTAVAIL;
1037                 }
1038         
1039         count = Math.min(count,MAX_CHUNK);
1040         byte[] buf = byteBuf(count);
1041         copyin(addr,buf,count);
1042         try {
1043                 return fd.sendto(buf,0,count,inetAddr,port);
1044         } catch(ErrnoException e) {
1045                 if(e.errno == EPIPE) exit(128+13,true);
1046                 throw e;
1047         }
1048     }
1049     
1050     private int sys_recvfrom(int fdn, int addr, int count, int flags, int sourceAddr, int socklenAddr) throws ErrnoException, FaultException {
1051         SocketFD fd = getSocketFD(fdn);
1052         if(flags != 0) throw new ErrnoException(EINVAL);
1053         
1054         InetAddress[] inetAddr = sourceAddr == 0 ? null : new InetAddress[1];
1055         int[] port = sourceAddr == 0 ? null : new int[1];
1056         
1057         count = Math.min(count,MAX_CHUNK);
1058         byte[] buf = byteBuf(count);
1059         int n = fd.recvfrom(buf,0,count,inetAddr,port);
1060         copyout(buf,addr,n);
1061         
1062         if(sourceAddr != 0) {
1063                 memWrite(sourceAddr,(AF_INET << 16) | port[0]);
1064                 byte[] ip = inetAddr[0].getAddress();
1065                 copyout(ip,sourceAddr+4,4);
1066         }
1067         
1068         return n;
1069     }
1070     
1071     private int sys_select(int n, int readFDs, int writeFDs, int exceptFDs, int timevalAddr) throws ReadFaultException, ErrnoException {
1072         return -ENOSYS;
1073     }
1074     
1075     private static String hostName() {
1076         try {
1077             return InetAddress.getLocalHost().getHostName();
1078         } catch(UnknownHostException e) {
1079             return "darkstar";
1080         }
1081     }
1082     
1083     private int sys_sysctl(int nameaddr, int namelen, int oldp, int oldlenaddr, int newp, int newlen) throws FaultException {
1084         if(newp != 0) return -EPERM;
1085         if(namelen == 0) return -ENOENT;
1086         if(oldp == 0) return 0;
1087         
1088         Object o = null;
1089         switch(memRead(nameaddr)) {
1090             case CTL_KERN:
1091                 if(namelen != 2) break;
1092                 switch(memRead(nameaddr+4)) {
1093                     case KERN_OSTYPE: o = "NestedVM"; break;
1094                     case KERN_HOSTNAME: o = hostName(); break;
1095                     case KERN_OSRELEASE: o = VERSION; break;
1096                     case KERN_VERSION: o = "NestedVM Kernel Version " + VERSION; break;
1097                 }
1098                 break;
1099             case CTL_HW:
1100                 if(namelen != 2) break;
1101                 switch(memRead(nameaddr+4)) {
1102                     case HW_MACHINE: o = "NestedVM Virtual Machine"; break;
1103                 }
1104                 break;
1105         }
1106         if(o == null) return -ENOENT;
1107         int len = memRead(oldlenaddr);
1108         if(o instanceof String) {
1109             byte[] b = getNullTerminatedBytes((String)o);
1110             if(len < b.length) return -ENOMEM;
1111             len = b.length;
1112             copyout(b,oldp,len);
1113             memWrite(oldlenaddr,len);
1114         } else if(o instanceof Integer) {
1115             if(len < 4) return -ENOMEM;
1116             memWrite(oldp,((Integer)o).intValue());
1117         } else {
1118             throw new Error("should never happen");
1119         }
1120         return 0;
1121     }
1122     
1123     public static final class GlobalState {
1124         Hashtable execCache = new Hashtable();
1125         
1126         final UnixRuntime[] tasks;
1127         int nextPID = 1;
1128         
1129         private MP[] mps = new MP[0];
1130         private FS root;
1131         
1132         public GlobalState() { this(255); }
1133         public GlobalState(int maxProcs) { this(maxProcs,true); }
1134         public GlobalState(int maxProcs, boolean defaultMounts) {
1135             tasks = new UnixRuntime[maxProcs+1];
1136             if(defaultMounts) {
1137                 addMount("/",new HostFS());
1138                 addMount("/dev",new DevFS());
1139             }
1140         }
1141         
1142         static class MP implements Sort.Comparable {
1143             public MP(String path, FS fs) { this.path = path; this.fs = fs; }
1144             public String path;
1145             public FS fs;
1146             public int compareTo(Object o) {
1147                 if(!(o instanceof MP)) return 1;
1148                 return -path.compareTo(((MP)o).path);
1149             }
1150         }
1151         
1152         public synchronized FS getMount(String path) {
1153             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1154             if(path.equals("/")) return root;
1155             path  = path.substring(1);
1156             for(int i=0;i<mps.length;i++)
1157                 if(mps[i].path.equals(path)) return mps[i].fs;
1158             return null;
1159         }
1160         
1161         public synchronized void addMount(String path, FS fs) {
1162             if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
1163             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1164             
1165             if(fs.owner != null) fs.owner.removeMount(fs);
1166             fs.owner = this;
1167             
1168             if(path.equals("/")) { root = fs; fs.devno = 1; return; }
1169             path = path.substring(1);
1170             int oldLength = mps.length;
1171             MP[] newMPS = new MP[oldLength + 1];
1172             if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
1173             newMPS[oldLength] = new MP(path,fs);
1174             Sort.sort(newMPS);
1175             mps = newMPS;
1176             int highdevno = 0;
1177             for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
1178             fs.devno = highdevno + 2;
1179         }
1180         
1181         public synchronized void removeMount(FS fs) {
1182             for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
1183             throw new IllegalArgumentException("mount point doesn't exist");
1184         }
1185         
1186         public synchronized void removeMount(String path) {
1187             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1188             if(path.equals("/")) {
1189                 removeMount(-1);
1190             } else {
1191                 path = path.substring(1);
1192                 int p;
1193                 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
1194                 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
1195                 removeMount(p);
1196             }
1197         }
1198         
1199         private void removeMount(int index) {
1200             if(index == -1) { root.owner = null; root = null; return; }
1201             MP[] newMPS = new MP[mps.length - 1];
1202             System.arraycopy(mps,0,newMPS,0,index);
1203             System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
1204             mps = newMPS;
1205         }
1206         
1207         private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
1208             int pl = normalizedPath.length();
1209             if(pl != 0) {
1210                 MP[] list;
1211                 synchronized(this) { list = mps; }
1212                 for(int i=0;i<list.length;i++) {
1213                     MP mp = list[i];
1214                     int mpl = mp.path.length();
1215                     if(normalizedPath.startsWith(mp.path) && (pl == mpl || normalizedPath.charAt(mpl) == '/'))
1216                         return mp.fs.dispatch(op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
1217                 }
1218             }
1219             return root.dispatch(op,r,normalizedPath,arg1,arg2);
1220         }
1221         
1222         public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(FS.OPEN,r,path,flags,mode); }
1223         public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.STAT,r,path,0,0); }
1224         public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.LSTAT,r,path,0,0); }
1225         public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(FS.MKDIR,r,path,mode,0); }
1226         public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(FS.UNLINK,r,path,0,0); }
1227         
1228         private static class CacheEnt {
1229             public final long time;
1230             public final long size;
1231             public final Object o;
1232             public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
1233         }
1234     }
1235     
1236     public abstract static class FS {
1237         static final int OPEN = 1;
1238         static final int STAT = 2;
1239         static final int LSTAT = 3;
1240         static final int MKDIR = 4;
1241         static final int UNLINK = 5;
1242         
1243         GlobalState owner;
1244         int devno;
1245         
1246         Object dispatch(int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
1247             switch(op) {
1248                 case OPEN: return open(r,path,arg1,arg2);
1249                 case STAT: return stat(r,path);
1250                 case LSTAT: return lstat(r,path);
1251                 case MKDIR: mkdir(r,path,arg1); return null;
1252                 case UNLINK: unlink(r,path); return null;
1253                 default: throw new Error("should never happen");
1254             }
1255         }
1256         
1257         public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1258
1259         // If this returns null it'll be truned into an ENOENT
1260         public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
1261         // If this returns null it'll be turned into an ENOENT
1262         public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
1263         public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
1264         public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
1265     }
1266         
1267     // chroot support should go in here if it is ever implemented chroot support in here
1268     private String normalizePath(String path) {
1269         boolean absolute = path.startsWith("/");
1270         int cwdl = cwd.length();
1271         
1272         // NOTE: This isn't just a fast path, it handles cases the code below doesn't
1273         if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
1274             return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
1275         
1276         char[] in = new char[path.length()+1];
1277         char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
1278         int inp=0, outp=0;
1279         
1280         if(absolute) {
1281             do { inp++; } while(in[inp] == '/');
1282         } else if(cwdl != 0) {
1283             cwd.getChars(0,cwdl,out,0);
1284             outp = cwdl;
1285         }
1286
1287         path.getChars(0,path.length(),in,0);
1288         while(in[inp] != 0) {
1289             if(inp != 0) {
1290                 while(in[inp] != 0 && in[inp] != '/') { out[outp++] = in[inp++]; }
1291                 if(in[inp] == '\0') break;
1292                 while(in[inp] == '/') inp++;
1293             }
1294             
1295             // Just read a /
1296             if(in[inp] == '\0') break;
1297             if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
1298             // Just read a /.
1299             if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
1300             if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
1301                 // Just read a /..{$,/}
1302                 inp += 2;
1303                 if(outp > 0) outp--;
1304                 while(outp > 0 && out[outp] != '/') outp--;
1305                 //System.err.println("After ..: " + new String(out,0,outp));
1306                 continue;
1307             }
1308             // Just read a /.[^.] or /..[^/$]
1309             inp++;
1310             out[outp++] = '/';
1311             out[outp++] = '.';
1312         }
1313         if(outp > 0 && out[outp-1] == '/') outp--;
1314         //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
1315         return new String(out,0,outp);
1316     }
1317     
1318     FStat hostFStat(final File f, Object data) {
1319         boolean e = false;
1320         try {
1321             FileInputStream fis = new FileInputStream(f);
1322             switch(fis.read()) {
1323                 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
1324                 case '#': e = fis.read() == '!';
1325             }
1326             fis.close();
1327         } catch(IOException e2) { } 
1328         HostFS fs = (HostFS) data;
1329         final int inode = fs.inodes.get(f.getAbsolutePath());
1330         final int devno = fs.devno;
1331         return new HostFStat(f,e) {
1332             public int inode() { return inode; }
1333             public int dev() { return devno; }
1334         };
1335     }
1336
1337     FD hostFSDirFD(File f, Object _fs) {
1338         HostFS fs = (HostFS) _fs;
1339         return fs.new HostDirFD(f);
1340     }
1341     
1342     public static class HostFS extends FS {
1343         InodeCache inodes = new InodeCache(4000);
1344         protected File root;
1345         public File getRoot() { return root; }
1346         
1347         static File hostRootDir() {
1348             if(Platform.getProperty("nestedvm.root") != null) {
1349                 File f = new File(Platform.getProperty("nestedvm.root"));
1350                 if(f.isDirectory()) return f;
1351                 // fall through to case below
1352             }
1353             String cwd = Platform.getProperty("user.dir");
1354             File f = new File(cwd != null ? cwd : ".");
1355             if(!f.exists()) throw new Error("Couldn't get File for cwd");
1356             f = new File(f.getAbsolutePath());
1357             while(f.getParent() != null) f = new File(f.getParent());
1358             // This works around a bug in some versions of ClassPath
1359             if(f.getPath().length() == 0) f = new File("/");
1360             return f;
1361         }
1362         
1363         private File hostFile(String path) {
1364             char sep = File.separatorChar;
1365             if(sep != '/') {
1366                 char buf[] = path.toCharArray();
1367                 for(int i=0;i<buf.length;i++) {
1368                     char c = buf[i];
1369                     if(c == '/') buf[i] = sep;
1370                     else if(c == sep) buf[i] = '/';
1371                 }
1372                 path = new String(buf);
1373             }
1374             return new File(root,path);
1375         }
1376         
1377         public HostFS() { this(hostRootDir()); }
1378         public HostFS(String root) { this(new File(root)); }
1379         public HostFS(File root) { this.root = root; }
1380         
1381         
1382         public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1383             final File f = hostFile(path);
1384             return r.hostFSOpen(f,flags,mode,this);
1385         }
1386         
1387         public void unlink(UnixRuntime r, String path) throws ErrnoException {
1388             File f = hostFile(path);
1389             if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1390             if(!f.exists()) throw new ErrnoException(ENOENT);
1391             if(!f.delete()) throw new ErrnoException(EPERM);
1392         }
1393         
1394         public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1395             File f = hostFile(path);
1396             if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1397             if(!f.exists()) return null;
1398             return r.hostFStat(f,this);
1399         }
1400         
1401         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1402             File f = hostFile(path);
1403             if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1404             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1405             if(f.exists()) throw new ErrnoException(ENOTDIR);
1406             File parent = getParentFile(f);
1407             if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1408             if(!f.mkdir()) throw new ErrnoException(EIO);            
1409         }
1410         
1411         private static File getParentFile(File f) {
1412             String p = f.getParent();
1413             return p == null ? null : new File(f,p);
1414         }
1415         
1416         public class HostDirFD extends DirFD {
1417             private final File f;
1418             private final File[] children;
1419             public HostDirFD(File f) {
1420                 this.f = f;
1421                 String[] l = f.list();
1422                 children = new File[l.length];
1423                 for(int i=0;i<l.length;i++) children[i] = new File(f,l[i]);
1424             }
1425             public int size() { return children.length; }
1426             public String name(int n) { return children[n].getName(); }
1427             public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1428             public int parentInode() {
1429                 File parent = getParentFile(f);
1430                 // HACK: myInode() isn't really correct  if we're not the root
1431                 return parent == null ? myInode() : inodes.get(parent.getAbsolutePath());
1432             }
1433             public int myInode() { return inodes.get(f.getAbsolutePath()); }
1434             public int myDev() { return devno; } 
1435         }
1436     }
1437     
1438     private static void putInt(byte[] buf, int off, int n) {
1439         buf[off+0] = (byte)((n>>>24)&0xff);
1440         buf[off+1] = (byte)((n>>>16)&0xff);
1441         buf[off+2] = (byte)((n>>> 8)&0xff);
1442         buf[off+3] = (byte)((n>>> 0)&0xff);
1443     }
1444     
1445     public static abstract class DirFD extends FD {
1446         private int pos = -2;
1447         
1448         protected abstract int size();
1449         protected abstract String name(int n);
1450         protected abstract int inode(int n);
1451         protected abstract int myDev();
1452         protected abstract int parentInode();
1453         protected abstract int myInode();
1454         public int flags() { return O_RDONLY; }
1455
1456         public int getdents(byte[] buf, int off, int len) {
1457             int ooff = off;
1458             int ino;
1459             int reclen;
1460             OUTER: for(;len > 0 && pos < size();pos++){
1461                 switch(pos) {
1462                     case -2:
1463                     case -1:
1464                         ino = pos == -1 ? parentInode() : myInode();
1465                         if(ino == -1) continue;
1466                         reclen = 9 + (pos == -1 ? 2 : 1);
1467                         if(reclen > len) break OUTER;
1468                         buf[off+8] = '.';
1469                         if(pos == -1) buf[off+9] = '.';
1470                         break;
1471                     default: {
1472                         String f = name(pos);
1473                         byte[] fb = getBytes(f);
1474                         reclen = fb.length + 9;
1475                         if(reclen > len) break OUTER;
1476                         ino = inode(pos);
1477                         System.arraycopy(fb,0,buf,off+8,fb.length);
1478                     }
1479                 }
1480                 buf[off+reclen-1] = 0; // null terminate
1481                 reclen = (reclen + 3) & ~3; // add padding
1482                 putInt(buf,off,reclen);
1483                 putInt(buf,off+4,ino);
1484                 off += reclen;
1485                 len -= reclen;    
1486             }
1487             return off-ooff;
1488         }
1489         
1490         protected FStat _fstat() {
1491             return new FStat() { 
1492                 public int type() { return S_IFDIR; }
1493                 public int inode() { return myInode(); }
1494                 public int dev() { return myDev(); }
1495             };
1496         }
1497     }
1498         
1499     public static class DevFS extends FS {
1500         private static final int ROOT_INODE = 1;
1501         private static final int NULL_INODE = 2;
1502         private static final int ZERO_INODE = 3;
1503         private static final int FD_INODE = 4;
1504         private static final int FD_INODES = 32;
1505         
1506         private abstract class DevFStat extends FStat {
1507             public int dev() { return devno; }
1508             public int mode() { return 0666; }
1509             public int type() { return S_IFCHR; }
1510             public int nlink() { return 1; }
1511             public abstract int inode();
1512         }
1513         
1514         private abstract class DevDirFD extends DirFD {
1515             public int myDev() { return devno; }
1516         }
1517         
1518         private FD devZeroFD = new FD() {
1519             public int read(byte[] a, int off, int length) { 
1520                 /*Arrays.fill(a,off,off+length,(byte)0);*/
1521                 for(int i=off;i<off+length;i++) a[i] = 0;
1522                 return length;
1523             }
1524             public int write(byte[] a, int off, int length) { return length; }
1525             public int seek(int n, int whence) { return 0; }
1526             public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1527             public int flags() { return O_RDWR; }
1528         };
1529         private FD devNullFD = new FD() {
1530             public int read(byte[] a, int off, int length) { return 0; }
1531             public int write(byte[] a, int off, int length) { return length; }
1532             public int seek(int n, int whence) { return 0; }
1533             public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1534             public int flags() { return O_RDWR; }
1535         }; 
1536         
1537         public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1538             if(path.equals("null")) return devNullFD;
1539             if(path.equals("zero")) return devZeroFD;
1540             if(path.startsWith("fd/")) {
1541                 int n;
1542                 try {
1543                     n = Integer.parseInt(path.substring(4));
1544                 } catch(NumberFormatException e) {
1545                     return null;
1546                 }
1547                 if(n < 0 || n >= OPEN_MAX) return null;
1548                 if(r.fds[n] == null) return null;
1549                 return r.fds[n].dup();
1550             }
1551             if(path.equals("fd")) {
1552                 int count=0;
1553                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1554                 final int[] files = new int[count];
1555                 count = 0;
1556                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1557                 return new DevDirFD() {
1558                     public int myInode() { return FD_INODE; }
1559                     public int parentInode() { return ROOT_INODE; }
1560                     public int inode(int n) { return FD_INODES + n; }
1561                     public String name(int n) { return Integer.toString(files[n]); }
1562                     public int size() { return files.length; }
1563                 };
1564             }
1565             if(path.equals("")) {
1566                 return new DevDirFD() {
1567                     public int myInode() { return ROOT_INODE; }
1568                     // HACK: We don't have any clean way to get the parent inode
1569                     public int parentInode() { return ROOT_INODE; }
1570                     public int inode(int n) {
1571                         switch(n) {
1572                             case 0: return NULL_INODE;
1573                             case 1: return ZERO_INODE;
1574                             case 2: return FD_INODE;
1575                             default: return -1;
1576                         }
1577                     }
1578                     
1579                     public String name(int n) {
1580                         switch(n) {
1581                             case 0: return "null";
1582                             case 1: return "zero";
1583                             case 2: return "fd";
1584                             default: return null;
1585                         }
1586                     }
1587                     public int size() { return 3; }
1588                 };
1589             }
1590             return null;
1591         }
1592         
1593         public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1594             if(path.equals("null")) return devNullFD.fstat();
1595             if(path.equals("zero")) return devZeroFD.fstat();            
1596             if(path.startsWith("fd/")) {
1597                 int n;
1598                 try {
1599                     n = Integer.parseInt(path.substring(3));
1600                 } catch(NumberFormatException e) {
1601                     return null;
1602                 }
1603                 if(n < 0 || n >= OPEN_MAX) return null;
1604                 if(r.fds[n] == null) return null;
1605                 return r.fds[n].fstat();
1606             }
1607             if(path.equals("fd")) return new FStat() { public int inode() { return FD_INODE; }   public int dev() { return devno; } public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1608             if(path.equals(""))   return new FStat() { public int inode() { return ROOT_INODE; } public int dev() { return devno; } public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1609             return null;
1610         }
1611         
1612         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1613         public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }
1614     }    
1615 }