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