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