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