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