remove debugging stuff
[nestedvm.git] / src / org / ibex / nestedvm / UnixRuntime.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.nestedvm;
6
7 import org.ibex.nestedvm.util.*;
8 // HACK: This is ugly, this stuff needs to be in org.ibex.util or something
9 import org.ibex.classgen.util.Sort;
10 import java.io.*;
11 import java.util.*;
12 import java.net.*;
13 import java.lang.reflect.*; // For lazily linked RuntimeCompiler
14
15 // FEATURE: vfork
16
17 public abstract class UnixRuntime extends Runtime implements Cloneable {
18     /** The pid of this "process" */
19     private int pid;
20     private UnixRuntime parent;
21     public final int getPid() { return pid; }
22     
23     private static final GlobalState defaultGS = new GlobalState();
24     private GlobalState gs;
25     public void setGlobalState(GlobalState gs) {
26         if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running");
27         if(gs == null) throw new NullPointerException("gs is null");
28         this.gs = gs;
29     }
30     
31     /** proceses' current working directory - absolute path WITHOUT leading slash
32         "" = root, "bin" = /bin "usr/bin" = /usr/bin */
33     private String cwd;
34     
35     /** The runtime that should be run next when in state == EXECED */
36     private UnixRuntime execedRuntime;
37
38     private Object children; // used only for synchronizatin
39     private Vector activeChildren;
40     private Vector exitedChildren;
41     
42     protected UnixRuntime(int pageSize, int totalPages) { this(pageSize,totalPages,false); }
43     protected UnixRuntime(int pageSize, int totalPages, boolean exec) {
44         super(pageSize,totalPages,exec);
45                 
46         if(!exec) {
47             gs = defaultGS;
48             String userdir = Platform.getProperty("user.dir");
49             String nvroot = Platform.getProperty("nestedvm.root");
50             cwd = "";
51             if(userdir != null && nvroot == null) {
52                 if(userdir.startsWith("/") && File.separatorChar == '/') {
53                     cwd = userdir.substring(1);
54                 } else {
55                     Vector vec = new Vector();
56                     File root = HostFS.hostRootDir();
57                     String s = new File(userdir).getAbsolutePath();
58                     File d = new File(s);
59                     System.err.println(s);
60                     System.err.println(d);
61                     while(!d.equals(root)) {
62                         vec.addElement(d.getName());
63                         if((s = d.getParent()) == null) break;
64                         d = new File(s);
65                     }
66                     if(s != null)
67                         for(int i=vec.size()-1;i>=0;i--) cwd += (String) vec.elementAt(i) + (i==0?"":"/");
68                 }
69             }
70         }
71     }
72     
73     private static String posixTZ() {
74         StringBuffer sb = new StringBuffer();
75         TimeZone zone = TimeZone.getDefault();
76         int off = zone.getRawOffset() / 1000;
77         sb.append(Platform.timeZoneGetDisplayName(zone,false,false));
78         if(off > 0) sb.append("-");
79         else off = -off;
80         sb.append(off/3600); off = off%3600;
81         if(off > 0) sb.append(":").append(off/60); off=off%60;
82         if(off > 0) sb.append(":").append(off);
83         if(zone.useDaylightTime())
84             sb.append(Platform.timeZoneGetDisplayName(zone,true,false));
85         return sb.toString();
86     }
87     
88     private static boolean envHas(String key,String[] environ) {
89         for(int i=0;i<environ.length;i++)
90             if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
91         return false;
92     }
93     
94     String[] createEnv(String[] extra) {
95         String[] defaults = new String[6];
96         int n=0;
97         if(extra == null) extra = new String[0];
98         if(!envHas("USER",extra) && Platform.getProperty("user.name") != null)
99             defaults[n++] = "USER=" + Platform.getProperty("user.name");
100         if(!envHas("HOME",extra) && Platform.getProperty("user.home") != null)
101             defaults[n++] = "HOME=" + Platform.getProperty("user.home");
102         if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
103         if(!envHas("TERM",extra) && !win32Hacks)  defaults[n++] = "TERM=vt100";
104         if(!envHas("TZ",extra))    defaults[n++] = "TZ=" + posixTZ();
105         if(!envHas("PATH",extra))  defaults[n++] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin";
106         String[] env = new String[extra.length+n];
107         for(int i=0;i<n;i++) env[i] = defaults[i];
108         for(int i=0;i<extra.length;i++) env[n++] = extra[i];
109         return env;
110     }
111     
112     private static class ProcessTableFullExn extends RuntimeException { }
113     
114     void _started() {
115         UnixRuntime[] tasks = gs.tasks;
116         synchronized(gs) {
117             if(pid != 0) {
118                 UnixRuntime prev = tasks[pid];
119                 if(prev == null || prev == this || prev.pid != pid || prev.parent != parent)
120                     throw new Error("should never happen");
121                 synchronized(parent.children) {
122                     int i = parent.activeChildren.indexOf(prev);
123                     if(i == -1) throw new Error("should never happen");
124                     parent.activeChildren.setElementAt(this,i);
125                 }
126             } else {
127                 int newpid = -1;
128                 int nextPID = gs.nextPID;
129                 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
130                 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
131                 if(newpid == -1) throw new ProcessTableFullExn();
132                 pid = newpid;
133                 gs.nextPID = newpid + 1;
134             }
135             tasks[pid] = this;
136         }
137     }
138     
139     int _syscall(int syscall, int a, int b, int c, int d, int e, int f) throws ErrnoException, FaultException {
140         switch(syscall) {
141             case SYS_kill: return sys_kill(a,b);
142             case SYS_fork: return sys_fork();
143             case SYS_pipe: return sys_pipe(a);
144             case SYS_dup2: return sys_dup2(a,b);
145             case SYS_dup: return sys_dup(a);
146             case SYS_waitpid: return sys_waitpid(a,b,c);
147             case SYS_stat: return sys_stat(a,b);
148             case SYS_lstat: return sys_lstat(a,b);
149             case SYS_mkdir: return sys_mkdir(a,b);
150             case SYS_getcwd: return sys_getcwd(a,b);
151             case SYS_chdir: return sys_chdir(a);
152             case SYS_exec: return sys_exec(a,b,c);
153             case SYS_getdents: return sys_getdents(a,b,c,d);
154             case SYS_unlink: return sys_unlink(a);
155             case SYS_getppid: return sys_getppid();
156             case SYS_socket: return sys_socket(a,b,c);
157             case SYS_connect: return sys_connect(a,b,c);
158             case SYS_resolve_hostname: return sys_resolve_hostname(a,b,c);
159             case SYS_setsockopt: return sys_setsockopt(a,b,c,d,e);
160             case SYS_getsockopt: return sys_getsockopt(a,b,c,d,e);
161             case SYS_bind: return sys_bind(a,b,c);
162             case SYS_listen: return sys_listen(a,b);
163             case SYS_accept: return sys_accept(a,b,c);
164             case SYS_shutdown: return sys_shutdown(a,b);
165             case SYS_sysctl: return sys_sysctl(a,b,c,d,e,f);
166             case SYS_sendto: return sys_sendto(a,b,c,d,e,f);
167             case SYS_recvfrom: return sys_recvfrom(a,b,c,d,e,f);
168             case SYS_select: return sys_select(a,b,c,d,e);
169             case SYS_access: return sys_access(a,b);
170             case SYS_realpath: return sys_realpath(a,b);
171             case SYS_chown: return sys_chown(a,b,c);
172             case SYS_lchown: return sys_chown(a,b,c);
173             case SYS_fchown: return sys_fchown(a,b,c);
174             case SYS_chmod: return sys_chmod(a,b,c);
175             case SYS_fchmod: return sys_fchmod(a,b,c);
176             case SYS_umask: return sys_umask(a);
177             
178             default: return super._syscall(syscall,a,b,c,d,e,f);
179         }
180     }
181     
182     FD _open(String path, int flags, int mode) throws ErrnoException {
183         return gs.open(this,normalizePath(path),flags,mode);
184     }
185     
186     private int sys_getppid() {
187         return parent == null ? 1 : parent.pid;
188     }
189     
190     private int sys_chown(int fileAddr, int uid, int gid) {
191         return 0;
192     }
193     private int sys_lchown(int fileAddr, int uid, int gid) {
194         return 0;
195     }
196     private int sys_fchown(int fd, int uid, int gid) {
197         return 0;
198     }
199     private int sys_chmod(int fileAddr, int uid, int gid) {
200         return 0;
201     }
202     private int sys_fchmod(int fd, int uid, int gid) {
203         return 0;
204     }
205     private int sys_umask(int mask) {
206         return 0;
207     }
208     
209     private int sys_access(int cstring, int mode) throws ErrnoException, ReadFaultException {
210         // FEATURE: sys_access
211         return gs.stat(this,cstring(cstring)) == null ? -ENOENT : 0;
212     }
213     
214     private int sys_realpath(int inAddr, int outAddr) throws FaultException {
215         String s = normalizePath(cstring(inAddr));
216         byte[] b = getNullTerminatedBytes(s);
217         if(b.length > PATH_MAX) return -ERANGE;
218         copyout(b,outAddr,b.length);
219         return 0;
220     }
221
222     // FEATURE: Signal handling
223     // check flag only on backwards jumps to basic blocks without compulsatory checks 
224     // (see A Portable Research Framework for the Execution of Java Bytecode - Etienne Gagnon, Chapter 2)
225     
226     /** The kill syscall.
227        SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
228        SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
229        Anything else terminates the process. */
230     private int sys_kill(int pid, int signal) {
231         // This will only be called by raise() in newlib to invoke the default handler
232         // We don't have to worry about actually delivering the signal
233         if(pid != pid) return -ESRCH;
234         if(signal < 0 || signal >= 32) return -EINVAL;
235         switch(signal) {
236             case 0: return 0;
237             case 17: // SIGSTOP
238             case 18: // SIGTSTP
239             case 21: // SIGTTIN
240             case 22: // SIGTTOU
241             case 19: // SIGCONT
242             case 20: // SIGCHLD
243             case 23: // SIGIO
244             case 28: // SIGWINCH
245                 break;
246             default:
247                 exit(128+signal, true);
248         }
249         return 0;
250     }
251
252     private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
253         final int WNOHANG = 1;
254         if((options & ~(WNOHANG)) != 0) return -EINVAL;
255         if(pid == 0 || pid < -1) {
256             if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
257             return -ECHILD;
258         }
259         boolean blocking = (options&WNOHANG)==0;
260         
261         if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
262         if(children == null) return blocking ? -ECHILD : 0;
263         
264         UnixRuntime done = null;
265         
266         synchronized(children) {
267             for(;;) {
268                 if(pid == -1) {
269                     if(exitedChildren.size() > 0) {
270                         done = (UnixRuntime)exitedChildren.elementAt(exitedChildren.size() - 1);
271                         exitedChildren.removeElementAt(exitedChildren.size() - 1);
272                     }
273                 } else if(pid > 0) {
274                     if(pid >= gs.tasks.length) return -ECHILD;
275                     UnixRuntime t = gs.tasks[pid];
276                     if(t.parent != this) return -ECHILD;
277                     if(t.state == EXITED) {
278                         if(!exitedChildren.removeElement(t)) throw new Error("should never happen");
279                         done = t;
280                     }
281                 } else {
282                     // process group stuff, EINVAL returned above
283                         throw new Error("should never happen");
284                 }
285                 if(done == null) {
286                     if(!blocking) return 0;
287                     try { children.wait(); } catch(InterruptedException e) {}
288                     //System.err.println("waitpid woke up: " + exitedChildren.size());
289                 } else {
290                     gs.tasks[done.pid] = null;
291                     break;
292                 }
293             }
294         }
295         if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
296         return done.pid;
297     }
298     
299     
300     void _exited() {
301         if(children != null) synchronized(children) {
302             for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
303                 UnixRuntime child = (UnixRuntime) e.nextElement();
304                 gs.tasks[child.pid] = null;
305             }
306             exitedChildren.removeAllElements();
307             for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
308                 UnixRuntime child = (UnixRuntime) e.nextElement();
309                 child.parent = null;
310             }
311             activeChildren.removeAllElements();
312         }
313         
314         UnixRuntime _parent = parent;
315         if(_parent == null) {
316             gs.tasks[pid] = null;
317         } else {
318             synchronized(_parent.children) {
319                 if(parent == null) {
320                     gs.tasks[pid] = null;
321                 } else {
322                     if(!parent.activeChildren.removeElement(this)) throw new Error("should never happen _exited: pid: " + pid);
323                     parent.exitedChildren.addElement(this);
324                     parent.children.notify();
325                 }
326             }
327         }
328     }
329     
330     protected Object clone() throws CloneNotSupportedException {
331         UnixRuntime r = (UnixRuntime) super.clone();
332         r.pid = 0;
333         r.parent = null;
334         r.children = null;
335         r.activeChildren = r.exitedChildren = null;
336         return r;
337     }
338
339     private int sys_fork() {
340         final UnixRuntime r;
341         
342         try {
343             r = (UnixRuntime) clone();
344         } catch(Exception e) {
345             e.printStackTrace();
346             return -ENOMEM;
347         }
348
349         r.parent = this;
350
351         try {
352             r._started();
353         } catch(ProcessTableFullExn e) {
354             return -ENOMEM;
355         }
356
357         //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
358         if(children == null) {
359             children = new Object();
360             activeChildren = new Vector();
361             exitedChildren = new Vector();
362         }
363         activeChildren.addElement(r);
364         
365         CPUState state = new CPUState();
366         getCPUState(state);
367         state.r[V0] = 0; // return 0 to child
368         state.pc += 4; // skip over syscall instruction
369         r.setCPUState(state);
370         r.state = PAUSED;
371         
372         new ForkedProcess(r);
373         
374         return r.pid;
375     }
376     
377     public static final class ForkedProcess extends Thread {
378         private final UnixRuntime initial;
379         public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
380         public void run() { UnixRuntime.executeAndExec(initial); }
381     }
382     
383     public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
384     public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
385     
386     public static int executeAndExec(UnixRuntime r) {
387         for(;;) {
388             for(;;) {
389                 if(r.execute()) break;
390                 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
391             }
392             if(r.state != EXECED) return r.exitStatus();
393             r = r.execedRuntime;
394         }
395     }
396      
397     private String[] readStringArray(int addr) throws ReadFaultException {
398         int count = 0;
399         for(int p=addr;memRead(p) != 0;p+=4) count++;
400         String[] a = new String[count];
401         for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
402         return a;
403     }
404     
405     private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
406         return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
407     }
408     
409     private final static Method runtimeCompilerCompile;
410     static {
411         Method m;
412         try {
413             m = Class.forName("org.ibex.nestedvm.RuntimeCompiler").getMethod("compile",new Class[]{Seekable.class,String.class,String.class});
414         } catch(NoSuchMethodException e) {
415             m = null;
416         } catch(ClassNotFoundException e) {
417             m = null;
418         }
419         runtimeCompilerCompile = m;
420     }
421             
422     public Class runtimeCompile(Seekable s, String sourceName) throws IOException {
423         if(runtimeCompilerCompile == null) {
424             if(STDERR_DIAG) System.err.println("WARNING: Exec attempted but RuntimeCompiler not found!");
425             return null;
426         }
427         
428         try {
429             return (Class) runtimeCompilerCompile.invoke(null,new Object[]{s,"unixruntime,maxinsnpermethod=256,lessconstants",sourceName});
430         } catch(IllegalAccessException e) {
431             e.printStackTrace();
432             return null;
433         } catch(InvocationTargetException e) {
434             Throwable t = e.getTargetException();
435             if(t instanceof IOException) throw (IOException) t;
436             if(t instanceof RuntimeException) throw (RuntimeException) t;
437             if(t instanceof Error) throw (Error) t;
438             if(STDERR_DIAG) t.printStackTrace();
439             return null;
440         }
441     }
442         
443     private int exec(String path, String[] argv, String[] envp) throws ErrnoException {
444         if(argv.length == 0) argv = new String[]{""};
445         // HACK: Hideous hack to make a standalone busybox possible
446         if(path.equals("bin/busybox") && getClass().getName().endsWith("BusyBox"))
447             return execClass(getClass(),argv,envp);
448         
449         // NOTE: For this little hack to work nestedvm.root MUST be "."
450         /*try {
451             System.err.println("Execing normalized path: " + normalizedPath);
452             if(true) return exec(new Interpreter(normalizedPath),argv,envp);
453         } catch(IOException e) { throw new Error(e); }*/
454         
455         FStat fstat = gs.stat(this,path);
456         if(fstat == null) return -ENOENT;
457         GlobalState.CacheEnt ent = (GlobalState.CacheEnt) gs.execCache.get(path);
458         long mtime = fstat.mtime();
459         long size = fstat.size();
460         if(ent != null) {
461             //System.err.println("Found cached entry for " + path);
462             if(ent.time ==mtime && ent.size == size) {
463                 if(ent.o instanceof Class)
464                     return execClass((Class) ent.o,argv,envp);
465                 if(ent.o instanceof String[]) 
466                     return execScript(path,(String[]) ent.o,argv,envp);
467                 throw new Error("should never happen");
468             }
469             //System.err.println("Cache was out of date");
470             gs.execCache.remove(path);
471         }
472         
473         FD fd = gs.open(this,path,RD_ONLY,0);
474         if(fd == null) throw new ErrnoException(ENOENT);
475         Seekable s = fd.seekable();        
476         if(s == null) throw new ErrnoException(EACCES);
477         
478         byte[] buf = new byte[4096];
479         
480         try {
481             int n = s.read(buf,0,buf.length);
482             if(n == -1) throw new ErrnoException(ENOEXEC);
483             
484             switch(buf[0]) {
485                 case '\177': // possible ELF
486                     if(n < 4) s.tryReadFully(buf,n,4-n);
487                     if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') return -ENOEXEC;
488                     s.seek(0);
489                     if(STDERR_DIAG) System.err.println("Running RuntimeCompiler for " + path);
490                     Class c = runtimeCompile(s,path);
491                     if(STDERR_DIAG) System.err.println("RuntimeCompiler finished for " + path);
492                     if(c == null) throw new ErrnoException(ENOEXEC);
493                     gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,c));
494                     return execClass(c,argv,envp);
495                 case '#':
496                     if(n == 1) {
497                         int n2 = s.read(buf,1,buf.length-1);
498                         if(n2 == -1) return -ENOEXEC;
499                         n += n2;
500                     }
501                     if(buf[1] != '!') return -ENOEXEC;
502                     int p = 2;
503                     n -= 2;
504                     OUTER: for(;;) {
505                         for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
506                             p += n;
507                         if(p == buf.length) break OUTER;
508                         n = s.read(buf,p,buf.length-p);
509                     }
510                     int cmdStart = 2;
511                     for(;cmdStart<p;cmdStart++) if(buf[cmdStart]!=' ') break;
512                     if(cmdStart == p) throw new ErrnoException(ENOEXEC);
513                     int argStart = cmdStart;
514                     for(;argStart<p;argStart++) if(buf[argStart] == ' ') break;
515                     int cmdEnd = argStart;
516                     while(argStart < p && buf[argStart] == ' ') argStart++;
517                     String[] command = new String[] {
518                         new String(buf,cmdStart,cmdEnd-cmdStart),
519                         argStart < p ? new String(buf,argStart,p-argStart) : null
520                     };
521                     gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,command));
522                     return execScript(path,command,argv,envp);
523                 default:
524                     return -ENOEXEC;
525             }
526         } catch(IOException e) {
527             return -EIO;
528         } finally {
529             fd.close();
530         }        
531     }
532     
533     public int execScript(String path, String[] command, String[] argv, String[] envp) throws ErrnoException {
534         String[] newArgv = new String[argv.length-1 + (command[1] != null ? 3 : 2)];
535         int p = command[0].lastIndexOf('/');
536         newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
537         newArgv[1] = "/" + path;
538         p = 2;
539         if(command[1] != null) newArgv[p++] = command[1];
540         for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
541         if(p != newArgv.length) throw new Error("p != newArgv.length");
542         System.err.println("Execing: " + command[0]);
543         for(int i=0;i<newArgv.length;i++) System.err.println("execing [" + i + "] " + newArgv[i]);
544         return exec(command[0],newArgv,envp);
545     }
546     
547     public int execClass(Class c,String[] argv, String[] envp) {
548         try {
549             UnixRuntime r = (UnixRuntime) c.getDeclaredConstructor(new Class[]{Boolean.TYPE}).newInstance(new Object[]{Boolean.TRUE});
550             return exec(r,argv,envp);
551         } catch(Exception e) {
552             e.printStackTrace();
553             return -ENOEXEC;
554         }
555     }
556     
557     private int exec(UnixRuntime r, String[] argv, String[] envp) {     
558         //System.err.println("Execing " + r);
559         for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
560         r.fds = fds;
561         r.closeOnExec = closeOnExec;
562         // make sure this doesn't get messed with these since we didn't copy them
563         fds = null;
564         closeOnExec = null;
565         
566         r.gs = gs;
567         r.sm = sm;
568         r.cwd = cwd;
569         r.pid = pid;
570         r.parent = parent;
571         r.start(argv,envp);
572                 
573         state = EXECED;
574         execedRuntime = r;
575         
576         return 0;   
577     }
578     
579     static class Pipe {
580         private final byte[] pipebuf = new byte[PIPE_BUF*4];
581         private int readPos;
582         private int writePos;
583         
584         public final FD reader = new Reader();
585         public final FD writer = new Writer();
586         
587         public class Reader extends FD {
588             protected FStat _fstat() { return new SocketFStat(); }
589             public int read(byte[] buf, int off, int len) throws ErrnoException {
590                 if(len == 0) return 0;
591                 synchronized(Pipe.this) {
592                     while(writePos != -1 && readPos == writePos) {
593                         try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
594                     }
595                     if(writePos == -1) return 0; // eof
596                     len = Math.min(len,writePos-readPos);
597                     System.arraycopy(pipebuf,readPos,buf,off,len);
598                     readPos += len;
599                     if(readPos == writePos) Pipe.this.notify();
600                     return len;
601                 }
602             }
603             public int flags() { return O_RDONLY; }
604             public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
605         }
606         
607         public class Writer extends FD {   
608             protected FStat _fstat() { return new SocketFStat(); }
609             public int write(byte[] buf, int off, int len) throws ErrnoException {
610                 if(len == 0) return 0;
611                 synchronized(Pipe.this) {
612                     if(readPos == -1) throw new ErrnoException(EPIPE);
613                     if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
614                         // not enough space to atomicly write the data
615                         while(readPos != -1 && readPos != writePos) {
616                             try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
617                         }
618                         if(readPos == -1) throw new ErrnoException(EPIPE);
619                         readPos = writePos = 0;
620                     }
621                     len = Math.min(len,pipebuf.length - writePos);
622                     System.arraycopy(buf,off,pipebuf,writePos,len);
623                     if(readPos == writePos) Pipe.this.notify();
624                     writePos += len;
625                     return len;
626                 }
627             }
628             public int flags() { return O_WRONLY; }
629             public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
630         }
631     }
632     
633     private int sys_pipe(int addr) {
634         Pipe pipe = new Pipe();
635         
636         int fd1 = addFD(pipe.reader);
637         if(fd1 < 0) return -ENFILE;
638         int fd2 = addFD(pipe.writer);
639         if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
640         
641         try {
642             memWrite(addr,fd1);
643             memWrite(addr+4,fd2);
644         } catch(FaultException e) {
645             closeFD(fd1);
646             closeFD(fd2);
647             return -EFAULT;
648         }
649         return 0;
650     }
651     
652     private int sys_dup2(int oldd, int newd) {
653         if(oldd == newd) return 0;
654         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
655         if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
656         if(fds[oldd] == null) return -EBADFD;
657         if(fds[newd] != null) fds[newd].close();
658         fds[newd] = fds[oldd].dup();
659         return 0;
660     }
661     
662     private int sys_dup(int oldd) {
663         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
664         if(fds[oldd] == null) return -EBADFD;
665         FD fd = fds[oldd].dup();
666         int newd = addFD(fd);
667         if(newd < 0) { fd.close(); return -ENFILE; }
668         return newd;
669     }
670     
671     private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
672         FStat s = gs.stat(this,normalizePath(cstring(cstring)));
673         if(s == null) return -ENOENT;
674         return stat(s,addr);
675     }
676     
677     private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
678         FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
679         if(s == null) return -ENOENT;
680         return stat(s,addr);
681     }
682     
683     private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
684         gs.mkdir(this,normalizePath(cstring(cstring)),mode);
685         return 0;
686     }
687    
688     private int sys_unlink(int cstring) throws FaultException, ErrnoException {
689         gs.unlink(this,normalizePath(cstring(cstring)));
690         return 0;
691     }
692     
693     private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
694         byte[] b = getBytes(cwd);
695         if(size == 0) return -EINVAL;
696         if(size < b.length+2) return -ERANGE;
697         memset(addr,'/',1);
698         copyout(b,addr+1,b.length);
699         memset(addr+b.length+1,0,1);
700         return addr;
701     }
702     
703     private int sys_chdir(int addr) throws ErrnoException, FaultException {
704         String path = normalizePath(cstring(addr));
705         FStat st = gs.stat(this,path);
706         if(st == null) return -ENOENT;
707         if(st.type() != FStat.S_IFDIR) return -ENOTDIR;
708         cwd = path;
709         return 0;
710     }
711     
712     private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
713         count = Math.min(count,MAX_CHUNK);
714         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
715         if(fds[fdn] == null) return -EBADFD;
716         byte[] buf = byteBuf(count);
717         int n = fds[fdn].getdents(buf,0,count);
718         copyout(buf,addr,n);
719         return n;
720     }
721     
722     static class SocketFD extends FD {
723         public static final int TYPE_STREAM = 0;
724         public static final int TYPE_DGRAM = 1;
725         public static final int LISTEN = 2;
726         public int type() { return flags & 1; }
727         public boolean listen() { return (flags & 2) != 0; }
728         
729         int flags;
730         int options;
731         
732         Socket s;
733         ServerSocket ss;
734         DatagramSocket ds;
735         
736         InetAddress bindAddr;
737         int bindPort = -1;
738         InetAddress connectAddr;
739         int connectPort = -1;
740         
741         DatagramPacket dp;
742         InputStream is;
743         OutputStream os; 
744         
745         private static final byte[] EMPTY = new byte[0];
746         public SocketFD(int type) {
747                 flags = type;
748                 if(type == TYPE_DGRAM)
749                         dp = new DatagramPacket(EMPTY,0);
750         }
751         
752         public void setOptions() {
753             try {
754                 if(s != null && type() == TYPE_STREAM && !listen()) {
755                     Platform.socketSetKeepAlive(s,(options & SO_KEEPALIVE) != 0);
756                 }
757             } catch(SocketException e) {
758                 if(STDERR_DIAG) e.printStackTrace();
759             }
760         }
761         
762         public void _close() {
763             try {
764                if(s != null) s.close();
765                if(ss != null) ss.close();
766                if(ds != null) ds.close();
767             } catch(IOException e) {
768                 /* ignore */
769             }
770         }
771         
772         public int read(byte[] a, int off, int length) throws ErrnoException {
773             if(type() == TYPE_DGRAM) return recvfrom(a,off,length,null,null);
774             if(is == null) throw new ErrnoException(EPIPE);
775             try {
776                 int n = is.read(a,off,length);
777                 return n < 0 ? 0 : n;
778             } catch(IOException e) {
779                 throw new ErrnoException(EIO);
780             }
781         }    
782         
783         public int recvfrom(byte[] a, int off, int length, InetAddress[] sockAddr, int[] port) throws ErrnoException {
784                 if(type() == TYPE_STREAM) return read(a,off,length);
785                 
786                 if(off != 0) throw new IllegalArgumentException("off must be 0");
787                 dp.setData(a);
788                 dp.setLength(length);
789                 try {
790                         if(ds == null) ds = new DatagramSocket();
791                         ds.receive(dp);
792                 } catch(IOException e) {
793                         if(STDERR_DIAG) e.printStackTrace();
794                         throw new ErrnoException(EIO);
795                 }
796                 if(sockAddr != null) {
797                         sockAddr[0] = dp.getAddress();
798                         port[0] = dp.getPort();
799                 }
800                 return dp.getLength();
801         }
802         
803         public int write(byte[] a, int off, int length) throws ErrnoException {
804             if(type() == TYPE_DGRAM) return  sendto(a,off,length,null,-1);
805
806             if(os == null) throw new ErrnoException(EPIPE);
807             try {
808                 os.write(a,off,length);
809                 return length;
810             } catch(IOException e) {
811                 throw new ErrnoException(EIO);
812             }
813         }
814         
815         public int sendto(byte[] a, int off, int length, InetAddress destAddr, int destPort) throws ErrnoException {
816                 if(off != 0) throw new IllegalArgumentException("off must be 0");
817                 if(type() == TYPE_STREAM) return write(a,off,length);
818                 
819                 if(destAddr == null) {
820                         destAddr = connectAddr;
821                         destPort = connectPort;
822                         
823                         if(destAddr == null) throw new ErrnoException(ENOTCONN);
824                 }
825                 
826                 dp.setAddress(destAddr);
827                 dp.setPort(destPort);
828                 dp.setData(a);
829                 dp.setLength(length);
830                 
831                 try {
832                         if(ds == null) ds = new DatagramSocket();
833                         ds.send(dp);
834                 } catch(IOException e) {
835                         if(STDERR_DIAG) e.printStackTrace();
836                         if("Network is unreachable".equals(e.getMessage())) throw new ErrnoException(EHOSTUNREACH);
837                         throw new ErrnoException(EIO);
838                 }
839                 return dp.getLength();
840         }
841
842         public int flags() { return O_RDWR; }
843         public FStat _fstat() { return new SocketFStat(); }
844     }
845     
846     private int sys_socket(int domain, int type, int proto) {
847         if(domain != AF_INET || (type != SOCK_STREAM && type != SOCK_DGRAM)) return -EPROTONOSUPPORT;
848         return addFD(new SocketFD(type == SOCK_STREAM ? SocketFD.TYPE_STREAM : SocketFD.TYPE_DGRAM));
849     }
850     
851     private SocketFD getSocketFD(int fdn) throws ErrnoException {
852         if(fdn < 0 || fdn >= OPEN_MAX) throw new ErrnoException(EBADFD);
853         if(fds[fdn] == null) throw new ErrnoException(EBADFD);
854         if(!(fds[fdn] instanceof SocketFD)) throw new ErrnoException(ENOTSOCK);
855         
856         return (SocketFD) fds[fdn];
857     }
858     
859     private int sys_connect(int fdn, int addr, int namelen) throws ErrnoException, FaultException {
860         SocketFD fd = getSocketFD(fdn);
861         
862         if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
863         int word1 = memRead(addr);
864         if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
865         int port = word1 & 0xffff;
866         byte[] ip = new byte[4];
867         copyin(addr+4,ip,4);
868         
869         InetAddress inetAddr;
870         try {
871             inetAddr = Platform.inetAddressFromBytes(ip);
872         } catch(UnknownHostException e) {
873             return -EADDRNOTAVAIL;
874         }
875         
876         fd.connectAddr = inetAddr;
877         fd.connectPort = port;
878         
879         try {
880             switch(fd.type()) {
881                 case SocketFD.TYPE_STREAM: {
882                     Socket s = new Socket(inetAddr,port);
883                     fd.s = s;
884                     fd.setOptions();
885                     fd.is = s.getInputStream();
886                     fd.os = s.getOutputStream();
887                     break;
888                 }
889                 case SocketFD.TYPE_DGRAM:
890                     break;
891                 default:
892                     throw new Error("should never happen");
893             }
894         } catch(IOException e) {
895             return -ECONNREFUSED;
896         }
897         
898         return 0;
899     }
900     
901     private int sys_resolve_hostname(int chostname, int addr, int sizeAddr) throws FaultException {
902         String hostname = cstring(chostname);
903         int size = memRead(sizeAddr);
904         InetAddress[] inetAddrs;
905         try {
906             inetAddrs = InetAddress.getAllByName(hostname);
907         } catch(UnknownHostException e) {
908             return HOST_NOT_FOUND;
909         }
910         int count = min(size/4,inetAddrs.length);
911         for(int i=0;i<count;i++,addr+=4) {
912             byte[] b = inetAddrs[i].getAddress();
913             copyout(b,addr,4);
914         }
915         memWrite(sizeAddr,count*4);
916         return 0;
917     }
918     
919     private int sys_setsockopt(int fdn, int level, int name, int valaddr, int len) throws ReadFaultException, ErrnoException {
920         SocketFD fd = getSocketFD(fdn);
921         switch(level) {
922             case SOL_SOCKET:
923                 switch(name) {
924                     case SO_REUSEADDR:
925                     case SO_KEEPALIVE: {
926                         if(len != 4) return -EINVAL;
927                         int val = memRead(valaddr);
928                         if(val != 0) fd.options |= name;
929                         else fd.options &= ~name;
930                         fd.setOptions();
931                         return 0;
932                     }
933                     default:
934                         if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
935                         return -ENOPROTOOPT;
936                 }
937             default:
938                 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
939                 return -ENOPROTOOPT;
940         }                   
941     }
942     
943     private int sys_getsockopt(int fdn, int level, int name, int valaddr, int lenaddr) throws ErrnoException, FaultException {
944         SocketFD fd = getSocketFD(fdn);
945         switch(level) {
946             case SOL_SOCKET:
947                 switch(name) {
948                     case SO_REUSEADDR:
949                     case SO_KEEPALIVE: {
950                         int len = memRead(lenaddr);
951                         if(len < 4) return -EINVAL;
952                         int val = (fd.options & name) != 0 ? 1 : 0;
953                         memWrite(valaddr,val);
954                         memWrite(lenaddr,4);
955                         return 0;
956                     }
957                     default:
958                         if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
959                         return -ENOPROTOOPT;
960                 }
961             default:
962                 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
963                 return -ENOPROTOOPT;
964         } 
965     }
966     
967     private int sys_bind(int fdn, int addr, int namelen) throws FaultException, ErrnoException {
968         SocketFD fd = getSocketFD(fdn);
969         
970         if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
971         int word1 = memRead(addr);
972         if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
973         int port = word1 & 0xffff;
974         InetAddress inetAddr = null;
975         if(memRead(addr+4) != 0) {
976             byte[] ip = new byte[4];
977             copyin(addr+4,ip,4);
978         
979             try {
980                 inetAddr = Platform.inetAddressFromBytes(ip);
981             } catch(UnknownHostException e) {
982                 return -EADDRNOTAVAIL;
983             }
984         }
985         
986         switch(fd.type()) {
987             case SocketFD.TYPE_STREAM: {
988                 fd.bindAddr = inetAddr;
989                 fd.bindPort = port;
990                 return 0;
991             }
992             case SocketFD.TYPE_DGRAM: {
993                 if(fd.ds != null) fd.ds.close();
994                 try {
995                     fd.ds = inetAddr != null ? new DatagramSocket(port,inetAddr) : new DatagramSocket(port);
996                 } catch(IOException e) {
997                     return -EADDRINUSE;
998                 }
999                 return 0;
1000             }
1001             default:
1002                 throw new Error("should never happen");
1003         }
1004     }
1005     
1006     private int sys_listen(int fdn, int backlog) throws ErrnoException {
1007         SocketFD fd = getSocketFD(fdn);
1008         if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
1009         if(fd.ss != null || fd.s != null) return -EISCONN;
1010         if(fd.bindPort < 0) return -EOPNOTSUPP;
1011         
1012         try {
1013             fd.ss = new ServerSocket(fd.bindPort,backlog,fd.bindAddr);
1014             fd.flags |= SocketFD.LISTEN;
1015             return 0;
1016         } catch(IOException e) {
1017             return -EADDRINUSE;
1018         }
1019         
1020     }
1021     
1022     private int sys_accept(int fdn, int addr, int lenaddr) throws ErrnoException, FaultException {
1023         SocketFD fd = getSocketFD(fdn);
1024         if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
1025         if(!fd.listen()) return -EOPNOTSUPP;
1026
1027         int size = memRead(lenaddr);
1028         
1029         ServerSocket s = fd.ss;
1030         Socket client;
1031         try {
1032             client = s.accept();
1033         } catch(IOException e) {
1034             return -EIO;
1035         }
1036         
1037         if(size >= 8) {
1038             memWrite(addr,(6 << 24) | (AF_INET << 16) | client.getPort());
1039             byte[] b = client.getInetAddress().getAddress();
1040             copyout(b,addr+4,4);
1041             memWrite(lenaddr,8);
1042         }
1043         
1044         SocketFD clientFD = new SocketFD(SocketFD.TYPE_STREAM);
1045         clientFD.s = client;
1046         try {
1047             clientFD.is = client.getInputStream();
1048             clientFD.os = client.getOutputStream();
1049         } catch(IOException e) {
1050             return -EIO;
1051         }
1052         int n = addFD(clientFD);
1053         if(n == -1) { clientFD.close(); return -ENFILE; }
1054         return n;
1055     }
1056     
1057     private int sys_shutdown(int fdn, int how) throws ErrnoException {
1058         SocketFD fd = getSocketFD(fdn);
1059         if(fd.type() != SocketFD.TYPE_STREAM || fd.listen()) return -EOPNOTSUPP;
1060         if(fd.s == null) return -ENOTCONN;
1061         
1062         Socket s = fd.s;
1063         
1064         try {
1065             if(how == SHUT_RD || how == SHUT_RDWR) Platform.socketHalfClose(s,false);
1066             if(how == SHUT_WR || how == SHUT_RDWR) Platform.socketHalfClose(s,true);
1067         } catch(IOException e) {
1068             return -EIO;
1069         }
1070         
1071         return 0;
1072     }
1073     
1074     private int sys_sendto(int fdn, int addr, int count, int flags, int destAddr, int socklen) throws ErrnoException,ReadFaultException {
1075         SocketFD fd = getSocketFD(fdn);
1076         if(flags != 0) throw new ErrnoException(EINVAL);
1077         
1078         int word1 = memRead(destAddr);
1079         if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
1080         int port = word1 & 0xffff;
1081         InetAddress inetAddr;
1082                 byte[] ip = new byte[4];
1083                 copyin(destAddr+4,ip,4);
1084                 try {
1085                         inetAddr = Platform.inetAddressFromBytes(ip);
1086                 } catch(UnknownHostException e) {
1087                         return -EADDRNOTAVAIL;
1088                 }
1089         
1090         count = Math.min(count,MAX_CHUNK);
1091         byte[] buf = byteBuf(count);
1092         copyin(addr,buf,count);
1093         try {
1094                 return fd.sendto(buf,0,count,inetAddr,port);
1095         } catch(ErrnoException e) {
1096                 if(e.errno == EPIPE) exit(128+13,true);
1097                 throw e;
1098         }
1099     }
1100     
1101     private int sys_recvfrom(int fdn, int addr, int count, int flags, int sourceAddr, int socklenAddr) throws ErrnoException, FaultException {
1102         SocketFD fd = getSocketFD(fdn);
1103         if(flags != 0) throw new ErrnoException(EINVAL);
1104         
1105         InetAddress[] inetAddr = sourceAddr == 0 ? null : new InetAddress[1];
1106         int[] port = sourceAddr == 0 ? null : new int[1];
1107         
1108         count = Math.min(count,MAX_CHUNK);
1109         byte[] buf = byteBuf(count);
1110         int n = fd.recvfrom(buf,0,count,inetAddr,port);
1111         copyout(buf,addr,n);
1112         
1113         if(sourceAddr != 0) {
1114                 memWrite(sourceAddr,(AF_INET << 16) | port[0]);
1115                 byte[] ip = inetAddr[0].getAddress();
1116                 copyout(ip,sourceAddr+4,4);
1117         }
1118         
1119         return n;
1120     }
1121     
1122     private int sys_select(int n, int readFDs, int writeFDs, int exceptFDs, int timevalAddr) throws ReadFaultException, ErrnoException {
1123         return -ENOSYS;
1124     }
1125     
1126     private static String hostName() {
1127         try {
1128             return InetAddress.getLocalHost().getHostName();
1129         } catch(UnknownHostException e) {
1130             return "darkstar";
1131         }
1132     }
1133     
1134     private int sys_sysctl(int nameaddr, int namelen, int oldp, int oldlenaddr, int newp, int newlen) throws FaultException {
1135         if(newp != 0) return -EPERM;
1136         if(namelen == 0) return -ENOENT;
1137         if(oldp == 0) return 0;
1138         
1139         Object o = null;
1140         switch(memRead(nameaddr)) {
1141             case CTL_KERN:
1142                 if(namelen != 2) break;
1143                 switch(memRead(nameaddr+4)) {
1144                     case KERN_OSTYPE: o = "NestedVM"; break;
1145                     case KERN_HOSTNAME: o = hostName(); break;
1146                     case KERN_OSRELEASE: o = VERSION; break;
1147                     case KERN_VERSION: o = "NestedVM Kernel Version " + VERSION; break;
1148                 }
1149                 break;
1150             case CTL_HW:
1151                 if(namelen != 2) break;
1152                 switch(memRead(nameaddr+4)) {
1153                     case HW_MACHINE: o = "NestedVM Virtual Machine"; break;
1154                 }
1155                 break;
1156         }
1157         if(o == null) return -ENOENT;
1158         int len = memRead(oldlenaddr);
1159         if(o instanceof String) {
1160             byte[] b = getNullTerminatedBytes((String)o);
1161             if(len < b.length) return -ENOMEM;
1162             len = b.length;
1163             copyout(b,oldp,len);
1164             memWrite(oldlenaddr,len);
1165         } else if(o instanceof Integer) {
1166             if(len < 4) return -ENOMEM;
1167             memWrite(oldp,((Integer)o).intValue());
1168         } else {
1169             throw new Error("should never happen");
1170         }
1171         return 0;
1172     }
1173     
1174     public static final class GlobalState {
1175         Hashtable execCache = new Hashtable();
1176         
1177         final UnixRuntime[] tasks;
1178         int nextPID = 1;
1179         
1180         private MP[] mps = new MP[0];
1181         private FS root;
1182         
1183         public GlobalState() { this(255); }
1184         public GlobalState(int maxProcs) { this(maxProcs,true); }
1185         public GlobalState(int maxProcs, boolean defaultMounts) {
1186             tasks = new UnixRuntime[maxProcs+1];
1187             if(defaultMounts) {
1188                 addMount("/",new HostFS());
1189                 addMount("/dev",new DevFS());
1190                 addMount("/resource",new ResourceFS());
1191             }
1192         }
1193         
1194         static class MP implements Sort.Comparable {
1195             public MP(String path, FS fs) { this.path = path; this.fs = fs; }
1196             public String path;
1197             public FS fs;
1198             public int compareTo(Object o) {
1199                 if(!(o instanceof MP)) return 1;
1200                 return -path.compareTo(((MP)o).path);
1201             }
1202         }
1203         
1204         public synchronized FS getMount(String path) {
1205             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1206             if(path.equals("/")) return root;
1207             path  = path.substring(1);
1208             for(int i=0;i<mps.length;i++)
1209                 if(mps[i].path.equals(path)) return mps[i].fs;
1210             return null;
1211         }
1212         
1213         public synchronized void addMount(String path, FS fs) {
1214             if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
1215             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1216             
1217             if(fs.owner != null) fs.owner.removeMount(fs);
1218             fs.owner = this;
1219             
1220             if(path.equals("/")) { root = fs; fs.devno = 1; return; }
1221             path = path.substring(1);
1222             int oldLength = mps.length;
1223             MP[] newMPS = new MP[oldLength + 1];
1224             if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
1225             newMPS[oldLength] = new MP(path,fs);
1226             Sort.sort(newMPS);
1227             mps = newMPS;
1228             int highdevno = 0;
1229             for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
1230             fs.devno = highdevno + 2;
1231         }
1232         
1233         public synchronized void removeMount(FS fs) {
1234             for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
1235             throw new IllegalArgumentException("mount point doesn't exist");
1236         }
1237         
1238         public synchronized void removeMount(String path) {
1239             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1240             if(path.equals("/")) {
1241                 removeMount(-1);
1242             } else {
1243                 path = path.substring(1);
1244                 int p;
1245                 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
1246                 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
1247                 removeMount(p);
1248             }
1249         }
1250         
1251         private void removeMount(int index) {
1252             if(index == -1) { root.owner = null; root = null; return; }
1253             MP[] newMPS = new MP[mps.length - 1];
1254             System.arraycopy(mps,0,newMPS,0,index);
1255             System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
1256             mps = newMPS;
1257         }
1258         
1259         private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
1260             int pl = normalizedPath.length();
1261             if(pl != 0) {
1262                 MP[] list;
1263                 synchronized(this) { list = mps; }
1264                 for(int i=0;i<list.length;i++) {
1265                     MP mp = list[i];
1266                     int mpl = mp.path.length();
1267                     if(normalizedPath.startsWith(mp.path) && (pl == mpl || normalizedPath.charAt(mpl) == '/'))
1268                         return mp.fs.dispatch(op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
1269                 }
1270             }
1271             return root.dispatch(op,r,normalizedPath,arg1,arg2);
1272         }
1273         
1274         public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(FS.OPEN,r,path,flags,mode); }
1275         public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.STAT,r,path,0,0); }
1276         public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.LSTAT,r,path,0,0); }
1277         public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(FS.MKDIR,r,path,mode,0); }
1278         public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(FS.UNLINK,r,path,0,0); }
1279         
1280         private static class CacheEnt {
1281             public final long time;
1282             public final long size;
1283             public final Object o;
1284             public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
1285         }
1286     }
1287     
1288     public abstract static class FS {
1289         static final int OPEN = 1;
1290         static final int STAT = 2;
1291         static final int LSTAT = 3;
1292         static final int MKDIR = 4;
1293         static final int UNLINK = 5;
1294         
1295         GlobalState owner;
1296         int devno;
1297         
1298         Object dispatch(int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
1299             switch(op) {
1300                 case OPEN: return open(r,path,arg1,arg2);
1301                 case STAT: return stat(r,path);
1302                 case LSTAT: return lstat(r,path);
1303                 case MKDIR: mkdir(r,path,arg1); return null;
1304                 case UNLINK: unlink(r,path); return null;
1305                 default: throw new Error("should never happen");
1306             }
1307         }
1308         
1309         public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1310
1311         // If this returns null it'll be truned into an ENOENT
1312         public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
1313         // If this returns null it'll be turned into an ENOENT
1314         public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
1315         public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
1316         public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
1317     }
1318         
1319     // chroot support should go in here if it is ever implemented chroot support in here
1320     private String normalizePath(String path) {
1321         boolean absolute = path.startsWith("/");
1322         int cwdl = cwd.length();
1323         
1324         // NOTE: This isn't just a fast path, it handles cases the code below doesn't
1325         if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
1326             return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
1327         
1328         char[] in = new char[path.length()+1];
1329         char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
1330         path.getChars(0,path.length(),in,0);
1331         int inp=0, outp=0;
1332         
1333         if(absolute) {
1334             do { inp++; } while(in[inp] == '/');
1335         } else if(cwdl != 0) {
1336             cwd.getChars(0,cwdl,out,0);
1337             outp = cwdl;
1338         }
1339
1340         while(in[inp] != 0) {
1341             if(inp != 0) {
1342                 while(in[inp] != 0 && in[inp] != '/') { out[outp++] = in[inp++]; }
1343                 if(in[inp] == '\0') break;
1344                 while(in[inp] == '/') inp++;
1345             }
1346             
1347             // Just read a /
1348             if(in[inp] == '\0') break;
1349             if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
1350             // Just read a /.
1351             if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
1352             if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
1353                 // Just read a /..{$,/}
1354                 inp += 2;
1355                 if(outp > 0) outp--;
1356                 while(outp > 0 && out[outp] != '/') outp--;
1357                 //System.err.println("After ..: " + new String(out,0,outp));
1358                 continue;
1359             }
1360             // Just read a /.[^.] or /..[^/$]
1361             inp++;
1362             out[outp++] = '/';
1363             out[outp++] = '.';
1364         }
1365         if(outp > 0 && out[outp-1] == '/') outp--;
1366         //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
1367         int outStart = out[0] == '/' ? 1 : 0;
1368         return new String(out,outStart,outp - outStart);
1369     }
1370     
1371     FStat hostFStat(final File f, Object data) {
1372         boolean e = false;
1373         try {
1374             FileInputStream fis = new FileInputStream(f);
1375             switch(fis.read()) {
1376                 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
1377                 case '#': e = fis.read() == '!';
1378             }
1379             fis.close();
1380         } catch(IOException e2) { } 
1381         HostFS fs = (HostFS) data;
1382         final int inode = fs.inodes.get(f.getAbsolutePath());
1383         final int devno = fs.devno;
1384         return new HostFStat(f,e) {
1385             public int inode() { return inode; }
1386             public int dev() { return devno; }
1387         };
1388     }
1389
1390     FD hostFSDirFD(File f, Object _fs) {
1391         HostFS fs = (HostFS) _fs;
1392         return fs.new HostDirFD(f);
1393     }
1394     
1395     public static class HostFS extends FS {
1396         InodeCache inodes = new InodeCache(4000);
1397         protected File root;
1398         public File getRoot() { return root; }
1399         
1400         static File hostRootDir() {
1401             if(Platform.getProperty("nestedvm.root") != null) {
1402                 File f = new File(Platform.getProperty("nestedvm.root"));
1403                 if(f.isDirectory()) return f;
1404                 // fall through to case below
1405             }
1406             String cwd = Platform.getProperty("user.dir");
1407             File f = new File(cwd != null ? cwd : ".");
1408             if(!f.exists()) throw new Error("Couldn't get File for cwd");
1409             f = new File(f.getAbsolutePath());
1410             while(f.getParent() != null) f = new File(f.getParent());
1411             // This works around a bug in some versions of ClassPath
1412             if(f.getPath().length() == 0) f = new File("/");
1413             return f;
1414         }
1415         
1416         private File hostFile(String path) {
1417             char sep = File.separatorChar;
1418             if(sep != '/') {
1419                 char buf[] = path.toCharArray();
1420                 for(int i=0;i<buf.length;i++) {
1421                     char c = buf[i];
1422                     if(c == '/') buf[i] = sep;
1423                     else if(c == sep) buf[i] = '/';
1424                 }
1425                 path = new String(buf);
1426             }
1427             return new File(root,path);
1428         }
1429         
1430         public HostFS() { this(hostRootDir()); }
1431         public HostFS(String root) { this(new File(root)); }
1432         public HostFS(File root) { this.root = root; }
1433         
1434         
1435         public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1436             final File f = hostFile(path);
1437             return r.hostFSOpen(f,flags,mode,this);
1438         }
1439         
1440         public void unlink(UnixRuntime r, String path) throws ErrnoException {
1441             File f = hostFile(path);
1442             if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1443             if(!f.exists()) throw new ErrnoException(ENOENT);
1444             if(!f.delete()) throw new ErrnoException(EPERM);
1445         }
1446         
1447         public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1448             File f = hostFile(path);
1449             if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1450             if(!f.exists()) return null;
1451             return r.hostFStat(f,this);
1452         }
1453         
1454         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1455             File f = hostFile(path);
1456             if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1457             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1458             if(f.exists()) throw new ErrnoException(ENOTDIR);
1459             File parent = getParentFile(f);
1460             if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1461             if(!f.mkdir()) throw new ErrnoException(EIO);            
1462         }
1463         
1464         private static File getParentFile(File f) {
1465             String p = f.getParent();
1466             return p == null ? null : new File(p);
1467         }
1468         
1469         public class HostDirFD extends DirFD {
1470             private final File f;
1471             private final File[] children;
1472             public HostDirFD(File f) {
1473                 this.f = f;
1474                 String[] l = f.list();
1475                 children = new File[l.length];
1476                 for(int i=0;i<l.length;i++) children[i] = new File(f,l[i]);
1477             }
1478             public int size() { return children.length; }
1479             public String name(int n) { return children[n].getName(); }
1480             public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1481             public int parentInode() {
1482                 File parent = getParentFile(f);
1483                 // HACK: myInode() isn't really correct  if we're not the root
1484                 return parent == null ? myInode() : inodes.get(parent.getAbsolutePath());
1485             }
1486             public int myInode() { return inodes.get(f.getAbsolutePath()); }
1487             public int myDev() { return devno; } 
1488         }
1489     }
1490     
1491     private static void putInt(byte[] buf, int off, int n) {
1492         buf[off+0] = (byte)((n>>>24)&0xff);
1493         buf[off+1] = (byte)((n>>>16)&0xff);
1494         buf[off+2] = (byte)((n>>> 8)&0xff);
1495         buf[off+3] = (byte)((n>>> 0)&0xff);
1496     }
1497     
1498     public static abstract class DirFD extends FD {
1499         private int pos = -2;
1500         
1501         protected abstract int size();
1502         protected abstract String name(int n);
1503         protected abstract int inode(int n);
1504         protected abstract int myDev();
1505         protected abstract int parentInode();
1506         protected abstract int myInode();
1507         public int flags() { return O_RDONLY; }
1508
1509         public int getdents(byte[] buf, int off, int len) {
1510             int ooff = off;
1511             int ino;
1512             int reclen;
1513             OUTER: for(;len > 0 && pos < size();pos++){
1514                 switch(pos) {
1515                     case -2:
1516                     case -1:
1517                         ino = pos == -1 ? parentInode() : myInode();
1518                         if(ino == -1) continue;
1519                         reclen = 9 + (pos == -1 ? 2 : 1);
1520                         if(reclen > len) break OUTER;
1521                         buf[off+8] = '.';
1522                         if(pos == -1) buf[off+9] = '.';
1523                         break;
1524                     default: {
1525                         String f = name(pos);
1526                         byte[] fb = getBytes(f);
1527                         reclen = fb.length + 9;
1528                         if(reclen > len) break OUTER;
1529                         ino = inode(pos);
1530                         System.arraycopy(fb,0,buf,off+8,fb.length);
1531                     }
1532                 }
1533                 buf[off+reclen-1] = 0; // null terminate
1534                 reclen = (reclen + 3) & ~3; // add padding
1535                 putInt(buf,off,reclen);
1536                 putInt(buf,off+4,ino);
1537                 off += reclen;
1538                 len -= reclen;    
1539             }
1540             return off-ooff;
1541         }
1542         
1543         protected FStat _fstat() {
1544             return new FStat() { 
1545                 public int type() { return S_IFDIR; }
1546                 public int inode() { return myInode(); }
1547                 public int dev() { return myDev(); }
1548             };
1549         }
1550     }
1551         
1552     public static class DevFS extends FS {
1553         private static final int ROOT_INODE = 1;
1554         private static final int NULL_INODE = 2;
1555         private static final int ZERO_INODE = 3;
1556         private static final int FD_INODE = 4;
1557         private static final int FD_INODES = 32;
1558         
1559         private abstract class DevFStat extends FStat {
1560             public int dev() { return devno; }
1561             public int mode() { return 0666; }
1562             public int type() { return S_IFCHR; }
1563             public int nlink() { return 1; }
1564             public abstract int inode();
1565         }
1566         
1567         private abstract class DevDirFD extends DirFD {
1568             public int myDev() { return devno; }
1569         }
1570         
1571         private FD devZeroFD = new FD() {
1572             public int read(byte[] a, int off, int length) { 
1573                 /*Arrays.fill(a,off,off+length,(byte)0);*/
1574                 for(int i=off;i<off+length;i++) a[i] = 0;
1575                 return length;
1576             }
1577             public int write(byte[] a, int off, int length) { return length; }
1578             public int seek(int n, int whence) { return 0; }
1579             public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1580             public int flags() { return O_RDWR; }
1581         };
1582         private FD devNullFD = new FD() {
1583             public int read(byte[] a, int off, int length) { return 0; }
1584             public int write(byte[] a, int off, int length) { return length; }
1585             public int seek(int n, int whence) { return 0; }
1586             public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1587             public int flags() { return O_RDWR; }
1588         }; 
1589         
1590         public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1591             if(path.equals("null")) return devNullFD;
1592             if(path.equals("zero")) return devZeroFD;
1593             if(path.startsWith("fd/")) {
1594                 int n;
1595                 try {
1596                     n = Integer.parseInt(path.substring(4));
1597                 } catch(NumberFormatException e) {
1598                     return null;
1599                 }
1600                 if(n < 0 || n >= OPEN_MAX) return null;
1601                 if(r.fds[n] == null) return null;
1602                 return r.fds[n].dup();
1603             }
1604             if(path.equals("fd")) {
1605                 int count=0;
1606                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1607                 final int[] files = new int[count];
1608                 count = 0;
1609                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1610                 return new DevDirFD() {
1611                     public int myInode() { return FD_INODE; }
1612                     public int parentInode() { return ROOT_INODE; }
1613                     public int inode(int n) { return FD_INODES + n; }
1614                     public String name(int n) { return Integer.toString(files[n]); }
1615                     public int size() { return files.length; }
1616                 };
1617             }
1618             if(path.equals("")) {
1619                 return new DevDirFD() {
1620                     public int myInode() { return ROOT_INODE; }
1621                     // HACK: We don't have any clean way to get the parent inode
1622                     public int parentInode() { return ROOT_INODE; }
1623                     public int inode(int n) {
1624                         switch(n) {
1625                             case 0: return NULL_INODE;
1626                             case 1: return ZERO_INODE;
1627                             case 2: return FD_INODE;
1628                             default: return -1;
1629                         }
1630                     }
1631                     
1632                     public String name(int n) {
1633                         switch(n) {
1634                             case 0: return "null";
1635                             case 1: return "zero";
1636                             case 2: return "fd";
1637                             default: return null;
1638                         }
1639                     }
1640                     public int size() { return 3; }
1641                 };
1642             }
1643             return null;
1644         }
1645         
1646         public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1647             if(path.equals("null")) return devNullFD.fstat();
1648             if(path.equals("zero")) return devZeroFD.fstat();            
1649             if(path.startsWith("fd/")) {
1650                 int n;
1651                 try {
1652                     n = Integer.parseInt(path.substring(3));
1653                 } catch(NumberFormatException e) {
1654                     return null;
1655                 }
1656                 if(n < 0 || n >= OPEN_MAX) return null;
1657                 if(r.fds[n] == null) return null;
1658                 return r.fds[n].fstat();
1659             }
1660             if(path.equals("fd")) return new FStat() { public int inode() { return FD_INODE; }   public int dev() { return devno; } public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1661             if(path.equals(""))   return new FStat() { public int inode() { return ROOT_INODE; } public int dev() { return devno; } public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1662             return null;
1663         }
1664         
1665         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1666         public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }
1667     }
1668     
1669     
1670     public static class ResourceFS extends FS {
1671         final InodeCache inodes = new InodeCache(500);
1672         
1673         public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1674         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1675         public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }
1676         
1677         FStat connFStat(final URLConnection conn) {
1678             return new FStat() {
1679                 public int type() { return S_IFREG; }
1680                 public int nlink() { return 1; }
1681                 public int mode() { return 0444; }
1682                 public int size() { return conn.getContentLength(); }
1683                 public int mtime() { return (int)(conn.getDate() / 1000); }
1684                 public int inode() { return inodes.get(conn.getURL().toString()); }
1685                 public int dev() { return devno; }
1686             };
1687         }
1688         
1689         public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1690             URL url = r.getClass().getResource("/" + path);
1691             if(url == null) return null;
1692             try {
1693                 return connFStat(url.openConnection());
1694             } catch(IOException e) {
1695                 throw new ErrnoException(EIO);
1696             }
1697         }
1698         
1699         public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1700             if((flags & ~3) != 0) {
1701                 if(STDERR_DIAG)
1702                     System.err.println("WARNING: Unsupported flags passed to ResourceFS.open(\"" + path + "\"): " + toHex(flags & ~3));
1703                 throw new ErrnoException(ENOTSUP);
1704             }
1705             if((flags&3) != RD_ONLY) throw new ErrnoException(EROFS);
1706             URL url = r.getClass().getResource("/" + path);
1707             if(url == null) return null;
1708             try {
1709                 final URLConnection conn = url.openConnection();
1710                 Seekable.InputStream si = new Seekable.InputStream(conn.getInputStream());
1711                 return new SeekableFD(si,flags) { protected FStat _fstat() { return connFStat(conn); } };
1712             } catch(FileNotFoundException e) {
1713                 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) throw new ErrnoException(EACCES);
1714                 return null;
1715             } catch(IOException e) { throw new ErrnoException(EIO); }
1716         }
1717     }
1718 }