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