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