added inodecache
[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 // FIXME: Make plain old "mips-unknown-elf-gcc -o foo foo.c" work (modify spec file or whatever)
8
9 // FEATURE: Remove System.{out,err}.printlns and throw Errors where applicable
10
11 public abstract class UnixRuntime extends Runtime implements Cloneable {
12     /** The pid of this "process" */
13     private int pid;
14     private UnixRuntime parent;
15     public final int getPid() { return pid; }
16     
17     private static final GlobalState defaultGD = new GlobalState();
18     private GlobalState gd = defaultGD;
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.name") != 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 = gd.tasks;
82         synchronized(gd) {
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 = gd.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                 gd.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_waitpid: return sys_waitpid(a,b,c);
105             case SYS_stat: return sys_stat(a,b);
106             case SYS_lstat: return sys_lstat(a,b);
107             case SYS_mkdir: return sys_mkdir(a,b);
108             case SYS_getcwd: return sys_getcwd(a,b);
109             case SYS_chdir: return sys_chdir(a);
110             case SYS_exec: return sys_exec(a,b,c);
111             case SYS_getdents: return sys_getdents(a,b,c,d);
112
113             default: return super._syscall(syscall,a,b,c,d);
114         }
115     }
116     
117     FD _open(String path, int flags, int mode) throws ErrnoException {
118         return gd.open(this,normalizePath(path),flags,mode);
119     }
120
121     /** The kill syscall.
122        SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
123        SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
124        Anything else terminates the process. */
125     private int sys_kill(int pid, int signal) {
126         // This will only be called by raise() in newlib to invoke the default handler
127         // We don't have to worry about actually delivering the signal
128         if(pid != pid) return -ESRCH;
129         if(signal < 0 || signal >= 32) return -EINVAL;
130         switch(signal) {
131             case 0: return 0;
132             case 17: // SIGSTOP
133             case 18: // SIGTSTP
134             case 21: // SIGTTIN
135             case 22: // SIGTTOU
136                 state = PAUSED;
137                 break;
138             case 19: // SIGCONT
139             case 20: // SIGCHLD
140             case 23: // SIGIO
141             case 28: // SIGWINCH
142                 break;
143             default:
144                 return syscall(SYS_exit,128+signal,0,0,0);
145         }
146         return 0;
147     }
148
149     private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
150         System.err.println("PID: " + this.pid + " is waiting on " + pid);
151         final int WNOHANG = 1;
152         if((options & ~(WNOHANG)) != 0) return -EINVAL;
153         if(pid == 0 || pid < -1) {
154             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 >= gd.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 = gd.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                     gd.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                     gd.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             gd.tasks[pid] = null;
211         } else {
212             synchronized(_parent.children) {
213                 if(parent == null) {
214                     gd.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                 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 = gd.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.gd = gd;
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: Use custom PipeFD - be sure to support PIPE_BUF of data
355     private int sys_pipe(int addr) throws FaultException {
356         PipedOutputStream writerStream = new PipedOutputStream();
357         PipedInputStream readerStream;
358         try {
359              readerStream = new PipedInputStream(writerStream);
360         } catch(IOException e) {
361             return -EIO;
362         }
363         FD reader = new InputStreamFD(readerStream);
364         FD writer = new OutputStreamFD(writerStream);
365         int fd1 = addFD(reader);
366         if(fd1 < 0) return -ENFILE;
367         int fd2 = addFD(writer);
368         if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
369         try {
370             memWrite(addr,fd1);
371             memWrite(addr+4,fd2);
372         } catch(FaultException e) {
373             closeFD(fd1);
374             closeFD(fd2);
375             return -EFAULT;
376         }
377         return 0;
378     }
379     
380     private int sys_dup2(int oldd, int newd) {
381         if(oldd == newd) return 0;
382         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
383         if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
384         if(fds[oldd] == null) return -EBADFD;
385         if(fds[newd] != null) fds[newd].close();
386         fds[newd] = fds[oldd].dup();
387         return 0;
388     }
389     
390     private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
391         FStat s = gd.stat(this,normalizePath(cstring(cstring)));
392         if(s == null) return -ENOENT;
393         return stat(s,addr);
394     }
395     
396     private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
397         FStat s = gd.lstat(this,normalizePath(cstring(cstring)));
398         if(s == null) return -ENOENT;
399         return stat(s,addr);
400     }
401     
402     private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
403         gd.mkdir(this,normalizePath(cstring(cstring)),mode);
404         return 0;
405     }
406    
407     private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
408         byte[] b = getBytes(cwd);
409         if(size == 0) return -EINVAL;
410         if(size < b.length+2) return -ERANGE;
411         memset(addr,'/',1);
412         copyout(b,addr+1,b.length);
413         memset(addr+b.length+1,0,1);
414         return addr;
415     }
416     
417     private int sys_chdir(int addr) throws ErrnoException, FaultException {
418         String path = normalizePath(cstring(addr));
419         System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
420         if(gd.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
421         cwd = path;
422         System.err.println("Now: [" + cwd + "]");
423         return 0;
424     }
425     
426     private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
427         count = Math.min(count,MAX_CHUNK);
428         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
429         if(fds[fdn] == null) return -EBADFD;
430         byte[] buf = byteBuf(count);
431         int n = fds[fdn].getdents(buf,0,count);
432         copyout(buf,addr,n);
433         return n;
434     }
435     
436     //  FEATURE: Run through the fork/wait stuff one more time
437     public static class GlobalState {    
438         protected static final int OPEN = 1;
439         protected static final int STAT = 2;
440         protected static final int LSTAT = 3;
441         protected static final int MKDIR = 4;
442         
443         final UnixRuntime[] tasks;
444         int nextPID = 1;
445         
446         private MP[] mps = new MP[0];
447         private FS root;
448         
449         public GlobalState() { this(255); }
450         public GlobalState(int maxProcs) { this(maxProcs,true); }
451         public GlobalState(int maxProcs, boolean defaultMounts) {
452             tasks = new UnixRuntime[maxProcs+1];
453             if(defaultMounts) {
454                     addMount("/",new HostFS());
455                 addMount("/dev",new DevFS());
456             }
457         }
458         
459         private static class MP {
460             public MP(String path, FS fs) { this.path = path; this.fs = fs; }
461             public String path;
462             public FS fs;
463             public int compareTo(Object o) {
464                 if(!(o instanceof MP)) return 1;
465                 return -path.compareTo(((MP)o).path);
466             }
467         }
468         
469         public synchronized FS getMount(String path) {
470             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
471             if(path.equals("/")) return root;
472             path  = path.substring(1);
473             for(int i=0;i<mps.length;i++)
474                 if(mps[i].path.equals(path)) return mps[i].fs;
475             return null;
476         }
477         
478         public synchronized void addMount(String path, FS fs) {
479             if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
480             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
481             
482             if(fs.owner != null) fs.owner.removeMount(fs);
483             fs.owner = this;
484             
485             if(path.equals("/")) { root = fs; fs.devno = 1; return; }
486             path = path.substring(1);
487             int oldLength = mps.length;
488             MP[] newMPS = new MP[oldLength + 1];
489             if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
490             newMPS[oldLength] = new MP(path,fs);
491             Arrays.sort(newMPS);
492             mps = newMPS;
493             int highdevno = 0;
494             for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
495             fs.devno = highdevno + 2;
496         }
497         
498         public synchronized void removeMount(FS fs) {
499             for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
500             throw new IllegalArgumentException("mount point doesn't exist");
501         }
502         
503         public synchronized void removeMount(String path) {
504             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
505             if(path.equals("/")) {
506                     removeMount(-1);
507             } else {
508                 path = path.substring(1);
509                 int p;
510                 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
511                 if(p == mps.length) throw new Error("mount point doesn't exist");
512                removeMount(p);
513             }
514         }
515         
516         private void removeMount(int index) {
517             if(index == -1) { root.owner = null; root = null; return; }
518             MP[] newMPS = new MP[mps.length - 1];
519             System.arraycopy(mps,0,newMPS,0,index);
520             System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
521             mps = newMPS;
522         }
523         
524         private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
525             int pl = normalizedPath.length();
526             if(pl != 0) {
527                     MP[] list;
528                 synchronized(this) { list = mps; }
529                 for(int i=0;i<list.length;i++) {
530                             MP mp = list[i];
531                             int mpl = mp.path.length();
532                     if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
533                             return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
534                 }
535             }
536             return dispatch(root,op,r,normalizedPath,arg1,arg2);
537         }
538         
539         private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
540             switch(op) {
541                     case OPEN: return fs.open(r,path,arg1,arg2);
542                 case STAT: return fs.stat(r,path);
543                 case LSTAT: return fs.lstat(r,path);
544                 case MKDIR: fs.mkdir(r,path,arg1); return null;
545                 default: throw new Error("should never happen");
546             }
547         }
548         
549         public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
550         public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
551         public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
552         public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
553         
554         private Hashtable execCache = new Hashtable();
555         private static class CacheEnt {
556             public final long time;
557             public final long size;
558             public final Object o;
559             public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
560         }
561
562         public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
563             FStat fstat = stat(r,path);
564             if(fstat == null) return null;
565             long mtime = fstat.mtime();
566             long size = fstat.size();
567             CacheEnt ent = (CacheEnt) execCache.get(path);
568             if(ent != null) {
569                 System.err.println("Found cached entry for " + path);
570                     if(ent.time == mtime && ent.size == size) return ent.o;
571                 System.err.println("Cache was out of date");
572                 execCache.remove(path);
573             }
574             FD fd = open(r,path,RD_ONLY,0);
575             if(fd == null) return null;
576             Seekable s = fd.seekable();
577             
578             String[] command  = null;
579
580             if(s == null) throw new ErrnoException(EACCES);
581             byte[] buf = new byte[4096];
582             
583             try {
584                 int n = s.read(buf,0,buf.length);
585                 if(n == -1) throw new Error("zero length file");
586                 
587                 switch(buf[0]) {
588                     case '\177': // possible ELF
589                         if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
590                         if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
591                         break;
592                     case '#':
593                         if(n == 1) {
594                                     int n2 = s.read(buf,1,buf.length-1);
595                             if(n2 == -1) throw new ErrnoException(ENOEXEC);
596                             n += n2;
597                         }
598                         if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
599                         int p = 2;
600                         n -= 2;
601                         OUTER: for(;;) {
602                                     for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
603                             p += n;
604                             if(p == buf.length) break OUTER;
605                             n = s.read(buf,p,buf.length-p);
606                         }
607                         command = new String[2];
608                         int arg;
609                         for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
610                         if(arg < p) {
611                             int cmdEnd = arg;
612                                     while(arg < p && buf[arg] == ' ') arg++;
613                             command[0] = new String(buf,2,cmdEnd);
614                             command[1] = arg < p ? new String(buf,arg,p-arg) : null;
615                         } else {
616                                     command[0] = new String(buf,2,p-2);
617                         }
618                         System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
619                         break;
620                     default:
621                         throw new ErrnoException(ENOEXEC);
622                 }
623             } catch(IOException e) {
624                 fd.close();
625                     throw new ErrnoException(EIO);
626             }
627                         
628             if(command == null) {
629                 // its an elf binary
630                 try {
631                     s.seek(0);
632                             Class c = RuntimeCompiler.compile(s);
633                     System.err.println("Compile succeeded: " + c);
634                     ent = new CacheEnt(mtime,size,c);
635                 } catch(Compiler.Exn e) {
636                     throw new ErrnoException(ENOEXEC);
637                 } catch(IOException e) {
638                             throw new ErrnoException(EIO);
639                 }
640             } else {
641                     ent = new CacheEnt(mtime,size,command);
642             }
643             
644             fd.close();
645             
646             execCache.put(path,ent);
647             return ent.o;
648         }
649     }
650     
651     public abstract static class FS {
652         GlobalState owner;
653         int devno;
654         
655         public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
656
657         // If this returns null it'll be truned into an ENOENT
658         public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
659         // If this returns null it'll be turned into an ENOENT
660         public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
661         public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
662     }
663         
664     // FEATURE: chroot support in here
665     private String normalizePath(String path) {
666         boolean absolute = path.startsWith("/");
667         int cwdl = cwd.length();
668         // NOTE: This isn't just a fast path, it handles cases the code below doesn't
669         if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
670             return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
671         
672         char[] in = new char[path.length()+1];
673         char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
674         int inp=0, outp=0;
675         
676         if(absolute) {
677             do { inp++; } while(in[inp] == '/');
678         } else if(cwdl != 0) {
679                 cwd.getChars(0,cwdl,out,0);
680                 outp = cwdl;
681         }
682             
683         path.getChars(0,path.length(),in,0);
684         while(in[inp] != 0) {
685             if(inp != 0) {
686                     if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
687                     while(in[inp] == '/') inp++;
688             }
689             if(in[inp] == '\0') continue;
690             if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
691             if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
692             if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
693                 inp += 2;
694                 if(outp > 0) outp--;
695                 while(outp > 0 && out[outp] != '/') outp--;
696                 System.err.println("After ..: " + new String(out,0,outp));
697                 continue;
698             }
699             inp++;
700             out[outp++] = '/';
701             out[outp++] = '.';
702         }
703         if(outp > 0 && out[outp-1] == '/') outp--;
704         //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
705         return new String(out,0,outp);
706     }
707     
708     FStat hostFStat(final File f, Object data) {
709         boolean e = false;
710         try {
711             FileInputStream fis = new FileInputStream(f);
712             switch(fis.read()) {
713                 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
714                 case '#': e = fis.read() == '!';
715             }
716             fis.close();
717         } catch(IOException e2) { } 
718         HostFS fs = (HostFS) data;
719         final int inode = fs.inodes.get(f.getAbsolutePath());
720         final int devno = fs.devno;
721         return new HostFStat(f,e) {
722             public int inode() { return inode; }
723             public int dev() { return devno; }
724         };
725     }
726
727     FD hostFSDirFD(File f, Object _fs) {
728         HostFS fs = (HostFS) _fs;
729         return fs.new HostDirFD(f);
730     }
731     
732     public static class HostFS extends FS {
733         InodeCache inodes = new InodeCache(4000);
734         protected File root;
735         public File getRoot() { return root; }
736         
737         private static File hostRootDir() {
738             String cwd = getSystemProperty("user.dir");
739             File f = new File(cwd != null ? cwd : ".");
740             f = new File(f.getAbsolutePath());
741             while(f.getParent() != null) f = new File(f.getParent());
742             return f;
743         }
744         
745         private File hostFile(String path) {
746             char sep = File.separatorChar;
747             if(sep != '/') {
748                 char buf[] = path.toCharArray();
749                 for(int i=0;i<buf.length;i++) {
750                             char c = buf[i];
751                     if(c == '/') buf[i] = sep;
752                     else if(c == sep) buf[i] = '/';
753                 }
754                 path = new String(buf);
755             }
756             return new File(root,path);
757         }
758         
759         public HostFS() { this(hostRootDir()); }
760         public HostFS(String root) { this(new File(root)); }
761         public HostFS(File root) { this.root = root; }
762         
763         
764         public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
765             final File f = hostFile(path);
766             return r.hostFSOpen(f,flags,mode,this);
767         }
768         
769         public FStat stat(UnixRuntime r, String path) throws ErrnoException {
770             File f = hostFile(path);
771             if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
772             if(!f.exists()) return null;
773             return r.hostFStat(f,this);
774         }
775         
776         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
777             File f = hostFile(path);
778             if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
779             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
780             if(f.exists()) throw new ErrnoException(ENOTDIR);
781             File parent = f.getParentFile();
782             if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
783             if(!f.mkdir()) throw new ErrnoException(EIO);            
784         }
785         
786         public class HostDirFD extends DirFD {
787             private final File f;
788             private final File[] children;
789             public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
790             public int size() { return children.length; }
791             public String name(int n) { return children[n].getName(); }
792             public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
793             public int parentInode() {
794                 File parent = f.getParentFile();
795                 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
796             }
797             public int myInode() { return inodes.get(f.getAbsolutePath()); }
798             public int myDev() { return devno; } 
799         }
800     }
801     
802     private static void putInt(byte[] buf, int off, int n) {
803         buf[off+0] = (byte)((n>>>24)&0xff);
804         buf[off+1] = (byte)((n>>>16)&0xff);
805         buf[off+2] = (byte)((n>>> 8)&0xff);
806         buf[off+3] = (byte)((n>>> 0)&0xff);
807     }
808     
809     public static abstract class DirFD extends FD {
810         private int pos = -2;
811         
812         protected abstract int size();
813         protected abstract String name(int n);
814         protected abstract int inode(int n);
815         protected abstract int myDev();
816         protected int parentInode() { return -1; }
817         protected int myInode() { return -1; }
818         
819         public int getdents(byte[] buf, int off, int len) {
820             int ooff = off;
821             int ino;
822             int reclen;
823             OUTER: for(;len > 0 && pos < size();pos++){
824                 switch(pos) {
825                             case -2:
826                     case -1:
827                                     ino = pos == -1 ? parentInode() : myInode();
828                         if(ino == -1) continue;
829                         reclen = 9 + (pos == -1 ? 2 : 1);
830                         if(reclen > len) break OUTER;
831                         buf[off+8] = '.';
832                         if(pos == -1) buf[off+9] = '.';
833                         break;
834                     default: {
835                         String f = name(pos);
836                         byte[] fb = getBytes(f);
837                         reclen = fb.length + 9;
838                         if(reclen > len) break OUTER;
839                         ino = inode(pos);
840                         System.arraycopy(fb,0,buf,off+8,fb.length);
841                     }
842                 }
843                 buf[off+reclen-1] = 0; // null terminate
844                 reclen = (reclen + 3) & ~3; // add padding
845                 putInt(buf,off,reclen);
846                 putInt(buf,off+4,ino);
847                 off += reclen;
848                 len -= reclen;    
849             }
850             return off-ooff;
851         }
852         
853         protected FStat _fstat() {
854             return new FStat() { 
855                 public int type() { return S_IFDIR; }
856                 public int inode() { return myInode(); }
857                 public int dev() { return myDev(); }
858             };
859         }
860     }
861         
862     public static class DevFS extends FS {
863         private static final int ROOT_INODE = 1;
864         private static final int NULL_INODE = 2;
865         private static final int ZERO_INODE = 3;
866         private static final int FD_INODE = 4;
867         private static final int FD_INODES = 32;
868         
869         private class DevFStat extends FStat {
870             public int dev() { return devno; }
871             public int mode() { return 0666; }
872             public int type() { return S_IFCHR; }
873             public int nlink() { return 1; }
874         }
875         
876         private abstract class DevDirFD extends DirFD {
877             public int myDev() { return devno; }
878         }
879         
880         private FD devZeroFD = new FD() {
881             public boolean readable() { return true; }
882             public boolean writable() { return true; }
883             public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
884             public int write(byte[] a, int off, int length) { return length; }
885             public int seek(int n, int whence) { return 0; }
886             public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
887         };
888         private FD devNullFD = new FD() {
889             public boolean readable() { return true; }
890             public boolean writable() { return true; }
891             public int read(byte[] a, int off, int length) { return 0; }
892             public int write(byte[] a, int off, int length) { return length; }
893             public int seek(int n, int whence) { return 0; }
894             public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
895         }; 
896         
897         public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
898             if(path.equals("null")) return devNullFD;
899             if(path.equals("zero")) return devZeroFD;
900             if(path.startsWith("fd/")) {
901                 int n;
902                 try {
903                     n = Integer.parseInt(path.substring(4));
904                 } catch(NumberFormatException e) {
905                     return null;
906                 }
907                 if(n < 0 || n >= OPEN_MAX) return null;
908                 if(r.fds[n] == null) return null;
909                 return r.fds[n].dup();
910             }
911             if(path.equals("fd")) {
912                 int count=0;
913                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
914                 final int[] files = new int[count];
915                 count = 0;
916                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
917                 return new DevDirFD() {
918                     public int myInode() { return FD_INODE; }
919                     public int parentInode() { return ROOT_INODE; }
920                     public int inode(int n) { return FD_INODES + n; }
921                     public String name(int n) { return Integer.toString(files[n]); }
922                     public int size() { return files.length; }
923                 };
924             }
925             if(path.equals("")) {
926                 return new DevDirFD() {
927                     public int myInode() { return ROOT_INODE; }
928                     // FEATURE: Get the real parent inode somehow
929                     public int parentInode() { return -1; }
930                     public int inode(int n) {
931                         switch(n) {
932                             case 0: return NULL_INODE;
933                             case 1: return ZERO_INODE;
934                             case 2: return FD_INODE;
935                             default: return -1;
936                         }
937                     }
938                     
939                     public String name(int n) {
940                         switch(n) {
941                                     case 0: return "null";
942                             case 1: return "zero";
943                             case 2: return "fd";
944                             default: return null;
945                         }
946                     }
947                     public int size() { return 3; }
948                 };
949             }
950             return null;
951         }
952         
953         public FStat stat(UnixRuntime r,String path) throws ErrnoException {
954             if(path.equals("null")) return devNullFD.fstat();
955             if(path.equals("zero")) return devZeroFD.fstat();            
956             if(path.startsWith("fd/")) {
957                 int n;
958                 try {
959                     n = Integer.parseInt(path.substring(4));
960                 } catch(NumberFormatException e) {
961                     return null;
962                 }
963                 if(n < 0 || n >= OPEN_MAX) return null;
964                 if(r.fds[n] == null) return null;
965                 return r.fds[n].fstat();
966             }
967             // FEATURE: inode stuff
968             if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
969             if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
970             return null;
971         }
972         
973         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EACCES); }
974     }
975 }