socket support
[nestedvm.git] / src / org / ibex / nestedvm / UnixRuntime.java
1 package org.ibex.nestedvm;
2
3 import org.ibex.nestedvm.util.*;
4 import java.io.*;
5 import java.util.*;
6 import java.net.Socket;
7 import java.net.ServerSocket;
8
9 // FEATURE: vfork
10
11 public abstract class UnixRuntime extends Runtime implements Cloneable {
12     /** The pid of this "process" */
13     private int pid;
14     private UnixRuntime parent;
15     public final int getPid() { return pid; }
16     
17     private static final GlobalState defaultGS = new GlobalState();
18     private GlobalState gs = defaultGS;
19     public void setGlobalState(GlobalState gs) {
20         if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running");
21         this.gs = gs;
22     }
23     
24     /** proceses' current working directory - absolute path WITHOUT leading slash
25         "" = root, "bin" = /bin "usr/bin" = /usr/bin */
26     private String cwd;
27     
28     /** The runtime that should be run next when in state == EXECED */
29     private UnixRuntime execedRuntime;
30
31     private Object children; // used only for synchronizatin
32     private Vector activeChildren;
33     private Vector exitedChildren;
34     
35     protected UnixRuntime(int pageSize, int totalPages) {
36         super(pageSize,totalPages);
37                 
38         // FEATURE: Do the proper mangling for non-unix hosts
39         String userdir = getSystemProperty("user.dir");
40         cwd = 
41             userdir != null && userdir.startsWith("/") && File.separatorChar == '/' && getSystemProperty("nestedvm.root") == null
42             ? userdir.substring(1) : "";
43     }
44     
45     // NOTE: getDisplayName() is a Java2 function
46     private static String posixTZ() {
47         StringBuffer sb = new StringBuffer();
48         TimeZone zone = TimeZone.getDefault();
49         int off = zone.getRawOffset() / 1000;
50         sb.append(zone.getDisplayName(false,TimeZone.SHORT));
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(zone.getDisplayName(true,TimeZone.SHORT));
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) && getSystemProperty("user.name") != null)
72             defaults[n++] = "USER=" + getSystemProperty("user.name");
73         if(!envHas("HOME",extra) && getSystemProperty("user.home") != null)
74             defaults[n++] = "HOME=" + getSystemProperty("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.set(i,this);
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) 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_opensocket: return sys_opensocket(a,b);
130             case SYS_listensocket: return sys_listensocket(a);
131             case SYS_accept: return sys_accept(a);
132
133             default: return super._syscall(syscall,a,b,c,d);
134         }
135     }
136     
137     FD _open(String path, int flags, int mode) throws ErrnoException {
138         return gs.open(this,normalizePath(path),flags,mode);
139     }
140     
141     private int sys_getppid() {
142         return parent == null ? 1 : parent.pid;
143     }
144
145     /** The kill syscall.
146        SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
147        SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
148        Anything else terminates the process. */
149     private int sys_kill(int pid, int signal) {
150         // This will only be called by raise() in newlib to invoke the default handler
151         // We don't have to worry about actually delivering the signal
152         if(pid != pid) return -ESRCH;
153         if(signal < 0 || signal >= 32) return -EINVAL;
154         switch(signal) {
155             case 0: return 0;
156             case 17: // SIGSTOP
157             case 18: // SIGTSTP
158             case 21: // SIGTTIN
159             case 22: // SIGTTOU
160                 state = PAUSED;
161                 break;
162             case 19: // SIGCONT
163             case 20: // SIGCHLD
164             case 23: // SIGIO
165             case 28: // SIGWINCH
166                 break;
167             default:
168                 return syscall(SYS_exit,128+signal,0,0,0);
169         }
170         return 0;
171     }
172
173     private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
174         final int WNOHANG = 1;
175         if((options & ~(WNOHANG)) != 0) return -EINVAL;
176         if(pid == 0 || pid < -1) {
177             if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
178             return -ECHILD;
179         }
180         boolean blocking = (options&WNOHANG)==0;
181         
182         if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
183         if(children == null) return blocking ? -ECHILD : 0;
184         
185         UnixRuntime done = null;
186         
187         synchronized(children) {
188             for(;;) {
189                 if(pid == -1) {
190                     if(exitedChildren.size() > 0) done = (UnixRuntime)exitedChildren.remove(exitedChildren.size() - 1);
191                 } else if(pid > 0) {
192                     UnixRuntime t = gs.tasks[pid];
193                     if(t.parent != this) return -ECHILD;
194                     if(t.state == EXITED) {
195                         if(!exitedChildren.remove(t)) throw new Error("should never happen");
196                         done = t;
197                     }
198                 } else {
199                     // process group stuff, EINVAL returned above
200                         throw new Error("should never happen");
201                 }
202                 if(done == null) {
203                     if(!blocking) return 0;
204                     try { children.wait(); } catch(InterruptedException e) {}
205                     //System.err.println("waitpid woke up: " + exitedChildren.size());
206                 } else {
207                     gs.tasks[done.pid] = null;
208                     break;
209                 }
210             }
211         }
212         if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
213         return done.pid;
214     }
215     
216     
217     void _exited() {
218         if(children != null) synchronized(children) {
219             for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
220                 UnixRuntime child = (UnixRuntime) e.nextElement();
221                 gs.tasks[child.pid] = null;
222             }
223             exitedChildren.clear();
224             for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
225                 UnixRuntime child = (UnixRuntime) e.nextElement();
226                 child.parent = null;
227             }
228             activeChildren.clear();
229         }
230         
231         UnixRuntime _parent = parent;
232         if(_parent == null) {
233             gs.tasks[pid] = null;
234         } else {
235             synchronized(_parent.children) {
236                 if(parent == null) {
237                     gs.tasks[pid] = null;
238                 } else {
239                     if(!parent.activeChildren.remove(this)) throw new Error("should never happen _exited: pid: " + pid);
240                     parent.exitedChildren.add(this);
241                     parent.children.notify();
242                 }
243             }
244         }
245     }
246     
247     protected Object clone() throws CloneNotSupportedException {
248         UnixRuntime r = (UnixRuntime) super.clone();
249         r.pid = 0;
250         r.parent = null;
251         r.children = null;
252         r.activeChildren = r.exitedChildren = null;
253         return r;
254     }
255
256     private int sys_fork() {
257         CPUState state = new CPUState();
258         getCPUState(state);
259         int sp = state.r[SP];
260         final UnixRuntime r;
261         
262         try {
263             r = (UnixRuntime) clone();
264         } catch(Exception e) {
265             e.printStackTrace();
266             return -ENOMEM;
267         }
268
269         r.parent = this;
270
271         try {
272             r._started();
273         } catch(ProcessTableFullExn e) {
274             return -ENOMEM;
275         }
276
277         //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
278         if(children == null) {
279             children = new Object();
280             activeChildren = new Vector();
281             exitedChildren = new Vector();
282         }
283         activeChildren.add(r);
284         
285         state.r[V0] = 0; // return 0 to child
286         state.pc += 4; // skip over syscall instruction
287         r.setCPUState(state);
288         r.state = PAUSED;
289         
290         new ForkedProcess(r);
291         
292         return r.pid;
293     }
294     
295     public static final class ForkedProcess extends Thread {
296         private final UnixRuntime initial;
297         public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
298         public void run() { UnixRuntime.executeAndExec(initial); }
299     }
300     
301     public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
302     public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
303     
304     public static int executeAndExec(UnixRuntime r) {
305         for(;;) {
306             for(;;) {
307                 if(r.execute()) break;
308                 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
309             }
310             if(r.state != EXECED) return r.exitStatus();
311             r = r.execedRuntime;
312         }
313     }
314      
315     private String[] readStringArray(int addr) throws ReadFaultException {
316         int count = 0;
317         for(int p=addr;memRead(p) != 0;p+=4) count++;
318         String[] a = new String[count];
319         for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
320         return a;
321     }
322     
323     private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
324         return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
325     }
326         
327     private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
328         if(argv.length == 0) argv = new String[]{""};
329
330         // NOTE: For this little hack to work nestedvm.root MUST be "."
331         /*try {
332             System.err.println("Execing normalized path: " + normalizedPath);
333             if(true) return exec(new Interpreter(normalizedPath),argv,envp);
334         } catch(IOException e) { throw new Error(e); }*/
335         
336         Object o = gs.exec(this,normalizedPath);
337         if(o == null) return -ENOENT;
338
339         if(o instanceof Class) {
340             Class c = (Class) o;
341             try {
342                 return exec((UnixRuntime) c.newInstance(),argv,envp);
343             } catch(Exception e) {
344                 e.printStackTrace();
345                 return -ENOEXEC;
346             }
347         } else {
348             String[] command = (String[]) o;
349             String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
350             int p = command[0].lastIndexOf('/');
351             newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
352             p = 1;
353             if(command[1] != null) newArgv[p++] = command[1];
354             newArgv[p++] = "/" + normalizedPath;
355             for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
356             return exec(command[0],newArgv,envp);
357         }
358     }
359     
360     private int exec(UnixRuntime r, String[] argv, String[] envp) {     
361         
362         //System.err.println("Execing " + r);
363         for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
364         r.fds = fds;
365         r.closeOnExec = closeOnExec;
366         // make sure this doesn't get messed with these since we didn't copy them
367         fds = null;
368         closeOnExec = null;
369         
370         r.gs = gs;
371         r.sm = sm;
372         r.cwd = cwd;
373         r.pid = pid;
374         r.parent = parent;
375         r.start(argv,envp);
376                 
377         state = EXECED;
378         execedRuntime = r;
379         
380         return 0;   
381     }
382     
383     // FEATURE: Make sure fstat info is correct
384     // FEATURE: This could be faster if we did direct copies from each process' memory
385     // FEATURE: Check this logic one more time
386     public static class Pipe {
387         private final byte[] pipebuf = new byte[PIPE_BUF*4];
388         private int readPos;
389         private int writePos;
390         
391         public final FD reader = new Reader();
392         public final FD writer = new Writer();
393         
394         public class Reader extends FD {
395             protected FStat _fstat() { return new FStat(); }
396             public int read(byte[] buf, int off, int len) throws ErrnoException {
397                 if(len == 0) return 0;
398                 synchronized(Pipe.this) {
399                     while(writePos != -1 && readPos == writePos) {
400                         try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
401                     }
402                     if(writePos == -1) return 0; // eof
403                     len = Math.min(len,writePos-readPos);
404                     System.arraycopy(pipebuf,readPos,buf,off,len);
405                     readPos += len;
406                     if(readPos == writePos) Pipe.this.notify();
407                     return len;
408                 }
409             }
410             public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
411         }
412         
413         public class Writer extends FD {   
414             protected FStat _fstat() { return new FStat(); }
415             public int write(byte[] buf, int off, int len) throws ErrnoException {
416                 if(len == 0) return 0;
417                 synchronized(Pipe.this) {
418                     if(readPos == -1) throw new ErrnoException(EPIPE);
419                     if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
420                         // not enough space to atomicly write the data
421                         while(readPos != -1 && readPos != writePos) {
422                             try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
423                         }
424                         if(readPos == -1) throw new ErrnoException(EPIPE);
425                         readPos = writePos = 0;
426                     }
427                     len = Math.min(len,pipebuf.length - writePos);
428                     System.arraycopy(buf,off,pipebuf,writePos,len);
429                     if(readPos == writePos) Pipe.this.notify();
430                     writePos += len;
431                     return len;
432                 }
433             }
434             public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
435         }
436     }
437     
438     private int sys_pipe(int addr) {
439         Pipe pipe = new Pipe();
440         
441         int fd1 = addFD(pipe.reader);
442         if(fd1 < 0) return -ENFILE;
443         int fd2 = addFD(pipe.writer);
444         if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
445         
446         try {
447             memWrite(addr,fd1);
448             memWrite(addr+4,fd2);
449         } catch(FaultException e) {
450             closeFD(fd1);
451             closeFD(fd2);
452             return -EFAULT;
453         }
454         return 0;
455     }
456     
457     private int sys_dup2(int oldd, int newd) {
458         if(oldd == newd) return 0;
459         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
460         if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
461         if(fds[oldd] == null) return -EBADFD;
462         if(fds[newd] != null) fds[newd].close();
463         fds[newd] = fds[oldd].dup();
464         return 0;
465     }
466     
467     private int sys_dup(int oldd) {
468         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
469         if(fds[oldd] == null) return -EBADFD;
470         FD fd = fds[oldd].dup();
471         int newd = addFD(fd);
472         if(newd < 0) { fd.close(); return -ENFILE; }
473         return newd;
474     }
475     
476     private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
477         FStat s = gs.stat(this,normalizePath(cstring(cstring)));
478         if(s == null) return -ENOENT;
479         return stat(s,addr);
480     }
481     
482     private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
483         FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
484         if(s == null) return -ENOENT;
485         return stat(s,addr);
486     }
487     
488     private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
489         gs.mkdir(this,normalizePath(cstring(cstring)),mode);
490         return 0;
491     }
492    
493     private int sys_unlink(int cstring) throws FaultException, ErrnoException {
494         gs.unlink(this,normalizePath(cstring(cstring)));
495         return 0;
496     }
497     
498     private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
499         byte[] b = getBytes(cwd);
500         if(size == 0) return -EINVAL;
501         if(size < b.length+2) return -ERANGE;
502         memset(addr,'/',1);
503         copyout(b,addr+1,b.length);
504         memset(addr+b.length+1,0,1);
505         return addr;
506     }
507     
508     private int sys_chdir(int addr) throws ErrnoException, FaultException {
509         String path = normalizePath(cstring(addr));
510         //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
511         if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
512         cwd = path;
513         //System.err.println("Now: [" + cwd + "]");
514         return 0;
515     }
516     
517     private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
518         count = Math.min(count,MAX_CHUNK);
519         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
520         if(fds[fdn] == null) return -EBADFD;
521         byte[] buf = byteBuf(count);
522         int n = fds[fdn].getdents(buf,0,count);
523         copyout(buf,addr,n);
524         return n;
525     }
526     
527     private static class SocketFD extends InputOutputStreamFD {
528         private final Socket s;
529         
530         public SocketFD(Socket s) throws IOException {
531             super(s.getInputStream(),s.getOutputStream());
532             this.s = s;
533         }
534         
535         public void _close() { try { s.close(); } catch(IOException e) { } }
536     }
537     
538     public int sys_opensocket(int cstring, int port) throws FaultException, ErrnoException {
539         String hostname = cstring(cstring);
540         try {
541             FD fd = new SocketFD(new Socket(hostname,port));
542             int n = addFD(fd);
543             if(n == -1) fd.close();
544             return n;
545         } catch(IOException e) {
546             return -EIO;
547         }
548     }
549     
550     private static class ListenSocketFD extends FD {
551         ServerSocket s;
552         public ListenSocketFD(ServerSocket s) { this.s = s; }
553         public int flags() { return 0; }
554         // FEATURE: What should these be?
555         public FStat _fstat() { return new FStat(); }
556         public void _close() { try { s.close(); } catch(IOException e) { } }
557     }
558     
559     public int sys_listensocket(int port) {
560         try {
561             ListenSocketFD fd = new ListenSocketFD(new ServerSocket(port));
562             int n = addFD(fd);
563             if(n == -1) fd.close();
564             return n;            
565         } catch(IOException e) {
566             return -EIO;
567         }
568     }
569     
570     public int sys_accept(int fdn) {
571         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
572         if(fds[fdn] == null) return -EBADFD;
573         if(!(fds[fdn] instanceof ListenSocketFD)) return -EBADFD;
574         try {
575             ServerSocket s = ((ListenSocketFD)fds[fdn]).s;
576             SocketFD fd = new SocketFD(s.accept());
577             int n = addFD(fd);
578             if(n == -1) fd.close();
579             return n;
580         } catch(IOException e) {
581             return -EIO;
582         }
583     }
584     
585     //  FEATURE: Run through the fork/wait stuff one more time
586     public static class GlobalState {    
587         protected static final int OPEN = 1;
588         protected static final int STAT = 2;
589         protected static final int LSTAT = 3;
590         protected static final int MKDIR = 4;
591         protected static final int UNLINK = 5;
592         
593         final UnixRuntime[] tasks;
594         int nextPID = 1;
595         
596         private MP[] mps = new MP[0];
597         private FS root;
598         
599         public GlobalState() { this(255); }
600         public GlobalState(int maxProcs) { this(maxProcs,true); }
601         public GlobalState(int maxProcs, boolean defaultMounts) {
602             tasks = new UnixRuntime[maxProcs+1];
603             if(defaultMounts) {
604                 addMount("/",new HostFS());
605                 addMount("/dev",new DevFS());
606             }
607         }
608         
609         private static class MP implements Comparable {
610             public MP(String path, FS fs) { this.path = path; this.fs = fs; }
611             public String path;
612             public FS fs;
613             public int compareTo(Object o) {
614                 if(!(o instanceof MP)) return 1;
615                 return -path.compareTo(((MP)o).path);
616             }
617         }
618         
619         public synchronized FS getMount(String path) {
620             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
621             if(path.equals("/")) return root;
622             path  = path.substring(1);
623             for(int i=0;i<mps.length;i++)
624                 if(mps[i].path.equals(path)) return mps[i].fs;
625             return null;
626         }
627         
628         public synchronized void addMount(String path, FS fs) {
629             if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
630             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
631             
632             if(fs.owner != null) fs.owner.removeMount(fs);
633             fs.owner = this;
634             
635             if(path.equals("/")) { root = fs; fs.devno = 1; return; }
636             path = path.substring(1);
637             int oldLength = mps.length;
638             MP[] newMPS = new MP[oldLength + 1];
639             if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
640             newMPS[oldLength] = new MP(path,fs);
641             Arrays.sort(newMPS);
642             mps = newMPS;
643             int highdevno = 0;
644             for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
645             fs.devno = highdevno + 2;
646         }
647         
648         public synchronized void removeMount(FS fs) {
649             for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
650             throw new IllegalArgumentException("mount point doesn't exist");
651         }
652         
653         public synchronized void removeMount(String path) {
654             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
655             if(path.equals("/")) {
656                 removeMount(-1);
657             } else {
658                 path = path.substring(1);
659                 int p;
660                 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
661                 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
662                 removeMount(p);
663             }
664         }
665         
666         private void removeMount(int index) {
667             if(index == -1) { root.owner = null; root = null; return; }
668             MP[] newMPS = new MP[mps.length - 1];
669             System.arraycopy(mps,0,newMPS,0,index);
670             System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
671             mps = newMPS;
672         }
673         
674         private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
675             int pl = normalizedPath.length();
676             if(pl != 0) {
677                 MP[] list;
678                 synchronized(this) { list = mps; }
679                 for(int i=0;i<list.length;i++) {
680                     MP mp = list[i];
681                     int mpl = mp.path.length();
682                     if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
683                         return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
684                 }
685             }
686             return dispatch(root,op,r,normalizedPath,arg1,arg2);
687         }
688         
689         private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
690             switch(op) {
691                 case OPEN: return fs.open(r,path,arg1,arg2);
692                 case STAT: return fs.stat(r,path);
693                 case LSTAT: return fs.lstat(r,path);
694                 case MKDIR: fs.mkdir(r,path,arg1); return null;
695                 case UNLINK: fs.unlink(r,path); return null;
696                 default: throw new Error("should never happen");
697             }
698         }
699         
700         public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
701         public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
702         public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
703         public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
704         public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
705         
706         private Hashtable execCache = new Hashtable();
707         private static class CacheEnt {
708             public final long time;
709             public final long size;
710             public final Object o;
711             public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
712         }
713
714         public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
715             // FIXME: Hideous hack to make a standalone busybox possible
716             if(path.equals("bin/busybox") && Boolean.valueOf(getSystemProperty("nestedvm.busyboxhack")).booleanValue())
717                 return r.getClass();
718             FStat fstat = stat(r,path);
719             if(fstat == null) return null;
720             long mtime = fstat.mtime();
721             long size = fstat.size();
722             CacheEnt ent = (CacheEnt) execCache.get(path);
723             if(ent != null) {
724                 //System.err.println("Found cached entry for " + path);
725                 if(ent.time == mtime && ent.size == size) return ent.o;
726                 //System.err.println("Cache was out of date");
727                 execCache.remove(path);
728             }
729             FD fd = open(r,path,RD_ONLY,0);
730             if(fd == null) return null;
731             Seekable s = fd.seekable();
732             
733             String[] command  = null;
734
735             if(s == null) throw new ErrnoException(EACCES);
736             byte[] buf = new byte[4096];
737             
738             try {
739                 int n = s.read(buf,0,buf.length);
740                 if(n == -1) throw new ErrnoException(ENOEXEC);
741                 
742                 switch(buf[0]) {
743                     case '\177': // possible ELF
744                         if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
745                         if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
746                         break;
747                     case '#':
748                         if(n == 1) {
749                             int n2 = s.read(buf,1,buf.length-1);
750                             if(n2 == -1) throw new ErrnoException(ENOEXEC);
751                             n += n2;
752                         }
753                         if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
754                         int p = 2;
755                         n -= 2;
756                         OUTER: for(;;) {
757                             for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
758                             p += n;
759                             if(p == buf.length) break OUTER;
760                             n = s.read(buf,p,buf.length-p);
761                         }
762                         command = new String[2];
763                         int arg;
764                         for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
765                         if(arg < p) {
766                             int cmdEnd = arg;
767                             while(arg < p && buf[arg] == ' ') arg++;
768                             command[0] = new String(buf,2,cmdEnd);
769                             command[1] = arg < p ? new String(buf,arg,p-arg) : null;
770                         } else {
771                             command[0] = new String(buf,2,p-2);
772                         }
773                         //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
774                         break;
775                     default:
776                         throw new ErrnoException(ENOEXEC);
777                 }
778             } catch(IOException e) {
779                 fd.close();
780                 throw new ErrnoException(EIO);
781             }
782                         
783             if(command == null) {
784                 // its an elf binary
785                 try {
786                     s.seek(0);
787                     Class c = RuntimeCompiler.compile(s);
788                     //System.err.println("Compile succeeded: " + c);
789                     ent = new CacheEnt(mtime,size,c);
790                 } catch(Compiler.Exn e) {
791                     if(STDERR_DIAG) e.printStackTrace();
792                     throw new ErrnoException(ENOEXEC);
793                 } catch(IOException e) {
794                     if(STDERR_DIAG) e.printStackTrace();
795                     throw new ErrnoException(EIO);
796                 }
797             } else {
798                 ent = new CacheEnt(mtime,size,command);
799             }
800             
801             fd.close();
802             
803             execCache.put(path,ent);
804             return ent.o;
805         }
806     }
807     
808     public abstract static class FS {
809         GlobalState owner;
810         int devno;
811         
812         public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
813
814         // If this returns null it'll be truned into an ENOENT
815         public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
816         // If this returns null it'll be turned into an ENOENT
817         public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
818         public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
819         public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
820     }
821         
822     // FEATURE: chroot support in here
823     private String normalizePath(String path) {
824         boolean absolute = path.startsWith("/");
825         int cwdl = cwd.length();
826         // NOTE: This isn't just a fast path, it handles cases the code below doesn't
827         if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
828             return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
829         
830         char[] in = new char[path.length()+1];
831         char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
832         int inp=0, outp=0;
833         
834         if(absolute) {
835             do { inp++; } while(in[inp] == '/');
836         } else if(cwdl != 0) {
837             cwd.getChars(0,cwdl,out,0);
838             outp = cwdl;
839         }
840             
841         path.getChars(0,path.length(),in,0);
842         while(in[inp] != 0) {
843             if(inp != 0 || cwdl==0) {
844                 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
845                 while(in[inp] == '/') inp++;
846             }
847             if(in[inp] == '\0') continue;
848             if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
849             if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
850             if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
851                 inp += 2;
852                 if(outp > 0) outp--;
853                 while(outp > 0 && out[outp] != '/') outp--;
854                 //System.err.println("After ..: " + new String(out,0,outp));
855                 continue;
856             }
857             inp++;
858             out[outp++] = '/';
859             out[outp++] = '.';
860         }
861         if(outp > 0 && out[outp-1] == '/') outp--;
862         //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
863         return new String(out,0,outp);
864     }
865     
866     FStat hostFStat(final File f, Object data) {
867         boolean e = false;
868         try {
869             FileInputStream fis = new FileInputStream(f);
870             switch(fis.read()) {
871                 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
872                 case '#': e = fis.read() == '!';
873             }
874             fis.close();
875         } catch(IOException e2) { } 
876         HostFS fs = (HostFS) data;
877         final int inode = fs.inodes.get(f.getAbsolutePath());
878         final int devno = fs.devno;
879         return new HostFStat(f,e) {
880             public int inode() { return inode; }
881             public int dev() { return devno; }
882         };
883     }
884
885     FD hostFSDirFD(File f, Object _fs) {
886         HostFS fs = (HostFS) _fs;
887         return fs.new HostDirFD(f);
888     }
889     
890     public static class HostFS extends FS {
891         InodeCache inodes = new InodeCache(4000);
892         protected File root;
893         public File getRoot() { return root; }
894         
895         private static File hostRootDir() {
896             if(getSystemProperty("nestedvm.root") != null) {
897                 File f = new File(getSystemProperty("nestedvm.root"));
898                 if(f.isDirectory()) return f;
899                 // fall through to case below
900             }
901             String cwd = getSystemProperty("user.dir");
902             File f = new File(cwd != null ? cwd : ".");
903             if(!f.exists()) throw new Error("Couldn't get File for cwd");
904             f = new File(f.getAbsolutePath());
905             while(f.getParent() != null) f = new File(f.getParent());
906             return f;
907         }
908         
909         private File hostFile(String path) {
910             char sep = File.separatorChar;
911             if(sep != '/') {
912                 char buf[] = path.toCharArray();
913                 for(int i=0;i<buf.length;i++) {
914                     char c = buf[i];
915                     if(c == '/') buf[i] = sep;
916                     else if(c == sep) buf[i] = '/';
917                 }
918                 path = new String(buf);
919             }
920             return new File(root,path);
921         }
922         
923         public HostFS() { this(hostRootDir()); }
924         public HostFS(String root) { this(new File(root)); }
925         public HostFS(File root) { this.root = root; }
926         
927         
928         public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
929             final File f = hostFile(path);
930             return r.hostFSOpen(f,flags,mode,this);
931         }
932         
933         public void unlink(UnixRuntime r, String path) throws ErrnoException {
934             File f = hostFile(path);
935             if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
936             if(!f.exists()) throw new ErrnoException(ENOENT);
937             if(!f.delete()) throw new ErrnoException(EPERM);
938         }
939         
940         public FStat stat(UnixRuntime r, String path) throws ErrnoException {
941             File f = hostFile(path);
942             if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
943             if(!f.exists()) return null;
944             return r.hostFStat(f,this);
945         }
946         
947         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
948             File f = hostFile(path);
949             if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
950             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
951             if(f.exists()) throw new ErrnoException(ENOTDIR);
952             File parent = f.getParentFile();
953             if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
954             if(!f.mkdir()) throw new ErrnoException(EIO);            
955         }
956         
957         public class HostDirFD extends DirFD {
958             private final File f;
959             private final File[] children;
960             public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
961             public int size() { return children.length; }
962             public String name(int n) { return children[n].getName(); }
963             public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
964             public int parentInode() {
965                 File parent = f.getParentFile();
966                 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
967             }
968             public int myInode() { return inodes.get(f.getAbsolutePath()); }
969             public int myDev() { return devno; } 
970         }
971     }
972     
973     private static void putInt(byte[] buf, int off, int n) {
974         buf[off+0] = (byte)((n>>>24)&0xff);
975         buf[off+1] = (byte)((n>>>16)&0xff);
976         buf[off+2] = (byte)((n>>> 8)&0xff);
977         buf[off+3] = (byte)((n>>> 0)&0xff);
978     }
979     
980     public static abstract class DirFD extends FD {
981         private int pos = -2;
982         
983         protected abstract int size();
984         protected abstract String name(int n);
985         protected abstract int inode(int n);
986         protected abstract int myDev();
987         protected int parentInode() { return -1; }
988         protected int myInode() { return -1; }
989         
990         public int getdents(byte[] buf, int off, int len) {
991             int ooff = off;
992             int ino;
993             int reclen;
994             OUTER: for(;len > 0 && pos < size();pos++){
995                 switch(pos) {
996                     case -2:
997                     case -1:
998                         ino = pos == -1 ? parentInode() : myInode();
999                         if(ino == -1) continue;
1000                         reclen = 9 + (pos == -1 ? 2 : 1);
1001                         if(reclen > len) break OUTER;
1002                         buf[off+8] = '.';
1003                         if(pos == -1) buf[off+9] = '.';
1004                         break;
1005                     default: {
1006                         String f = name(pos);
1007                         byte[] fb = getBytes(f);
1008                         reclen = fb.length + 9;
1009                         if(reclen > len) break OUTER;
1010                         ino = inode(pos);
1011                         System.arraycopy(fb,0,buf,off+8,fb.length);
1012                     }
1013                 }
1014                 buf[off+reclen-1] = 0; // null terminate
1015                 reclen = (reclen + 3) & ~3; // add padding
1016                 putInt(buf,off,reclen);
1017                 putInt(buf,off+4,ino);
1018                 off += reclen;
1019                 len -= reclen;    
1020             }
1021             return off-ooff;
1022         }
1023         
1024         protected FStat _fstat() {
1025             return new FStat() { 
1026                 public int type() { return S_IFDIR; }
1027                 public int inode() { return myInode(); }
1028                 public int dev() { return myDev(); }
1029             };
1030         }
1031     }
1032         
1033     public static class DevFS extends FS {
1034         private static final int ROOT_INODE = 1;
1035         private static final int NULL_INODE = 2;
1036         private static final int ZERO_INODE = 3;
1037         private static final int FD_INODE = 4;
1038         private static final int FD_INODES = 32;
1039         
1040         private class DevFStat extends FStat {
1041             public int dev() { return devno; }
1042             public int mode() { return 0666; }
1043             public int type() { return S_IFCHR; }
1044             public int nlink() { return 1; }
1045         }
1046         
1047         private abstract class DevDirFD extends DirFD {
1048             public int myDev() { return devno; }
1049         }
1050         
1051         private FD devZeroFD = new FD() {
1052             public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
1053             public int write(byte[] a, int off, int length) { return length; }
1054             public int seek(int n, int whence) { return 0; }
1055             public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1056         };
1057         private FD devNullFD = new FD() {
1058             public int read(byte[] a, int off, int length) { return 0; }
1059             public int write(byte[] a, int off, int length) { return length; }
1060             public int seek(int n, int whence) { return 0; }
1061             public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1062         }; 
1063         
1064         public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1065             if(path.equals("null")) return devNullFD;
1066             if(path.equals("zero")) return devZeroFD;
1067             if(path.startsWith("fd/")) {
1068                 int n;
1069                 try {
1070                     n = Integer.parseInt(path.substring(4));
1071                 } catch(NumberFormatException e) {
1072                     return null;
1073                 }
1074                 if(n < 0 || n >= OPEN_MAX) return null;
1075                 if(r.fds[n] == null) return null;
1076                 return r.fds[n].dup();
1077             }
1078             if(path.equals("fd")) {
1079                 int count=0;
1080                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1081                 final int[] files = new int[count];
1082                 count = 0;
1083                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1084                 return new DevDirFD() {
1085                     public int myInode() { return FD_INODE; }
1086                     public int parentInode() { return ROOT_INODE; }
1087                     public int inode(int n) { return FD_INODES + n; }
1088                     public String name(int n) { return Integer.toString(files[n]); }
1089                     public int size() { return files.length; }
1090                 };
1091             }
1092             if(path.equals("")) {
1093                 return new DevDirFD() {
1094                     public int myInode() { return ROOT_INODE; }
1095                     // FEATURE: Get the real parent inode somehow
1096                     public int parentInode() { return -1; }
1097                     public int inode(int n) {
1098                         switch(n) {
1099                             case 0: return NULL_INODE;
1100                             case 1: return ZERO_INODE;
1101                             case 2: return FD_INODE;
1102                             default: return -1;
1103                         }
1104                     }
1105                     
1106                     public String name(int n) {
1107                         switch(n) {
1108                             case 0: return "null";
1109                             case 1: return "zero";
1110                             case 2: return "fd";
1111                             default: return null;
1112                         }
1113                     }
1114                     public int size() { return 3; }
1115                 };
1116             }
1117             return null;
1118         }
1119         
1120         public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1121             if(path.equals("null")) return devNullFD.fstat();
1122             if(path.equals("zero")) return devZeroFD.fstat();            
1123             if(path.startsWith("fd/")) {
1124                 int n;
1125                 try {
1126                     n = Integer.parseInt(path.substring(4));
1127                 } catch(NumberFormatException e) {
1128                     return null;
1129                 }
1130                 if(n < 0 || n >= OPEN_MAX) return null;
1131                 if(r.fds[n] == null) return null;
1132                 return r.fds[n].fstat();
1133             }
1134             // FEATURE: inode stuff
1135             if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1136             if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1137             return null;
1138         }
1139         
1140         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1141         public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }
1142     }    
1143 }