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