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