include sourcename in runtime compiled binaries, more gc friendly runtime compiler
[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,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, String sourceName) 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,maxinsnpermethod=256,lessconstants",sourceName});
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                     if(STDERR_DIAG) System.err.println("Running RuntimeCompiler for " + path);
488                     Class c = runtimeCompile(s,path);
489                     if(STDERR_DIAG) System.err.println("RuntimeCompiler finished for " + path);
490                     if(c == null) throw new ErrnoException(ENOEXEC);
491                     gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,c));
492                     return execClass(c,argv,envp);
493                 case '#':
494                     if(n == 1) {
495                         int n2 = s.read(buf,1,buf.length-1);
496                         if(n2 == -1) return -ENOEXEC;
497                         n += n2;
498                     }
499                     if(buf[1] != '!') return -ENOEXEC;
500                     int p = 2;
501                     n -= 2;
502                     OUTER: for(;;) {
503                         for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
504                             p += n;
505                         if(p == buf.length) break OUTER;
506                         n = s.read(buf,p,buf.length-p);
507                     }
508                     int arg;
509                     for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
510                     int cmdEnd = arg;
511                     while(arg < p && buf[arg] == ' ') arg++;
512                     String[] command = new String[] {
513                         new String(buf,2,cmdEnd),
514                         arg < p ? new String(buf,arg,p-arg) : null
515                     };
516                     gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,command));
517                     return execScript(path,command,argv,envp);
518                 default:
519                     return -ENOEXEC;
520             }
521         } catch(IOException e) {
522             return -EIO;
523         } finally {
524             fd.close();
525         }        
526     }
527     
528     public int execScript(String path, String[] command, String[] argv, String[] envp) throws ErrnoException {
529         String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
530         int p = command[0].lastIndexOf('/');
531         newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
532         p = 1;
533         if(command[1] != null) newArgv[p++] = command[1];
534         newArgv[p++] = "/" + path;
535         for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
536         return exec(command[0],newArgv,envp);
537     }
538     
539     public int execClass(Class c,String[] argv, String[] envp) {
540         try {
541             UnixRuntime r = (UnixRuntime) c.getDeclaredConstructor(new Class[]{Boolean.TYPE}).newInstance(new Object[]{Boolean.TRUE});
542             return exec(r,argv,envp);
543         } catch(Exception e) {
544             e.printStackTrace();
545             return -ENOEXEC;
546         }
547     }
548     
549     private int exec(UnixRuntime r, String[] argv, String[] envp) {     
550         //System.err.println("Execing " + r);
551         for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
552         r.fds = fds;
553         r.closeOnExec = closeOnExec;
554         // make sure this doesn't get messed with these since we didn't copy them
555         fds = null;
556         closeOnExec = null;
557         
558         r.gs = gs;
559         r.sm = sm;
560         r.cwd = cwd;
561         r.pid = pid;
562         r.parent = parent;
563         r.start(argv,envp);
564                 
565         state = EXECED;
566         execedRuntime = r;
567         
568         return 0;   
569     }
570     
571     static class Pipe {
572         private final byte[] pipebuf = new byte[PIPE_BUF*4];
573         private int readPos;
574         private int writePos;
575         
576         public final FD reader = new Reader();
577         public final FD writer = new Writer();
578         
579         public class Reader extends FD {
580             protected FStat _fstat() { return new SocketFStat(); }
581             public int read(byte[] buf, int off, int len) throws ErrnoException {
582                 if(len == 0) return 0;
583                 synchronized(Pipe.this) {
584                     while(writePos != -1 && readPos == writePos) {
585                         try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
586                     }
587                     if(writePos == -1) return 0; // eof
588                     len = Math.min(len,writePos-readPos);
589                     System.arraycopy(pipebuf,readPos,buf,off,len);
590                     readPos += len;
591                     if(readPos == writePos) Pipe.this.notify();
592                     return len;
593                 }
594             }
595             public int flags() { return O_RDONLY; }
596             public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
597         }
598         
599         public class Writer extends FD {   
600             protected FStat _fstat() { return new SocketFStat(); }
601             public int write(byte[] buf, int off, int len) throws ErrnoException {
602                 if(len == 0) return 0;
603                 synchronized(Pipe.this) {
604                     if(readPos == -1) throw new ErrnoException(EPIPE);
605                     if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
606                         // not enough space to atomicly write the data
607                         while(readPos != -1 && readPos != writePos) {
608                             try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
609                         }
610                         if(readPos == -1) throw new ErrnoException(EPIPE);
611                         readPos = writePos = 0;
612                     }
613                     len = Math.min(len,pipebuf.length - writePos);
614                     System.arraycopy(buf,off,pipebuf,writePos,len);
615                     if(readPos == writePos) Pipe.this.notify();
616                     writePos += len;
617                     return len;
618                 }
619             }
620             public int flags() { return O_WRONLY; }
621             public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
622         }
623     }
624     
625     private int sys_pipe(int addr) {
626         Pipe pipe = new Pipe();
627         
628         int fd1 = addFD(pipe.reader);
629         if(fd1 < 0) return -ENFILE;
630         int fd2 = addFD(pipe.writer);
631         if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
632         
633         try {
634             memWrite(addr,fd1);
635             memWrite(addr+4,fd2);
636         } catch(FaultException e) {
637             closeFD(fd1);
638             closeFD(fd2);
639             return -EFAULT;
640         }
641         return 0;
642     }
643     
644     private int sys_dup2(int oldd, int newd) {
645         if(oldd == newd) return 0;
646         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
647         if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
648         if(fds[oldd] == null) return -EBADFD;
649         if(fds[newd] != null) fds[newd].close();
650         fds[newd] = fds[oldd].dup();
651         return 0;
652     }
653     
654     private int sys_dup(int oldd) {
655         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
656         if(fds[oldd] == null) return -EBADFD;
657         FD fd = fds[oldd].dup();
658         int newd = addFD(fd);
659         if(newd < 0) { fd.close(); return -ENFILE; }
660         return newd;
661     }
662     
663     private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
664         FStat s = gs.stat(this,normalizePath(cstring(cstring)));
665         if(s == null) return -ENOENT;
666         return stat(s,addr);
667     }
668     
669     private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
670         FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
671         if(s == null) return -ENOENT;
672         return stat(s,addr);
673     }
674     
675     private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
676         gs.mkdir(this,normalizePath(cstring(cstring)),mode);
677         return 0;
678     }
679    
680     private int sys_unlink(int cstring) throws FaultException, ErrnoException {
681         gs.unlink(this,normalizePath(cstring(cstring)));
682         return 0;
683     }
684     
685     private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
686         byte[] b = getBytes(cwd);
687         if(size == 0) return -EINVAL;
688         if(size < b.length+2) return -ERANGE;
689         memset(addr,'/',1);
690         copyout(b,addr+1,b.length);
691         memset(addr+b.length+1,0,1);
692         return addr;
693     }
694     
695     private int sys_chdir(int addr) throws ErrnoException, FaultException {
696         String path = normalizePath(cstring(addr));
697         FStat st = gs.stat(this,path);
698         if(st == null) return -ENOENT;
699         if(st.type() != FStat.S_IFDIR) return -ENOTDIR;
700         cwd = path;
701         return 0;
702     }
703     
704     private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
705         count = Math.min(count,MAX_CHUNK);
706         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
707         if(fds[fdn] == null) return -EBADFD;
708         byte[] buf = byteBuf(count);
709         int n = fds[fdn].getdents(buf,0,count);
710         copyout(buf,addr,n);
711         return n;
712     }
713     
714     static class SocketFD extends FD {
715         public static final int TYPE_STREAM = 0;
716         public static final int TYPE_DGRAM = 1;
717         public static final int LISTEN = 2;
718         public int type() { return flags & 1; }
719         public boolean listen() { return (flags & 2) != 0; }
720         
721         int flags;
722         int options;
723         
724         Socket s;
725         ServerSocket ss;
726         DatagramSocket ds;
727         
728         InetAddress bindAddr;
729         int bindPort = -1;
730         InetAddress connectAddr;
731         int connectPort = -1;
732         
733         DatagramPacket dp;
734         InputStream is;
735         OutputStream os; 
736         
737         private static final byte[] EMPTY = new byte[0];
738         public SocketFD(int type) {
739                 flags = type;
740                 if(type == TYPE_DGRAM)
741                         dp = new DatagramPacket(EMPTY,0);
742         }
743         
744         public void setOptions() {
745             try {
746                 if(s != null && type() == TYPE_STREAM && !listen()) {
747                     Platform.socketSetKeepAlive(s,(options & SO_KEEPALIVE) != 0);
748                 }
749             } catch(SocketException e) {
750                 if(STDERR_DIAG) e.printStackTrace();
751             }
752         }
753         
754         public void _close() {
755             try {
756                if(s != null) s.close();
757                if(ss != null) ss.close();
758                if(ds != null) ds.close();
759             } catch(IOException e) {
760                 /* ignore */
761             }
762         }
763         
764         public int read(byte[] a, int off, int length) throws ErrnoException {
765             if(type() == TYPE_DGRAM) return recvfrom(a,off,length,null,null);
766             if(is == null) throw new ErrnoException(EPIPE);
767             try {
768                 int n = is.read(a,off,length);
769                 return n < 0 ? 0 : n;
770             } catch(IOException e) {
771                 throw new ErrnoException(EIO);
772             }
773         }    
774         
775         public int recvfrom(byte[] a, int off, int length, InetAddress[] sockAddr, int[] port) throws ErrnoException {
776                 if(type() == TYPE_STREAM) return read(a,off,length);
777                 
778                 if(off != 0) throw new IllegalArgumentException("off must be 0");
779                 dp.setData(a);
780                 dp.setLength(length);
781                 try {
782                         if(ds == null) ds = new DatagramSocket();
783                         ds.receive(dp);
784                 } catch(IOException e) {
785                         if(STDERR_DIAG) e.printStackTrace();
786                         throw new ErrnoException(EIO);
787                 }
788                 if(sockAddr != null) {
789                         sockAddr[0] = dp.getAddress();
790                         port[0] = dp.getPort();
791                 }
792                 return dp.getLength();
793         }
794         
795         public int write(byte[] a, int off, int length) throws ErrnoException {
796             if(type() == TYPE_DGRAM) return  sendto(a,off,length,null,-1);
797
798             if(os == null) throw new ErrnoException(EPIPE);
799             try {
800                 os.write(a,off,length);
801                 return length;
802             } catch(IOException e) {
803                 throw new ErrnoException(EIO);
804             }
805         }
806         
807         public int sendto(byte[] a, int off, int length, InetAddress destAddr, int destPort) throws ErrnoException {
808                 if(off != 0) throw new IllegalArgumentException("off must be 0");
809                 if(type() == TYPE_STREAM) return write(a,off,length);
810                 
811                 if(destAddr == null) {
812                         destAddr = connectAddr;
813                         destPort = connectPort;
814                         
815                         if(destAddr == null) throw new ErrnoException(ENOTCONN);
816                 }
817                 
818                 dp.setAddress(destAddr);
819                 dp.setPort(destPort);
820                 dp.setData(a);
821                 dp.setLength(length);
822                 
823                 try {
824                         if(ds == null) ds = new DatagramSocket();
825                         ds.send(dp);
826                 } catch(IOException e) {
827                         if(STDERR_DIAG) e.printStackTrace();
828                         if("Network is unreachable".equals(e.getMessage())) throw new ErrnoException(EHOSTUNREACH);
829                         throw new ErrnoException(EIO);
830                 }
831                 return dp.getLength();
832         }
833
834         public int flags() { return O_RDWR; }
835         public FStat _fstat() { return new SocketFStat(); }
836     }
837     
838     private int sys_socket(int domain, int type, int proto) {
839         if(domain != AF_INET || (type != SOCK_STREAM && type != SOCK_DGRAM)) return -EPROTONOSUPPORT;
840         return addFD(new SocketFD(type == SOCK_STREAM ? SocketFD.TYPE_STREAM : SocketFD.TYPE_DGRAM));
841     }
842     
843     private SocketFD getSocketFD(int fdn) throws ErrnoException {
844         if(fdn < 0 || fdn >= OPEN_MAX) throw new ErrnoException(EBADFD);
845         if(fds[fdn] == null) throw new ErrnoException(EBADFD);
846         if(!(fds[fdn] instanceof SocketFD)) throw new ErrnoException(ENOTSOCK);
847         
848         return (SocketFD) fds[fdn];
849     }
850     
851     private int sys_connect(int fdn, int addr, int namelen) throws ErrnoException, FaultException {
852         SocketFD fd = getSocketFD(fdn);
853         
854         if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
855         int word1 = memRead(addr);
856         if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
857         int port = word1 & 0xffff;
858         byte[] ip = new byte[4];
859         copyin(addr+4,ip,4);
860         
861         InetAddress inetAddr;
862         try {
863             inetAddr = Platform.inetAddressFromBytes(ip);
864         } catch(UnknownHostException e) {
865             return -EADDRNOTAVAIL;
866         }
867         
868         fd.connectAddr = inetAddr;
869         fd.connectPort = port;
870         
871         try {
872             switch(fd.type()) {
873                 case SocketFD.TYPE_STREAM: {
874                     Socket s = new Socket(inetAddr,port);
875                     fd.s = s;
876                     fd.setOptions();
877                     fd.is = s.getInputStream();
878                     fd.os = s.getOutputStream();
879                     break;
880                 }
881                 case SocketFD.TYPE_DGRAM:
882                     break;
883                 default:
884                     throw new Error("should never happen");
885             }
886         } catch(IOException e) {
887             return -ECONNREFUSED;
888         }
889         
890         return 0;
891     }
892     
893     private int sys_resolve_hostname(int chostname, int addr, int sizeAddr) throws FaultException {
894         String hostname = cstring(chostname);
895         int size = memRead(sizeAddr);
896         InetAddress[] inetAddrs;
897         try {
898             inetAddrs = InetAddress.getAllByName(hostname);
899         } catch(UnknownHostException e) {
900             return HOST_NOT_FOUND;
901         }
902         int count = min(size/4,inetAddrs.length);
903         for(int i=0;i<count;i++,addr+=4) {
904             byte[] b = inetAddrs[i].getAddress();
905             copyout(b,addr,4);
906         }
907         memWrite(sizeAddr,count*4);
908         return 0;
909     }
910     
911     private int sys_setsockopt(int fdn, int level, int name, int valaddr, int len) throws ReadFaultException, ErrnoException {
912         SocketFD fd = getSocketFD(fdn);
913         switch(level) {
914             case SOL_SOCKET:
915                 switch(name) {
916                     case SO_REUSEADDR:
917                     case SO_KEEPALIVE: {
918                         if(len != 4) return -EINVAL;
919                         int val = memRead(valaddr);
920                         if(val != 0) fd.options |= name;
921                         else fd.options &= ~name;
922                         fd.setOptions();
923                         return 0;
924                     }
925                     default:
926                         if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
927                         return -ENOPROTOOPT;
928                 }
929             default:
930                 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
931                 return -ENOPROTOOPT;
932         }                   
933     }
934     
935     private int sys_getsockopt(int fdn, int level, int name, int valaddr, int lenaddr) throws ErrnoException, FaultException {
936         SocketFD fd = getSocketFD(fdn);
937         switch(level) {
938             case SOL_SOCKET:
939                 switch(name) {
940                     case SO_REUSEADDR:
941                     case SO_KEEPALIVE: {
942                         int len = memRead(lenaddr);
943                         if(len < 4) return -EINVAL;
944                         int val = (fd.options & name) != 0 ? 1 : 0;
945                         memWrite(valaddr,val);
946                         memWrite(lenaddr,4);
947                         return 0;
948                     }
949                     default:
950                         if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
951                         return -ENOPROTOOPT;
952                 }
953             default:
954                 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
955                 return -ENOPROTOOPT;
956         } 
957     }
958     
959     private int sys_bind(int fdn, int addr, int namelen) throws FaultException, ErrnoException {
960         SocketFD fd = getSocketFD(fdn);
961         
962         if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
963         int word1 = memRead(addr);
964         if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
965         int port = word1 & 0xffff;
966         InetAddress inetAddr = null;
967         if(memRead(addr+4) != 0) {
968             byte[] ip = new byte[4];
969             copyin(addr+4,ip,4);
970         
971             try {
972                 inetAddr = Platform.inetAddressFromBytes(ip);
973             } catch(UnknownHostException e) {
974                 return -EADDRNOTAVAIL;
975             }
976         }
977         
978         switch(fd.type()) {
979             case SocketFD.TYPE_STREAM: {
980                 fd.bindAddr = inetAddr;
981                 fd.bindPort = port;
982                 return 0;
983             }
984             case SocketFD.TYPE_DGRAM: {
985                 if(fd.ds != null) fd.ds.close();
986                 try {
987                     fd.ds = inetAddr != null ? new DatagramSocket(port,inetAddr) : new DatagramSocket(port);
988                 } catch(IOException e) {
989                     return -EADDRINUSE;
990                 }
991                 return 0;
992             }
993             default:
994                 throw new Error("should never happen");
995         }
996     }
997     
998     private int sys_listen(int fdn, int backlog) throws ErrnoException {
999         SocketFD fd = getSocketFD(fdn);
1000         if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
1001         if(fd.ss != null || fd.s != null) return -EISCONN;
1002         if(fd.bindPort < 0) return -EOPNOTSUPP;
1003         
1004         try {
1005             fd.ss = new ServerSocket(fd.bindPort,backlog,fd.bindAddr);
1006             fd.flags |= SocketFD.LISTEN;
1007             return 0;
1008         } catch(IOException e) {
1009             return -EADDRINUSE;
1010         }
1011         
1012     }
1013     
1014     private int sys_accept(int fdn, int addr, int lenaddr) throws ErrnoException, FaultException {
1015         SocketFD fd = getSocketFD(fdn);
1016         if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
1017         if(!fd.listen()) return -EOPNOTSUPP;
1018
1019         int size = memRead(lenaddr);
1020         
1021         ServerSocket s = fd.ss;
1022         Socket client;
1023         try {
1024             client = s.accept();
1025         } catch(IOException e) {
1026             return -EIO;
1027         }
1028         
1029         if(size >= 8) {
1030             memWrite(addr,(6 << 24) | (AF_INET << 16) | client.getPort());
1031             byte[] b = client.getInetAddress().getAddress();
1032             copyout(b,addr+4,4);
1033             memWrite(lenaddr,8);
1034         }
1035         
1036         SocketFD clientFD = new SocketFD(SocketFD.TYPE_STREAM);
1037         clientFD.s = client;
1038         try {
1039             clientFD.is = client.getInputStream();
1040             clientFD.os = client.getOutputStream();
1041         } catch(IOException e) {
1042             return -EIO;
1043         }
1044         int n = addFD(clientFD);
1045         if(n == -1) { clientFD.close(); return -ENFILE; }
1046         return n;
1047     }
1048     
1049     private int sys_shutdown(int fdn, int how) throws ErrnoException {
1050         SocketFD fd = getSocketFD(fdn);
1051         if(fd.type() != SocketFD.TYPE_STREAM || fd.listen()) return -EOPNOTSUPP;
1052         if(fd.s == null) return -ENOTCONN;
1053         
1054         Socket s = fd.s;
1055         
1056         try {
1057             if(how == SHUT_RD || how == SHUT_RDWR) Platform.socketHalfClose(s,false);
1058             if(how == SHUT_WR || how == SHUT_RDWR) Platform.socketHalfClose(s,true);
1059         } catch(IOException e) {
1060             return -EIO;
1061         }
1062         
1063         return 0;
1064     }
1065     
1066     private int sys_sendto(int fdn, int addr, int count, int flags, int destAddr, int socklen) throws ErrnoException,ReadFaultException {
1067         SocketFD fd = getSocketFD(fdn);
1068         if(flags != 0) throw new ErrnoException(EINVAL);
1069         
1070         int word1 = memRead(destAddr);
1071         if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
1072         int port = word1 & 0xffff;
1073         InetAddress inetAddr;
1074                 byte[] ip = new byte[4];
1075                 copyin(destAddr+4,ip,4);
1076                 try {
1077                         inetAddr = Platform.inetAddressFromBytes(ip);
1078                 } catch(UnknownHostException e) {
1079                         return -EADDRNOTAVAIL;
1080                 }
1081         
1082         count = Math.min(count,MAX_CHUNK);
1083         byte[] buf = byteBuf(count);
1084         copyin(addr,buf,count);
1085         try {
1086                 return fd.sendto(buf,0,count,inetAddr,port);
1087         } catch(ErrnoException e) {
1088                 if(e.errno == EPIPE) exit(128+13,true);
1089                 throw e;
1090         }
1091     }
1092     
1093     private int sys_recvfrom(int fdn, int addr, int count, int flags, int sourceAddr, int socklenAddr) throws ErrnoException, FaultException {
1094         SocketFD fd = getSocketFD(fdn);
1095         if(flags != 0) throw new ErrnoException(EINVAL);
1096         
1097         InetAddress[] inetAddr = sourceAddr == 0 ? null : new InetAddress[1];
1098         int[] port = sourceAddr == 0 ? null : new int[1];
1099         
1100         count = Math.min(count,MAX_CHUNK);
1101         byte[] buf = byteBuf(count);
1102         int n = fd.recvfrom(buf,0,count,inetAddr,port);
1103         copyout(buf,addr,n);
1104         
1105         if(sourceAddr != 0) {
1106                 memWrite(sourceAddr,(AF_INET << 16) | port[0]);
1107                 byte[] ip = inetAddr[0].getAddress();
1108                 copyout(ip,sourceAddr+4,4);
1109         }
1110         
1111         return n;
1112     }
1113     
1114     private int sys_select(int n, int readFDs, int writeFDs, int exceptFDs, int timevalAddr) throws ReadFaultException, ErrnoException {
1115         return -ENOSYS;
1116     }
1117     
1118     private static String hostName() {
1119         try {
1120             return InetAddress.getLocalHost().getHostName();
1121         } catch(UnknownHostException e) {
1122             return "darkstar";
1123         }
1124     }
1125     
1126     private int sys_sysctl(int nameaddr, int namelen, int oldp, int oldlenaddr, int newp, int newlen) throws FaultException {
1127         if(newp != 0) return -EPERM;
1128         if(namelen == 0) return -ENOENT;
1129         if(oldp == 0) return 0;
1130         
1131         Object o = null;
1132         switch(memRead(nameaddr)) {
1133             case CTL_KERN:
1134                 if(namelen != 2) break;
1135                 switch(memRead(nameaddr+4)) {
1136                     case KERN_OSTYPE: o = "NestedVM"; break;
1137                     case KERN_HOSTNAME: o = hostName(); break;
1138                     case KERN_OSRELEASE: o = VERSION; break;
1139                     case KERN_VERSION: o = "NestedVM Kernel Version " + VERSION; break;
1140                 }
1141                 break;
1142             case CTL_HW:
1143                 if(namelen != 2) break;
1144                 switch(memRead(nameaddr+4)) {
1145                     case HW_MACHINE: o = "NestedVM Virtual Machine"; break;
1146                 }
1147                 break;
1148         }
1149         if(o == null) return -ENOENT;
1150         int len = memRead(oldlenaddr);
1151         if(o instanceof String) {
1152             byte[] b = getNullTerminatedBytes((String)o);
1153             if(len < b.length) return -ENOMEM;
1154             len = b.length;
1155             copyout(b,oldp,len);
1156             memWrite(oldlenaddr,len);
1157         } else if(o instanceof Integer) {
1158             if(len < 4) return -ENOMEM;
1159             memWrite(oldp,((Integer)o).intValue());
1160         } else {
1161             throw new Error("should never happen");
1162         }
1163         return 0;
1164     }
1165     
1166     public static final class GlobalState {
1167         Hashtable execCache = new Hashtable();
1168         
1169         final UnixRuntime[] tasks;
1170         int nextPID = 1;
1171         
1172         private MP[] mps = new MP[0];
1173         private FS root;
1174         
1175         public GlobalState() { this(255); }
1176         public GlobalState(int maxProcs) { this(maxProcs,true); }
1177         public GlobalState(int maxProcs, boolean defaultMounts) {
1178             tasks = new UnixRuntime[maxProcs+1];
1179             if(defaultMounts) {
1180                 addMount("/",new HostFS());
1181                 addMount("/dev",new DevFS());
1182             }
1183         }
1184         
1185         static class MP implements Sort.Comparable {
1186             public MP(String path, FS fs) { this.path = path; this.fs = fs; }
1187             public String path;
1188             public FS fs;
1189             public int compareTo(Object o) {
1190                 if(!(o instanceof MP)) return 1;
1191                 return -path.compareTo(((MP)o).path);
1192             }
1193         }
1194         
1195         public synchronized FS getMount(String path) {
1196             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1197             if(path.equals("/")) return root;
1198             path  = path.substring(1);
1199             for(int i=0;i<mps.length;i++)
1200                 if(mps[i].path.equals(path)) return mps[i].fs;
1201             return null;
1202         }
1203         
1204         public synchronized void addMount(String path, FS fs) {
1205             if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
1206             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1207             
1208             if(fs.owner != null) fs.owner.removeMount(fs);
1209             fs.owner = this;
1210             
1211             if(path.equals("/")) { root = fs; fs.devno = 1; return; }
1212             path = path.substring(1);
1213             int oldLength = mps.length;
1214             MP[] newMPS = new MP[oldLength + 1];
1215             if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
1216             newMPS[oldLength] = new MP(path,fs);
1217             Sort.sort(newMPS);
1218             mps = newMPS;
1219             int highdevno = 0;
1220             for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
1221             fs.devno = highdevno + 2;
1222         }
1223         
1224         public synchronized void removeMount(FS fs) {
1225             for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
1226             throw new IllegalArgumentException("mount point doesn't exist");
1227         }
1228         
1229         public synchronized void removeMount(String path) {
1230             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1231             if(path.equals("/")) {
1232                 removeMount(-1);
1233             } else {
1234                 path = path.substring(1);
1235                 int p;
1236                 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
1237                 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
1238                 removeMount(p);
1239             }
1240         }
1241         
1242         private void removeMount(int index) {
1243             if(index == -1) { root.owner = null; root = null; return; }
1244             MP[] newMPS = new MP[mps.length - 1];
1245             System.arraycopy(mps,0,newMPS,0,index);
1246             System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
1247             mps = newMPS;
1248         }
1249         
1250         private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
1251             int pl = normalizedPath.length();
1252             if(pl != 0) {
1253                 MP[] list;
1254                 synchronized(this) { list = mps; }
1255                 for(int i=0;i<list.length;i++) {
1256                     MP mp = list[i];
1257                     int mpl = mp.path.length();
1258                     if(normalizedPath.startsWith(mp.path) && (pl == mpl || normalizedPath.charAt(mpl) == '/'))
1259                         return mp.fs.dispatch(op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
1260                 }
1261             }
1262             return root.dispatch(op,r,normalizedPath,arg1,arg2);
1263         }
1264         
1265         public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(FS.OPEN,r,path,flags,mode); }
1266         public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.STAT,r,path,0,0); }
1267         public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.LSTAT,r,path,0,0); }
1268         public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(FS.MKDIR,r,path,mode,0); }
1269         public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(FS.UNLINK,r,path,0,0); }
1270         
1271         private static class CacheEnt {
1272             public final long time;
1273             public final long size;
1274             public final Object o;
1275             public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
1276         }
1277     }
1278     
1279     public abstract static class FS {
1280         static final int OPEN = 1;
1281         static final int STAT = 2;
1282         static final int LSTAT = 3;
1283         static final int MKDIR = 4;
1284         static final int UNLINK = 5;
1285         
1286         GlobalState owner;
1287         int devno;
1288         
1289         Object dispatch(int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
1290             switch(op) {
1291                 case OPEN: return open(r,path,arg1,arg2);
1292                 case STAT: return stat(r,path);
1293                 case LSTAT: return lstat(r,path);
1294                 case MKDIR: mkdir(r,path,arg1); return null;
1295                 case UNLINK: unlink(r,path); return null;
1296                 default: throw new Error("should never happen");
1297             }
1298         }
1299         
1300         public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1301
1302         // If this returns null it'll be truned into an ENOENT
1303         public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
1304         // If this returns null it'll be turned into an ENOENT
1305         public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
1306         public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
1307         public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
1308     }
1309         
1310     // chroot support should go in here if it is ever implemented chroot support in here
1311     private String normalizePath(String path) {
1312         boolean absolute = path.startsWith("/");
1313         int cwdl = cwd.length();
1314         
1315         // NOTE: This isn't just a fast path, it handles cases the code below doesn't
1316         if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
1317             return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
1318         
1319         char[] in = new char[path.length()+1];
1320         char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
1321         int inp=0, outp=0;
1322         
1323         if(absolute) {
1324             do { inp++; } while(in[inp] == '/');
1325         } else if(cwdl != 0) {
1326             cwd.getChars(0,cwdl,out,0);
1327             outp = cwdl;
1328         }
1329
1330         path.getChars(0,path.length(),in,0);
1331         while(in[inp] != 0) {
1332             if(inp != 0) {
1333                 while(in[inp] != 0 && in[inp] != '/') { out[outp++] = in[inp++]; }
1334                 if(in[inp] == '\0') break;
1335                 while(in[inp] == '/') inp++;
1336             }
1337             
1338             // Just read a /
1339             if(in[inp] == '\0') break;
1340             if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
1341             // Just read a /.
1342             if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
1343             if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
1344                 // Just read a /..{$,/}
1345                 inp += 2;
1346                 if(outp > 0) outp--;
1347                 while(outp > 0 && out[outp] != '/') outp--;
1348                 //System.err.println("After ..: " + new String(out,0,outp));
1349                 continue;
1350             }
1351             // Just read a /.[^.] or /..[^/$]
1352             inp++;
1353             out[outp++] = '/';
1354             out[outp++] = '.';
1355         }
1356         if(outp > 0 && out[outp-1] == '/') outp--;
1357         //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
1358         return new String(out,0,outp);
1359     }
1360     
1361     FStat hostFStat(final File f, Object data) {
1362         boolean e = false;
1363         try {
1364             FileInputStream fis = new FileInputStream(f);
1365             switch(fis.read()) {
1366                 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
1367                 case '#': e = fis.read() == '!';
1368             }
1369             fis.close();
1370         } catch(IOException e2) { } 
1371         HostFS fs = (HostFS) data;
1372         final int inode = fs.inodes.get(f.getAbsolutePath());
1373         final int devno = fs.devno;
1374         return new HostFStat(f,e) {
1375             public int inode() { return inode; }
1376             public int dev() { return devno; }
1377         };
1378     }
1379
1380     FD hostFSDirFD(File f, Object _fs) {
1381         HostFS fs = (HostFS) _fs;
1382         return fs.new HostDirFD(f);
1383     }
1384     
1385     public static class HostFS extends FS {
1386         InodeCache inodes = new InodeCache(4000);
1387         protected File root;
1388         public File getRoot() { return root; }
1389         
1390         static File hostRootDir() {
1391             if(Platform.getProperty("nestedvm.root") != null) {
1392                 File f = new File(Platform.getProperty("nestedvm.root"));
1393                 if(f.isDirectory()) return f;
1394                 // fall through to case below
1395             }
1396             String cwd = Platform.getProperty("user.dir");
1397             File f = new File(cwd != null ? cwd : ".");
1398             if(!f.exists()) throw new Error("Couldn't get File for cwd");
1399             f = new File(f.getAbsolutePath());
1400             while(f.getParent() != null) f = new File(f.getParent());
1401             // This works around a bug in some versions of ClassPath
1402             if(f.getPath().length() == 0) f = new File("/");
1403             return f;
1404         }
1405         
1406         private File hostFile(String path) {
1407             char sep = File.separatorChar;
1408             if(sep != '/') {
1409                 char buf[] = path.toCharArray();
1410                 for(int i=0;i<buf.length;i++) {
1411                     char c = buf[i];
1412                     if(c == '/') buf[i] = sep;
1413                     else if(c == sep) buf[i] = '/';
1414                 }
1415                 path = new String(buf);
1416             }
1417             return new File(root,path);
1418         }
1419         
1420         public HostFS() { this(hostRootDir()); }
1421         public HostFS(String root) { this(new File(root)); }
1422         public HostFS(File root) { this.root = root; }
1423         
1424         
1425         public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1426             final File f = hostFile(path);
1427             return r.hostFSOpen(f,flags,mode,this);
1428         }
1429         
1430         public void unlink(UnixRuntime r, String path) throws ErrnoException {
1431             File f = hostFile(path);
1432             if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1433             if(!f.exists()) throw new ErrnoException(ENOENT);
1434             if(!f.delete()) throw new ErrnoException(EPERM);
1435         }
1436         
1437         public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1438             File f = hostFile(path);
1439             if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1440             if(!f.exists()) return null;
1441             return r.hostFStat(f,this);
1442         }
1443         
1444         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1445             File f = hostFile(path);
1446             if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1447             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1448             if(f.exists()) throw new ErrnoException(ENOTDIR);
1449             File parent = getParentFile(f);
1450             if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1451             if(!f.mkdir()) throw new ErrnoException(EIO);            
1452         }
1453         
1454         private static File getParentFile(File f) {
1455             String p = f.getParent();
1456             return p == null ? null : new File(p);
1457         }
1458         
1459         public class HostDirFD extends DirFD {
1460             private final File f;
1461             private final File[] children;
1462             public HostDirFD(File f) {
1463                 this.f = f;
1464                 String[] l = f.list();
1465                 children = new File[l.length];
1466                 for(int i=0;i<l.length;i++) children[i] = new File(f,l[i]);
1467             }
1468             public int size() { return children.length; }
1469             public String name(int n) { return children[n].getName(); }
1470             public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1471             public int parentInode() {
1472                 File parent = getParentFile(f);
1473                 // HACK: myInode() isn't really correct  if we're not the root
1474                 return parent == null ? myInode() : inodes.get(parent.getAbsolutePath());
1475             }
1476             public int myInode() { return inodes.get(f.getAbsolutePath()); }
1477             public int myDev() { return devno; } 
1478         }
1479     }
1480     
1481     private static void putInt(byte[] buf, int off, int n) {
1482         buf[off+0] = (byte)((n>>>24)&0xff);
1483         buf[off+1] = (byte)((n>>>16)&0xff);
1484         buf[off+2] = (byte)((n>>> 8)&0xff);
1485         buf[off+3] = (byte)((n>>> 0)&0xff);
1486     }
1487     
1488     public static abstract class DirFD extends FD {
1489         private int pos = -2;
1490         
1491         protected abstract int size();
1492         protected abstract String name(int n);
1493         protected abstract int inode(int n);
1494         protected abstract int myDev();
1495         protected abstract int parentInode();
1496         protected abstract int myInode();
1497         public int flags() { return O_RDONLY; }
1498
1499         public int getdents(byte[] buf, int off, int len) {
1500             int ooff = off;
1501             int ino;
1502             int reclen;
1503             OUTER: for(;len > 0 && pos < size();pos++){
1504                 switch(pos) {
1505                     case -2:
1506                     case -1:
1507                         ino = pos == -1 ? parentInode() : myInode();
1508                         if(ino == -1) continue;
1509                         reclen = 9 + (pos == -1 ? 2 : 1);
1510                         if(reclen > len) break OUTER;
1511                         buf[off+8] = '.';
1512                         if(pos == -1) buf[off+9] = '.';
1513                         break;
1514                     default: {
1515                         String f = name(pos);
1516                         byte[] fb = getBytes(f);
1517                         reclen = fb.length + 9;
1518                         if(reclen > len) break OUTER;
1519                         ino = inode(pos);
1520                         System.arraycopy(fb,0,buf,off+8,fb.length);
1521                     }
1522                 }
1523                 buf[off+reclen-1] = 0; // null terminate
1524                 reclen = (reclen + 3) & ~3; // add padding
1525                 putInt(buf,off,reclen);
1526                 putInt(buf,off+4,ino);
1527                 off += reclen;
1528                 len -= reclen;    
1529             }
1530             return off-ooff;
1531         }
1532         
1533         protected FStat _fstat() {
1534             return new FStat() { 
1535                 public int type() { return S_IFDIR; }
1536                 public int inode() { return myInode(); }
1537                 public int dev() { return myDev(); }
1538             };
1539         }
1540     }
1541         
1542     public static class DevFS extends FS {
1543         private static final int ROOT_INODE = 1;
1544         private static final int NULL_INODE = 2;
1545         private static final int ZERO_INODE = 3;
1546         private static final int FD_INODE = 4;
1547         private static final int FD_INODES = 32;
1548         
1549         private abstract class DevFStat extends FStat {
1550             public int dev() { return devno; }
1551             public int mode() { return 0666; }
1552             public int type() { return S_IFCHR; }
1553             public int nlink() { return 1; }
1554             public abstract int inode();
1555         }
1556         
1557         private abstract class DevDirFD extends DirFD {
1558             public int myDev() { return devno; }
1559         }
1560         
1561         private FD devZeroFD = new FD() {
1562             public int read(byte[] a, int off, int length) { 
1563                 /*Arrays.fill(a,off,off+length,(byte)0);*/
1564                 for(int i=off;i<off+length;i++) a[i] = 0;
1565                 return length;
1566             }
1567             public int write(byte[] a, int off, int length) { return length; }
1568             public int seek(int n, int whence) { return 0; }
1569             public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1570             public int flags() { return O_RDWR; }
1571         };
1572         private FD devNullFD = new FD() {
1573             public int read(byte[] a, int off, int length) { return 0; }
1574             public int write(byte[] a, int off, int length) { return length; }
1575             public int seek(int n, int whence) { return 0; }
1576             public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1577             public int flags() { return O_RDWR; }
1578         }; 
1579         
1580         public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1581             if(path.equals("null")) return devNullFD;
1582             if(path.equals("zero")) return devZeroFD;
1583             if(path.startsWith("fd/")) {
1584                 int n;
1585                 try {
1586                     n = Integer.parseInt(path.substring(4));
1587                 } catch(NumberFormatException e) {
1588                     return null;
1589                 }
1590                 if(n < 0 || n >= OPEN_MAX) return null;
1591                 if(r.fds[n] == null) return null;
1592                 return r.fds[n].dup();
1593             }
1594             if(path.equals("fd")) {
1595                 int count=0;
1596                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1597                 final int[] files = new int[count];
1598                 count = 0;
1599                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1600                 return new DevDirFD() {
1601                     public int myInode() { return FD_INODE; }
1602                     public int parentInode() { return ROOT_INODE; }
1603                     public int inode(int n) { return FD_INODES + n; }
1604                     public String name(int n) { return Integer.toString(files[n]); }
1605                     public int size() { return files.length; }
1606                 };
1607             }
1608             if(path.equals("")) {
1609                 return new DevDirFD() {
1610                     public int myInode() { return ROOT_INODE; }
1611                     // HACK: We don't have any clean way to get the parent inode
1612                     public int parentInode() { return ROOT_INODE; }
1613                     public int inode(int n) {
1614                         switch(n) {
1615                             case 0: return NULL_INODE;
1616                             case 1: return ZERO_INODE;
1617                             case 2: return FD_INODE;
1618                             default: return -1;
1619                         }
1620                     }
1621                     
1622                     public String name(int n) {
1623                         switch(n) {
1624                             case 0: return "null";
1625                             case 1: return "zero";
1626                             case 2: return "fd";
1627                             default: return null;
1628                         }
1629                     }
1630                     public int size() { return 3; }
1631                 };
1632             }
1633             return null;
1634         }
1635         
1636         public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1637             if(path.equals("null")) return devNullFD.fstat();
1638             if(path.equals("zero")) return devZeroFD.fstat();            
1639             if(path.startsWith("fd/")) {
1640                 int n;
1641                 try {
1642                     n = Integer.parseInt(path.substring(3));
1643                 } catch(NumberFormatException e) {
1644                     return null;
1645                 }
1646                 if(n < 0 || n >= OPEN_MAX) return null;
1647                 if(r.fds[n] == null) return null;
1648                 return r.fds[n].fstat();
1649             }
1650             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; }};
1651             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; }};
1652             return null;
1653         }
1654         
1655         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1656         public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }
1657     }    
1658 }