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