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