1c33a089ff5a790e34e52fbaf61b8a98c67417b7
[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         //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
518         if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
519         cwd = path;
520         //System.err.println("Now: [" + cwd + "]");
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     public int sys_opensocket(int cstring, int port) throws FaultException, ErrnoException {
632         String hostname = cstring(cstring);
633         try {
634             FD fd = new SocketFD(new Socket(hostname,port));
635             int n = addFD(fd);
636             if(n == -1) fd.close();
637             return n;
638         } catch(IOException e) {
639             return -EIO;
640         }
641     }
642     
643     private static class ListenSocketFD extends FD {
644         ServerSocket s;
645         public ListenSocketFD(ServerSocket s) { this.s = s; }
646         public int flags() { return 0; }
647         // FEATURE: What should these be?
648         public FStat _fstat() { return new FStat(); }
649         public void _close() { try { s.close(); } catch(IOException e) { } }
650     }
651     
652     public int sys_listensocket(int port) {
653         try {
654             ListenSocketFD fd = new ListenSocketFD(new ServerSocket(port));
655             int n = addFD(fd);
656             if(n == -1) fd.close();
657             return n;            
658         } catch(IOException e) {
659             return -EIO;
660         }
661     }
662     
663     public int sys_accept(int fdn) {
664         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
665         if(fds[fdn] == null) return -EBADFD;
666         if(!(fds[fdn] instanceof ListenSocketFD)) return -EBADFD;
667         try {
668             ServerSocket s = ((ListenSocketFD)fds[fdn]).s;
669             SocketFD fd = new SocketFD(s.accept());
670             int n = addFD(fd);
671             if(n == -1) fd.close();
672             return n;
673         } catch(IOException e) {
674             return -EIO;
675         }
676     }*/
677     
678     //  FEATURE: Run through the fork/wait stuff one more time
679     public static class GlobalState {    
680         protected static final int OPEN = 1;
681         protected static final int STAT = 2;
682         protected static final int LSTAT = 3;
683         protected static final int MKDIR = 4;
684         protected static final int UNLINK = 5;
685         
686         final UnixRuntime[] tasks;
687         int nextPID = 1;
688         
689         private MP[] mps = new MP[0];
690         private FS root;
691         
692         public GlobalState() { this(255); }
693         public GlobalState(int maxProcs) { this(maxProcs,true); }
694         public GlobalState(int maxProcs, boolean defaultMounts) {
695             tasks = new UnixRuntime[maxProcs+1];
696             if(defaultMounts) {
697                 addMount("/",new HostFS());
698                 addMount("/dev",new DevFS());
699             }
700         }
701         
702         private static class MP implements Comparable {
703             public MP(String path, FS fs) { this.path = path; this.fs = fs; }
704             public String path;
705             public FS fs;
706             public int compareTo(Object o) {
707                 if(!(o instanceof MP)) return 1;
708                 return -path.compareTo(((MP)o).path);
709             }
710         }
711         
712         public synchronized FS getMount(String path) {
713             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
714             if(path.equals("/")) return root;
715             path  = path.substring(1);
716             for(int i=0;i<mps.length;i++)
717                 if(mps[i].path.equals(path)) return mps[i].fs;
718             return null;
719         }
720         
721         public synchronized void addMount(String path, FS fs) {
722             if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
723             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
724             
725             if(fs.owner != null) fs.owner.removeMount(fs);
726             fs.owner = this;
727             
728             if(path.equals("/")) { root = fs; fs.devno = 1; return; }
729             path = path.substring(1);
730             int oldLength = mps.length;
731             MP[] newMPS = new MP[oldLength + 1];
732             if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
733             newMPS[oldLength] = new MP(path,fs);
734             Arrays.sort(newMPS);
735             mps = newMPS;
736             int highdevno = 0;
737             for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
738             fs.devno = highdevno + 2;
739         }
740         
741         public synchronized void removeMount(FS fs) {
742             for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
743             throw new IllegalArgumentException("mount point doesn't exist");
744         }
745         
746         public synchronized void removeMount(String path) {
747             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
748             if(path.equals("/")) {
749                 removeMount(-1);
750             } else {
751                 path = path.substring(1);
752                 int p;
753                 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
754                 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
755                 removeMount(p);
756             }
757         }
758         
759         private void removeMount(int index) {
760             if(index == -1) { root.owner = null; root = null; return; }
761             MP[] newMPS = new MP[mps.length - 1];
762             System.arraycopy(mps,0,newMPS,0,index);
763             System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
764             mps = newMPS;
765         }
766         
767         private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
768             int pl = normalizedPath.length();
769             if(pl != 0) {
770                 MP[] list;
771                 synchronized(this) { list = mps; }
772                 for(int i=0;i<list.length;i++) {
773                     MP mp = list[i];
774                     int mpl = mp.path.length();
775                     if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
776                         return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
777                 }
778             }
779             return dispatch(root,op,r,normalizedPath,arg1,arg2);
780         }
781         
782         private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
783             switch(op) {
784                 case OPEN: return fs.open(r,path,arg1,arg2);
785                 case STAT: return fs.stat(r,path);
786                 case LSTAT: return fs.lstat(r,path);
787                 case MKDIR: fs.mkdir(r,path,arg1); return null;
788                 case UNLINK: fs.unlink(r,path); return null;
789                 default: throw new Error("should never happen");
790             }
791         }
792         
793         public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
794         public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
795         public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
796         public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
797         public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
798         
799         private Hashtable execCache = new Hashtable();
800         private static class CacheEnt {
801             public final long time;
802             public final long size;
803             public final Object o;
804             public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
805         }
806
807         public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
808             // FIXME: Hideous hack to make a standalone busybox possible
809             if(path.equals("bin/busybox") && Boolean.valueOf(getSystemProperty("nestedvm.busyboxhack")).booleanValue())
810                 return r.getClass();
811             FStat fstat = stat(r,path);
812             if(fstat == null) return null;
813             long mtime = fstat.mtime();
814             long size = fstat.size();
815             CacheEnt ent = (CacheEnt) execCache.get(path);
816             if(ent != null) {
817                 //System.err.println("Found cached entry for " + path);
818                 if(ent.time == mtime && ent.size == size) return ent.o;
819                 //System.err.println("Cache was out of date");
820                 execCache.remove(path);
821             }
822             FD fd = open(r,path,RD_ONLY,0);
823             if(fd == null) return null;
824             Seekable s = fd.seekable();
825             
826             String[] command  = null;
827
828             if(s == null) throw new ErrnoException(EACCES);
829             byte[] buf = new byte[4096];
830             
831             try {
832                 int n = s.read(buf,0,buf.length);
833                 if(n == -1) throw new ErrnoException(ENOEXEC);
834                 
835                 switch(buf[0]) {
836                     case '\177': // possible ELF
837                         if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
838                         if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
839                         break;
840                     case '#':
841                         if(n == 1) {
842                             int n2 = s.read(buf,1,buf.length-1);
843                             if(n2 == -1) throw new ErrnoException(ENOEXEC);
844                             n += n2;
845                         }
846                         if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
847                         int p = 2;
848                         n -= 2;
849                         OUTER: for(;;) {
850                             for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
851                             p += n;
852                             if(p == buf.length) break OUTER;
853                             n = s.read(buf,p,buf.length-p);
854                         }
855                         command = new String[2];
856                         int arg;
857                         for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
858                         if(arg < p) {
859                             int cmdEnd = arg;
860                             while(arg < p && buf[arg] == ' ') arg++;
861                             command[0] = new String(buf,2,cmdEnd);
862                             command[1] = arg < p ? new String(buf,arg,p-arg) : null;
863                         } else {
864                             command[0] = new String(buf,2,p-2);
865                         }
866                         //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
867                         break;
868                     default:
869                         throw new ErrnoException(ENOEXEC);
870                 }
871             } catch(IOException e) {
872                 fd.close();
873                 throw new ErrnoException(EIO);
874             }
875                         
876             if(command == null) {
877                 // its an elf binary
878                 try {
879                     s.seek(0);
880                     Class c = RuntimeCompiler.compile(s);
881                     //System.err.println("Compile succeeded: " + c);
882                     ent = new CacheEnt(mtime,size,c);
883                 } catch(Compiler.Exn e) {
884                     if(STDERR_DIAG) e.printStackTrace();
885                     throw new ErrnoException(ENOEXEC);
886                 } catch(IOException e) {
887                     if(STDERR_DIAG) e.printStackTrace();
888                     throw new ErrnoException(EIO);
889                 }
890             } else {
891                 ent = new CacheEnt(mtime,size,command);
892             }
893             
894             fd.close();
895             
896             execCache.put(path,ent);
897             return ent.o;
898         }
899     }
900     
901     public abstract static class FS {
902         GlobalState owner;
903         int devno;
904         
905         public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
906
907         // If this returns null it'll be truned into an ENOENT
908         public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
909         // If this returns null it'll be turned into an ENOENT
910         public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
911         public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
912         public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
913     }
914         
915     // FEATURE: chroot support in here
916     private String normalizePath(String path) {
917         boolean absolute = path.startsWith("/");
918         int cwdl = cwd.length();
919         // NOTE: This isn't just a fast path, it handles cases the code below doesn't
920         if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
921             return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
922         
923         char[] in = new char[path.length()+1];
924         char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
925         int inp=0, outp=0;
926         
927         if(absolute) {
928             do { inp++; } while(in[inp] == '/');
929         } else if(cwdl != 0) {
930             cwd.getChars(0,cwdl,out,0);
931             outp = cwdl;
932         }
933             
934         path.getChars(0,path.length(),in,0);
935         while(in[inp] != 0) {
936             if(inp != 0 || cwdl==0) {
937                 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
938                 while(in[inp] == '/') inp++;
939             }
940             if(in[inp] == '\0') continue;
941             if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
942             if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
943             if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
944                 inp += 2;
945                 if(outp > 0) outp--;
946                 while(outp > 0 && out[outp] != '/') outp--;
947                 //System.err.println("After ..: " + new String(out,0,outp));
948                 continue;
949             }
950             inp++;
951             out[outp++] = '/';
952             out[outp++] = '.';
953         }
954         if(outp > 0 && out[outp-1] == '/') outp--;
955         //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
956         return new String(out,0,outp);
957     }
958     
959     FStat hostFStat(final File f, Object data) {
960         boolean e = false;
961         try {
962             FileInputStream fis = new FileInputStream(f);
963             switch(fis.read()) {
964                 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
965                 case '#': e = fis.read() == '!';
966             }
967             fis.close();
968         } catch(IOException e2) { } 
969         HostFS fs = (HostFS) data;
970         final int inode = fs.inodes.get(f.getAbsolutePath());
971         final int devno = fs.devno;
972         return new HostFStat(f,e) {
973             public int inode() { return inode; }
974             public int dev() { return devno; }
975         };
976     }
977
978     FD hostFSDirFD(File f, Object _fs) {
979         HostFS fs = (HostFS) _fs;
980         return fs.new HostDirFD(f);
981     }
982     
983     public static class HostFS extends FS {
984         InodeCache inodes = new InodeCache(4000);
985         protected File root;
986         public File getRoot() { return root; }
987         
988         private static File hostRootDir() {
989             if(getSystemProperty("nestedvm.root") != null) {
990                 File f = new File(getSystemProperty("nestedvm.root"));
991                 if(f.isDirectory()) return f;
992                 // fall through to case below
993             }
994             String cwd = getSystemProperty("user.dir");
995             File f = new File(cwd != null ? cwd : ".");
996             if(!f.exists()) throw new Error("Couldn't get File for cwd");
997             f = new File(f.getAbsolutePath());
998             while(f.getParent() != null) f = new File(f.getParent());
999             return f;
1000         }
1001         
1002         private File hostFile(String path) {
1003             char sep = File.separatorChar;
1004             if(sep != '/') {
1005                 char buf[] = path.toCharArray();
1006                 for(int i=0;i<buf.length;i++) {
1007                     char c = buf[i];
1008                     if(c == '/') buf[i] = sep;
1009                     else if(c == sep) buf[i] = '/';
1010                 }
1011                 path = new String(buf);
1012             }
1013             return new File(root,path);
1014         }
1015         
1016         public HostFS() { this(hostRootDir()); }
1017         public HostFS(String root) { this(new File(root)); }
1018         public HostFS(File root) { this.root = root; }
1019         
1020         
1021         public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1022             // FIXME: horrendous, ugly hack needed by TeX... sorry Brian...
1023             path = path.trim();
1024             final File f = hostFile(path);
1025             return r.hostFSOpen(f,flags,mode,this);
1026         }
1027         
1028         public void unlink(UnixRuntime r, String path) throws ErrnoException {
1029             File f = hostFile(path);
1030             if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1031             if(!f.exists()) throw new ErrnoException(ENOENT);
1032             if(!f.delete()) throw new ErrnoException(EPERM);
1033         }
1034         
1035         public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1036             File f = hostFile(path);
1037             if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1038             if(!f.exists()) return null;
1039             return r.hostFStat(f,this);
1040         }
1041         
1042         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1043             File f = hostFile(path);
1044             if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1045             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1046             if(f.exists()) throw new ErrnoException(ENOTDIR);
1047             File parent = f.getParentFile();
1048             if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1049             if(!f.mkdir()) throw new ErrnoException(EIO);            
1050         }
1051         
1052         public class HostDirFD extends DirFD {
1053             private final File f;
1054             private final File[] children;
1055             public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
1056             public int size() { return children.length; }
1057             public String name(int n) { return children[n].getName(); }
1058             public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1059             public int parentInode() {
1060                 File parent = f.getParentFile();
1061                 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
1062             }
1063             public int myInode() { return inodes.get(f.getAbsolutePath()); }
1064             public int myDev() { return devno; } 
1065         }
1066     }
1067     
1068     private static void putInt(byte[] buf, int off, int n) {
1069         buf[off+0] = (byte)((n>>>24)&0xff);
1070         buf[off+1] = (byte)((n>>>16)&0xff);
1071         buf[off+2] = (byte)((n>>> 8)&0xff);
1072         buf[off+3] = (byte)((n>>> 0)&0xff);
1073     }
1074     
1075     public static abstract class DirFD extends FD {
1076         private int pos = -2;
1077         
1078         protected abstract int size();
1079         protected abstract String name(int n);
1080         protected abstract int inode(int n);
1081         protected abstract int myDev();
1082         protected int parentInode() { return -1; }
1083         protected int myInode() { return -1; }
1084         
1085         public int getdents(byte[] buf, int off, int len) {
1086             int ooff = off;
1087             int ino;
1088             int reclen;
1089             OUTER: for(;len > 0 && pos < size();pos++){
1090                 switch(pos) {
1091                     case -2:
1092                     case -1:
1093                         ino = pos == -1 ? parentInode() : myInode();
1094                         if(ino == -1) continue;
1095                         reclen = 9 + (pos == -1 ? 2 : 1);
1096                         if(reclen > len) break OUTER;
1097                         buf[off+8] = '.';
1098                         if(pos == -1) buf[off+9] = '.';
1099                         break;
1100                     default: {
1101                         String f = name(pos);
1102                         byte[] fb = getBytes(f);
1103                         reclen = fb.length + 9;
1104                         if(reclen > len) break OUTER;
1105                         ino = inode(pos);
1106                         System.arraycopy(fb,0,buf,off+8,fb.length);
1107                     }
1108                 }
1109                 buf[off+reclen-1] = 0; // null terminate
1110                 reclen = (reclen + 3) & ~3; // add padding
1111                 putInt(buf,off,reclen);
1112                 putInt(buf,off+4,ino);
1113                 off += reclen;
1114                 len -= reclen;    
1115             }
1116             return off-ooff;
1117         }
1118         
1119         protected FStat _fstat() {
1120             return new FStat() { 
1121                 public int type() { return S_IFDIR; }
1122                 public int inode() { return myInode(); }
1123                 public int dev() { return myDev(); }
1124             };
1125         }
1126     }
1127         
1128     public static class DevFS extends FS {
1129         private static final int ROOT_INODE = 1;
1130         private static final int NULL_INODE = 2;
1131         private static final int ZERO_INODE = 3;
1132         private static final int FD_INODE = 4;
1133         private static final int FD_INODES = 32;
1134         
1135         private class DevFStat extends FStat {
1136             public int dev() { return devno; }
1137             public int mode() { return 0666; }
1138             public int type() { return S_IFCHR; }
1139             public int nlink() { return 1; }
1140         }
1141         
1142         private abstract class DevDirFD extends DirFD {
1143             public int myDev() { return devno; }
1144         }
1145         
1146         private FD devZeroFD = new FD() {
1147             public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
1148             public int write(byte[] a, int off, int length) { return length; }
1149             public int seek(int n, int whence) { return 0; }
1150             public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1151         };
1152         private FD devNullFD = new FD() {
1153             public int read(byte[] a, int off, int length) { return 0; }
1154             public int write(byte[] a, int off, int length) { return length; }
1155             public int seek(int n, int whence) { return 0; }
1156             public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1157         }; 
1158         
1159         public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1160             if(path.equals("null")) return devNullFD;
1161             if(path.equals("zero")) return devZeroFD;
1162             if(path.startsWith("fd/")) {
1163                 int n;
1164                 try {
1165                     n = Integer.parseInt(path.substring(4));
1166                 } catch(NumberFormatException e) {
1167                     return null;
1168                 }
1169                 if(n < 0 || n >= OPEN_MAX) return null;
1170                 if(r.fds[n] == null) return null;
1171                 return r.fds[n].dup();
1172             }
1173             if(path.equals("fd")) {
1174                 int count=0;
1175                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1176                 final int[] files = new int[count];
1177                 count = 0;
1178                 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1179                 return new DevDirFD() {
1180                     public int myInode() { return FD_INODE; }
1181                     public int parentInode() { return ROOT_INODE; }
1182                     public int inode(int n) { return FD_INODES + n; }
1183                     public String name(int n) { return Integer.toString(files[n]); }
1184                     public int size() { return files.length; }
1185                 };
1186             }
1187             if(path.equals("")) {
1188                 return new DevDirFD() {
1189                     public int myInode() { return ROOT_INODE; }
1190                     // FEATURE: Get the real parent inode somehow
1191                     public int parentInode() { return -1; }
1192                     public int inode(int n) {
1193                         switch(n) {
1194                             case 0: return NULL_INODE;
1195                             case 1: return ZERO_INODE;
1196                             case 2: return FD_INODE;
1197                             default: return -1;
1198                         }
1199                     }
1200                     
1201                     public String name(int n) {
1202                         switch(n) {
1203                             case 0: return "null";
1204                             case 1: return "zero";
1205                             case 2: return "fd";
1206                             default: return null;
1207                         }
1208                     }
1209                     public int size() { return 3; }
1210                 };
1211             }
1212             return null;
1213         }
1214         
1215         public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1216             if(path.equals("null")) return devNullFD.fstat();
1217             if(path.equals("zero")) return devZeroFD.fstat();            
1218             if(path.startsWith("fd/")) {
1219                 int n;
1220                 try {
1221                     n = Integer.parseInt(path.substring(4));
1222                 } catch(NumberFormatException e) {
1223                     return null;
1224                 }
1225                 if(n < 0 || n >= OPEN_MAX) return null;
1226                 if(r.fds[n] == null) return null;
1227                 return r.fds[n].fstat();
1228             }
1229             // FEATURE: inode stuff
1230             if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1231             if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1232             return null;
1233         }
1234         
1235         public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1236         public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }
1237     }    
1238 }