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