interpreter fixes
[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         // NOTE: For this little hack to work nestedvm.root MUST be "."
310         /*try {
311             System.err.println("Execing normalized path: " + normalizedPath);
312             if(true) return exec(new Interpreter(normalizedPath),argv,envp);
313         } catch(IOException e) { throw new Error(e); }*/
314         
315         Object o = gs.exec(this,normalizedPath);
316         if(o == null) return -ENOENT;
317
318         if(o instanceof Class) {
319             Class c = (Class) o;
320             try {
321                     return exec((UnixRuntime) c.newInstance(),argv,envp);
322             } catch(Exception e) {
323                     e.printStackTrace();
324                 return -ENOEXEC;
325             }
326         } else {
327             String[] command = (String[]) o;
328             String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
329             int p = command[0].lastIndexOf('/');
330             newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
331             p = 1;
332             if(command[1] != null) newArgv[p++] = command[1];
333             newArgv[p++] = "/" + normalizedPath;
334             for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
335             return exec(command[0],newArgv,envp);
336         }
337     }
338     
339     private int exec(UnixRuntime r, String[] argv, String[] envp) {     
340         
341         //System.err.println("Execing " + r);
342         for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
343         r.fds = fds;
344         r.closeOnExec = closeOnExec;
345         // make sure this doesn't get messed with these since we didn't copy them
346         fds = null;
347         closeOnExec = null;
348         
349         r.gs = gs;
350         r.sm = sm;
351         r.cwd = cwd;
352         r.pid = pid;
353         r.parent = parent;
354         r.start(argv,envp);
355                 
356         state = EXECED;
357         execedRuntime = r;
358         
359         return 0;   
360     }
361     
362     // FEATURE: Make sure fstat info is correct
363     // FEATURE: This could be faster if we did direct copies from each process' memory
364     // FEATURE: Check this logic one more time
365     public static class Pipe {
366         private final byte[] pipebuf = new byte[PIPE_BUF*4];
367         private int readPos;
368         private int writePos;
369         
370         public final FD reader = new Reader();
371         public final FD writer = new Writer();
372         
373         public class Reader extends FD {
374             protected FStat _fstat() { return new FStat(); }
375             public int read(byte[] buf, int off, int len) throws ErrnoException {
376                 if(len == 0) return 0;
377                 synchronized(Pipe.this) {
378                     while(writePos != -1 && readPos == writePos) {
379                         try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
380                     }
381                     if(writePos == -1) return 0; // eof
382                     len = Math.min(len,writePos-readPos);
383                     System.arraycopy(pipebuf,readPos,buf,off,len);
384                     readPos += len;
385                     if(readPos == writePos) Pipe.this.notify();
386                     return len;
387                 }
388             }
389             public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
390         }
391         
392         public class Writer extends FD {   
393             protected FStat _fstat() { return new FStat(); }
394             public int write(byte[] buf, int off, int len) throws ErrnoException {
395                 if(len == 0) return 0;
396                 synchronized(Pipe.this) {
397                     if(readPos == -1) throw new ErrnoException(EPIPE);
398                     if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
399                         // not enough space to atomicly write the data
400                         while(readPos != -1 && readPos != writePos) {
401                             try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
402                         }
403                         if(readPos == -1) throw new ErrnoException(EPIPE);
404                         readPos = writePos = 0;
405                     }
406                     len = Math.min(len,pipebuf.length - writePos);
407                     System.arraycopy(buf,off,pipebuf,writePos,len);
408                     if(readPos == writePos) Pipe.this.notify();
409                     writePos += len;
410                     return len;
411                 }
412             }
413             public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
414         }
415     }
416     
417     private int sys_pipe(int addr) {
418         Pipe pipe = new Pipe();
419         
420         int fd1 = addFD(pipe.reader);
421         if(fd1 < 0) return -ENFILE;
422         int fd2 = addFD(pipe.writer);
423         if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
424         
425         try {
426             memWrite(addr,fd1);
427             memWrite(addr+4,fd2);
428         } catch(FaultException e) {
429             closeFD(fd1);
430             closeFD(fd2);
431             return -EFAULT;
432         }
433         return 0;
434     }
435     
436     private int sys_dup2(int oldd, int newd) {
437         if(oldd == newd) return 0;
438         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
439         if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
440         if(fds[oldd] == null) return -EBADFD;
441         if(fds[newd] != null) fds[newd].close();
442         fds[newd] = fds[oldd].dup();
443         return 0;
444     }
445     
446     private int sys_dup(int oldd) {
447         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
448         if(fds[oldd] == null) return -EBADFD;
449         FD fd = fds[oldd].dup();
450         int newd = addFD(fd);
451         if(newd < 0) { fd.close(); return -ENFILE; }
452         return newd;
453     }
454     
455     private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
456         FStat s = gs.stat(this,normalizePath(cstring(cstring)));
457         if(s == null) return -ENOENT;
458         return stat(s,addr);
459     }
460     
461     private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
462         FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
463         if(s == null) return -ENOENT;
464         return stat(s,addr);
465     }
466     
467     private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
468         gs.mkdir(this,normalizePath(cstring(cstring)),mode);
469         return 0;
470     }
471    
472     private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
473         byte[] b = getBytes(cwd);
474         if(size == 0) return -EINVAL;
475         if(size < b.length+2) return -ERANGE;
476         memset(addr,'/',1);
477         copyout(b,addr+1,b.length);
478         memset(addr+b.length+1,0,1);
479         return addr;
480     }
481     
482     private int sys_chdir(int addr) throws ErrnoException, FaultException {
483         String path = normalizePath(cstring(addr));
484         //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
485         if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
486         cwd = path;
487         //System.err.println("Now: [" + cwd + "]");
488         return 0;
489     }
490     
491     private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
492         count = Math.min(count,MAX_CHUNK);
493         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
494         if(fds[fdn] == null) return -EBADFD;
495         byte[] buf = byteBuf(count);
496         int n = fds[fdn].getdents(buf,0,count);
497         copyout(buf,addr,n);
498         return n;
499     }
500     
501     //  FEATURE: Run through the fork/wait stuff one more time
502     public static class GlobalState {    
503         protected static final int OPEN = 1;
504         protected static final int STAT = 2;
505         protected static final int LSTAT = 3;
506         protected static final int MKDIR = 4;
507         
508         final UnixRuntime[] tasks;
509         int nextPID = 1;
510         
511         private MP[] mps = new MP[0];
512         private FS root;
513         
514         public GlobalState() { this(255); }
515         public GlobalState(int maxProcs) { this(maxProcs,true); }
516         public GlobalState(int maxProcs, boolean defaultMounts) {
517             tasks = new UnixRuntime[maxProcs+1];
518             if(defaultMounts) {
519                 addMount("/",new HostFS());
520                 addMount("/dev",new DevFS());
521             }
522         }
523         
524         private static class MP {
525             public MP(String path, FS fs) { this.path = path; this.fs = fs; }
526             public String path;
527             public FS fs;
528             public int compareTo(Object o) {
529                 if(!(o instanceof MP)) return 1;
530                 return -path.compareTo(((MP)o).path);
531             }
532         }
533         
534         public synchronized FS getMount(String path) {
535             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
536             if(path.equals("/")) return root;
537             path  = path.substring(1);
538             for(int i=0;i<mps.length;i++)
539                 if(mps[i].path.equals(path)) return mps[i].fs;
540             return null;
541         }
542         
543         public synchronized void addMount(String path, FS fs) {
544             if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
545             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
546             
547             if(fs.owner != null) fs.owner.removeMount(fs);
548             fs.owner = this;
549             
550             if(path.equals("/")) { root = fs; fs.devno = 1; return; }
551             path = path.substring(1);
552             int oldLength = mps.length;
553             MP[] newMPS = new MP[oldLength + 1];
554             if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
555             newMPS[oldLength] = new MP(path,fs);
556             Arrays.sort(newMPS);
557             mps = newMPS;
558             int highdevno = 0;
559             for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
560             fs.devno = highdevno + 2;
561         }
562         
563         public synchronized void removeMount(FS fs) {
564             for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
565             throw new IllegalArgumentException("mount point doesn't exist");
566         }
567         
568         public synchronized void removeMount(String path) {
569             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
570             if(path.equals("/")) {
571                 removeMount(-1);
572             } else {
573                 path = path.substring(1);
574                 int p;
575                 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
576                 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
577                 removeMount(p);
578             }
579         }
580         
581         private void removeMount(int index) {
582             if(index == -1) { root.owner = null; root = null; return; }
583             MP[] newMPS = new MP[mps.length - 1];
584             System.arraycopy(mps,0,newMPS,0,index);
585             System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
586             mps = newMPS;
587         }
588         
589         private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
590             int pl = normalizedPath.length();
591             if(pl != 0) {
592                 MP[] list;
593                 synchronized(this) { list = mps; }
594                 for(int i=0;i<list.length;i++) {
595                     MP mp = list[i];
596                     int mpl = mp.path.length();
597                     if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
598                         return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
599                 }
600             }
601             return dispatch(root,op,r,normalizedPath,arg1,arg2);
602         }
603         
604         private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
605             switch(op) {
606                 case OPEN: return fs.open(r,path,arg1,arg2);
607                 case STAT: return fs.stat(r,path);
608                 case LSTAT: return fs.lstat(r,path);
609                 case MKDIR: fs.mkdir(r,path,arg1); return null;
610                 default: throw new Error("should never happen");
611             }
612         }
613         
614         public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
615         public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
616         public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
617         public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
618         
619         private Hashtable execCache = new Hashtable();
620         private static class CacheEnt {
621             public final long time;
622             public final long size;
623             public final Object o;
624             public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
625         }
626
627         public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
628             FStat fstat = stat(r,path);
629             if(fstat == null) return null;
630             long mtime = fstat.mtime();
631             long size = fstat.size();
632             CacheEnt ent = (CacheEnt) execCache.get(path);
633             if(ent != null) {
634                 //System.err.println("Found cached entry for " + path);
635                 if(ent.time == mtime && ent.size == size) return ent.o;
636                 //System.err.println("Cache was out of date");
637                 execCache.remove(path);
638             }
639             FD fd = open(r,path,RD_ONLY,0);
640             if(fd == null) return null;
641             Seekable s = fd.seekable();
642             
643             String[] command  = null;
644
645             if(s == null) throw new ErrnoException(EACCES);
646             byte[] buf = new byte[4096];
647             
648             try {
649                 int n = s.read(buf,0,buf.length);
650                 if(n == -1) throw new ErrnoException(ENOEXEC);
651                 
652                 switch(buf[0]) {
653                     case '\177': // possible ELF
654                         if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
655                         if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
656                         break;
657                     case '#':
658                         if(n == 1) {
659                             int n2 = s.read(buf,1,buf.length-1);
660                             if(n2 == -1) throw new ErrnoException(ENOEXEC);
661                             n += n2;
662                         }
663                         if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
664                         int p = 2;
665                         n -= 2;
666                         OUTER: for(;;) {
667                             for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
668                             p += n;
669                             if(p == buf.length) break OUTER;
670                             n = s.read(buf,p,buf.length-p);
671                         }
672                         command = new String[2];
673                         int arg;
674                         for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
675                         if(arg < p) {
676                             int cmdEnd = arg;
677                             while(arg < p && buf[arg] == ' ') arg++;
678                             command[0] = new String(buf,2,cmdEnd);
679                             command[1] = arg < p ? new String(buf,arg,p-arg) : null;
680                         } else {
681                             command[0] = new String(buf,2,p-2);
682                         }
683                         //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
684                         break;
685                     default:
686                         throw new ErrnoException(ENOEXEC);
687                 }
688             } catch(IOException e) {
689                 fd.close();
690                 throw new ErrnoException(EIO);
691             }
692                         
693             if(command == null) {
694                 // its an elf binary
695                 try {
696                     s.seek(0);
697                     Class c = RuntimeCompiler.compile(s);
698                     //System.err.println("Compile succeeded: " + c);
699                     ent = new CacheEnt(mtime,size,c);
700                 } catch(Compiler.Exn e) {
701                     if(STDERR_DIAG) e.printStackTrace();
702                     throw new ErrnoException(ENOEXEC);
703                 } catch(IOException e) {
704                     if(STDERR_DIAG) e.printStackTrace();
705                     throw new ErrnoException(EIO);
706                 }
707             } else {
708                 ent = new CacheEnt(mtime,size,command);
709             }
710             
711             fd.close();
712             
713             execCache.put(path,ent);
714             return ent.o;
715         }
716     }
717     
718     public abstract static class FS {
719         GlobalState owner;
720         int devno;
721         
722         public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
723
724         // If this returns null it'll be truned into an ENOENT
725         public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
726         // If this returns null it'll be turned into an ENOENT
727         public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
728         public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
729     }
730         
731     // FEATURE: chroot support in here
732     private String normalizePath(String path) {
733         boolean absolute = path.startsWith("/");
734         int cwdl = cwd.length();
735         // NOTE: This isn't just a fast path, it handles cases the code below doesn't
736         if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
737             return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
738         
739         char[] in = new char[path.length()+1];
740         char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
741         int inp=0, outp=0;
742         
743         if(absolute) {
744             do { inp++; } while(in[inp] == '/');
745         } else if(cwdl != 0) {
746             cwd.getChars(0,cwdl,out,0);
747             outp = cwdl;
748         }
749             
750         path.getChars(0,path.length(),in,0);
751         while(in[inp] != 0) {
752             if(inp != 0) {
753                 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
754                 while(in[inp] == '/') inp++;
755             }
756             if(in[inp] == '\0') continue;
757             if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
758             if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
759             if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
760                 inp += 2;
761                 if(outp > 0) outp--;
762                 while(outp > 0 && out[outp] != '/') outp--;
763                 //System.err.println("After ..: " + new String(out,0,outp));
764                 continue;
765             }
766             inp++;
767             out[outp++] = '/';
768             out[outp++] = '.';
769         }
770         if(outp > 0 && out[outp-1] == '/') outp--;
771         //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
772         return new String(out,0,outp);
773     }
774     
775     FStat hostFStat(final File f, Object data) {
776         boolean e = false;
777         try {
778             FileInputStream fis = new FileInputStream(f);
779             switch(fis.read()) {
780                 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
781                 case '#': e = fis.read() == '!';
782             }
783             fis.close();
784         } catch(IOException e2) { } 
785         HostFS fs = (HostFS) data;
786         final int inode = fs.inodes.get(f.getAbsolutePath());
787         final int devno = fs.devno;
788         return new HostFStat(f,e) {
789             public int inode() { return inode; }
790             public int dev() { return devno; }
791         };
792     }
793
794     FD hostFSDirFD(File f, Object _fs) {
795         HostFS fs = (HostFS) _fs;
796         return fs.new HostDirFD(f);
797     }
798     
799     public static class HostFS extends FS {
800         InodeCache inodes = new InodeCache(4000);
801         protected File root;
802         public File getRoot() { return root; }
803         
804         private static File hostRootDir() {
805             if(getSystemProperty("nestedvm.root") != null) {
806                 File f = new File(getSystemProperty("nestedvm.root"));
807                 if(f.isDirectory()) return f;
808                 // fall through to case below
809             }
810             String cwd = getSystemProperty("user.dir");
811             File f = new File(cwd != null ? cwd : ".");
812             if(!f.exists()) throw new Error("Couldn't get File for cwd");
813             f = new File(f.getAbsolutePath());
814             while(f.getParent() != null) f = new File(f.getParent());
815             return f;
816         }
817         
818         private File hostFile(String path) {
819             char sep = File.separatorChar;
820             if(sep != '/') {
821                 char buf[] = path.toCharArray();
822                 for(int i=0;i<buf.length;i++) {
823                     char c = buf[i];
824                     if(c == '/') buf[i] = sep;
825                     else if(c == sep) buf[i] = '/';
826                 }
827                 path = new String(buf);
828             }
829             return new File(root,path);
830         }
831         
832         public HostFS() { this(hostRootDir()); }
833         public HostFS(String root) { this(new File(root)); }
834         public HostFS(File root) { this.root = root; }
835         
836         
837         public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
838             final File f = hostFile(path);
839             return r.hostFSOpen(f,flags,mode,this);
840         }
841         
842         public FStat stat(UnixRuntime r, String path) throws ErrnoException {
843             File f = hostFile(path);
844             if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
845             if(!f.exists()) return null;
846             return r.hostFStat(f,this);
847         }
848         
849         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
850             File f = hostFile(path);
851             if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
852             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
853             if(f.exists()) throw new ErrnoException(ENOTDIR);
854             File parent = f.getParentFile();
855             if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
856             if(!f.mkdir()) throw new ErrnoException(EIO);            
857         }
858         
859         public class HostDirFD extends DirFD {
860             private final File f;
861             private final File[] children;
862             public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
863             public int size() { return children.length; }
864             public String name(int n) { return children[n].getName(); }
865             public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
866             public int parentInode() {
867                 File parent = f.getParentFile();
868                 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
869             }
870             public int myInode() { return inodes.get(f.getAbsolutePath()); }
871             public int myDev() { return devno; } 
872         }
873     }
874     
875     private static void putInt(byte[] buf, int off, int n) {
876         buf[off+0] = (byte)((n>>>24)&0xff);
877         buf[off+1] = (byte)((n>>>16)&0xff);
878         buf[off+2] = (byte)((n>>> 8)&0xff);
879         buf[off+3] = (byte)((n>>> 0)&0xff);
880     }
881     
882     public static abstract class DirFD extends FD {
883         private int pos = -2;
884         
885         protected abstract int size();
886         protected abstract String name(int n);
887         protected abstract int inode(int n);
888         protected abstract int myDev();
889         protected int parentInode() { return -1; }
890         protected int myInode() { return -1; }
891         
892         public int getdents(byte[] buf, int off, int len) {
893             int ooff = off;
894             int ino;
895             int reclen;
896             OUTER: for(;len > 0 && pos < size();pos++){
897                 switch(pos) {
898                     case -2:
899                     case -1:
900                         ino = pos == -1 ? parentInode() : myInode();
901                         if(ino == -1) continue;
902                         reclen = 9 + (pos == -1 ? 2 : 1);
903                         if(reclen > len) break OUTER;
904                         buf[off+8] = '.';
905                         if(pos == -1) buf[off+9] = '.';
906                         break;
907                     default: {
908                         String f = name(pos);
909                         byte[] fb = getBytes(f);
910                         reclen = fb.length + 9;
911                         if(reclen > len) break OUTER;
912                         ino = inode(pos);
913                         System.arraycopy(fb,0,buf,off+8,fb.length);
914                     }
915                 }
916                 buf[off+reclen-1] = 0; // null terminate
917                 reclen = (reclen + 3) & ~3; // add padding
918                 putInt(buf,off,reclen);
919                 putInt(buf,off+4,ino);
920                 off += reclen;
921                 len -= reclen;    
922             }
923             return off-ooff;
924         }
925         
926         protected FStat _fstat() {
927             return new FStat() { 
928                 public int type() { return S_IFDIR; }
929                 public int inode() { return myInode(); }
930                 public int dev() { return myDev(); }
931             };
932         }
933     }
934         
935     public static class DevFS extends FS {
936         private static final int ROOT_INODE = 1;
937         private static final int NULL_INODE = 2;
938         private static final int ZERO_INODE = 3;
939         private static final int FD_INODE = 4;
940         private static final int FD_INODES = 32;
941         
942         private class DevFStat extends FStat {
943             public int dev() { return devno; }
944             public int mode() { return 0666; }
945             public int type() { return S_IFCHR; }
946             public int nlink() { return 1; }
947         }
948         
949         private abstract class DevDirFD extends DirFD {
950             public int myDev() { return devno; }
951         }
952         
953         private FD devZeroFD = new FD() {
954             public boolean readable() { return true; }
955             public boolean writable() { return true; }
956             public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
957             public int write(byte[] a, int off, int length) { return length; }
958             public int seek(int n, int whence) { return 0; }
959             public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
960         };
961         private FD devNullFD = new FD() {
962             public boolean readable() { return true; }
963             public boolean writable() { return true; }
964             public int read(byte[] a, int off, int length) { return 0; }
965             public int write(byte[] a, int off, int length) { return length; }
966             public int seek(int n, int whence) { return 0; }
967             public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
968         }; 
969         
970         public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
971             if(path.equals("null")) return devNullFD;
972             if(path.equals("zero")) return devZeroFD;
973             if(path.startsWith("fd/")) {
974                 int n;
975                 try {
976                     n = Integer.parseInt(path.substring(4));
977                 } catch(NumberFormatException e) {
978                     return null;
979                 }
980                 if(n < 0 || n >= OPEN_MAX) return null;
981                 if(r.fds[n] == null) return null;
982                 return r.fds[n].dup();
983             }
984             if(path.equals("fd")) {
985                 int count=0;
986                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
987                 final int[] files = new int[count];
988                 count = 0;
989                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
990                 return new DevDirFD() {
991                     public int myInode() { return FD_INODE; }
992                     public int parentInode() { return ROOT_INODE; }
993                     public int inode(int n) { return FD_INODES + n; }
994                     public String name(int n) { return Integer.toString(files[n]); }
995                     public int size() { return files.length; }
996                 };
997             }
998             if(path.equals("")) {
999                 return new DevDirFD() {
1000                     public int myInode() { return ROOT_INODE; }
1001                     // FEATURE: Get the real parent inode somehow
1002                     public int parentInode() { return -1; }
1003                     public int inode(int n) {
1004                         switch(n) {
1005                             case 0: return NULL_INODE;
1006                             case 1: return ZERO_INODE;
1007                             case 2: return FD_INODE;
1008                             default: return -1;
1009                         }
1010                     }
1011                     
1012                     public String name(int n) {
1013                         switch(n) {
1014                             case 0: return "null";
1015                             case 1: return "zero";
1016                             case 2: return "fd";
1017                             default: return null;
1018                         }
1019                     }
1020                     public int size() { return 3; }
1021                 };
1022             }
1023             return null;
1024         }
1025         
1026         public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1027             if(path.equals("null")) return devNullFD.fstat();
1028             if(path.equals("zero")) return devZeroFD.fstat();            
1029             if(path.startsWith("fd/")) {
1030                 int n;
1031                 try {
1032                     n = Integer.parseInt(path.substring(4));
1033                 } catch(NumberFormatException e) {
1034                     return null;
1035                 }
1036                 if(n < 0 || n >= OPEN_MAX) return null;
1037                 if(r.fds[n] == null) return null;
1038                 return r.fds[n].fstat();
1039             }
1040             // FEATURE: inode stuff
1041             if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1042             if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1043             return null;
1044         }
1045         
1046         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EACCES); }
1047     }
1048 }