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