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