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