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