1 package org.ibex.nestedvm;
3 import org.ibex.nestedvm.util.*;
10 public abstract class UnixRuntime extends Runtime implements Cloneable {
11 /** The pid of this "process" */
13 private UnixRuntime parent;
14 public final int getPid() { return pid; }
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");
23 /** proceses' current working directory - absolute path WITHOUT leading slash
24 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
27 /** The runtime that should be run next when in state == EXECED */
28 private UnixRuntime execedRuntime;
30 private Object children; // used only for synchronizatin
31 private Vector activeChildren;
32 private Vector exitedChildren;
34 protected UnixRuntime(int pageSize, int totalPages) {
35 super(pageSize,totalPages);
37 // FEATURE: Do the proper mangling for non-unix hosts
38 String userdir = getSystemProperty("user.dir");
40 userdir != null && userdir.startsWith("/") && File.separatorChar == '/' && getSystemProperty("nestedvm.root") == null
41 ? userdir.substring(1) : "";
44 private static String posixTZ() {
45 StringBuffer sb = new StringBuffer();
46 TimeZone zone = TimeZone.getDefault();
47 int off = zone.getRawOffset() / 1000;
48 sb.append(Platform.timeZoneGetDisplayName(zone,false,false));
49 if(off > 0) sb.append("-");
51 sb.append(off/3600); off = off%3600;
52 if(off > 0) sb.append(":").append(off/60); off=off%60;
53 if(off > 0) sb.append(":").append(off);
54 if(zone.useDaylightTime())
55 sb.append(Platform.timeZoneGetDisplayName(zone,true,false));
59 private static boolean envHas(String key,String[] environ) {
60 for(int i=0;i<environ.length;i++)
61 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
65 String[] createEnv(String[] extra) {
66 String[] defaults = new String[6];
68 if(extra == null) extra = new String[0];
69 if(!envHas("USER",extra) && getSystemProperty("user.name") != null)
70 defaults[n++] = "USER=" + getSystemProperty("user.name");
71 if(!envHas("HOME",extra) && getSystemProperty("user.home") != null)
72 defaults[n++] = "HOME=" + getSystemProperty("user.home");
73 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
74 if(!envHas("TERM",extra)) defaults[n++] = "TERM=vt100";
75 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
76 if(!envHas("PATH",extra)) defaults[n++] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin";
77 String[] env = new String[extra.length+n];
78 for(int i=0;i<n;i++) env[i] = defaults[i];
79 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
83 private static class ProcessTableFullExn extends RuntimeException { }
86 UnixRuntime[] tasks = gs.tasks;
89 UnixRuntime prev = tasks[pid];
90 if(prev == null || prev == this || prev.pid != pid || prev.parent != parent)
91 throw new Error("should never happen");
92 synchronized(parent.children) {
93 int i = parent.activeChildren.indexOf(prev);
94 if(i == -1) throw new Error("should never happen");
95 parent.activeChildren.setElementAt(this,i);
99 int nextPID = gs.nextPID;
100 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
101 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
102 if(newpid == -1) throw new ProcessTableFullExn();
104 gs.nextPID = newpid + 1;
110 int _syscall(int syscall, int a, int b, int c, int d, int e, int f) throws ErrnoException, FaultException {
112 case SYS_kill: return sys_kill(a,b);
113 case SYS_fork: return sys_fork();
114 case SYS_pipe: return sys_pipe(a);
115 case SYS_dup2: return sys_dup2(a,b);
116 case SYS_dup: return sys_dup(a);
117 case SYS_waitpid: return sys_waitpid(a,b,c);
118 case SYS_stat: return sys_stat(a,b);
119 case SYS_lstat: return sys_lstat(a,b);
120 case SYS_mkdir: return sys_mkdir(a,b);
121 case SYS_getcwd: return sys_getcwd(a,b);
122 case SYS_chdir: return sys_chdir(a);
123 case SYS_exec: return sys_exec(a,b,c);
124 case SYS_getdents: return sys_getdents(a,b,c,d);
125 case SYS_unlink: return sys_unlink(a);
126 case SYS_getppid: return sys_getppid();
127 case SYS_socket: return sys_socket(a,b,c);
128 case SYS_connect: return sys_connect(a,b,c);
129 case SYS_resolve_hostname: return sys_resolve_hostname(a,b,c);
130 case SYS_setsockopt: return sys_setsockopt(a,b,c,d,e);
131 case SYS_getsockopt: return sys_getsockopt(a,b,c,d,e);
132 case SYS_bind: return sys_bind(a,b,c);
133 case SYS_listen: return sys_listen(a,b);
134 case SYS_accept: return sys_accept(a,b,c);
135 case SYS_shutdown: return sys_shutdown(a,b);
136 case SYS_sysctl: return sys_sysctl(a,b,c,d,e,f);
138 default: return super._syscall(syscall,a,b,c,d,e,f);
142 FD _open(String path, int flags, int mode) throws ErrnoException {
143 return gs.open(this,normalizePath(path),flags,mode);
146 private int sys_getppid() {
147 return parent == null ? 1 : parent.pid;
150 /** The kill syscall.
151 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
152 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
153 Anything else terminates the process. */
154 private int sys_kill(int pid, int signal) {
155 // This will only be called by raise() in newlib to invoke the default handler
156 // We don't have to worry about actually delivering the signal
157 if(pid != pid) return -ESRCH;
158 if(signal < 0 || signal >= 32) return -EINVAL;
173 // FEATURE: This is ugly, make a clean interface to sys_exit
174 return syscall(SYS_exit,128+signal,0,0,0,0,0);
179 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
180 final int WNOHANG = 1;
181 if((options & ~(WNOHANG)) != 0) return -EINVAL;
182 if(pid == 0 || pid < -1) {
183 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
186 boolean blocking = (options&WNOHANG)==0;
188 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
189 if(children == null) return blocking ? -ECHILD : 0;
191 UnixRuntime done = null;
193 synchronized(children) {
196 if(exitedChildren.size() > 0) {
197 done = (UnixRuntime)exitedChildren.elementAt(exitedChildren.size() - 1);
198 exitedChildren.removeElementAt(exitedChildren.size() - 1);
201 UnixRuntime t = gs.tasks[pid];
202 if(t.parent != this) return -ECHILD;
203 if(t.state == EXITED) {
204 if(!exitedChildren.removeElement(t)) throw new Error("should never happen");
208 // process group stuff, EINVAL returned above
209 throw new Error("should never happen");
212 if(!blocking) return 0;
213 try { children.wait(); } catch(InterruptedException e) {}
214 //System.err.println("waitpid woke up: " + exitedChildren.size());
216 gs.tasks[done.pid] = null;
221 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
227 if(children != null) synchronized(children) {
228 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
229 UnixRuntime child = (UnixRuntime) e.nextElement();
230 gs.tasks[child.pid] = null;
232 exitedChildren.removeAllElements();
233 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
234 UnixRuntime child = (UnixRuntime) e.nextElement();
237 activeChildren.removeAllElements();
240 UnixRuntime _parent = parent;
241 if(_parent == null) {
242 gs.tasks[pid] = null;
244 synchronized(_parent.children) {
246 gs.tasks[pid] = null;
248 if(!parent.activeChildren.removeElement(this)) throw new Error("should never happen _exited: pid: " + pid);
249 parent.exitedChildren.addElement(this);
250 parent.children.notify();
256 protected Object clone() throws CloneNotSupportedException {
257 UnixRuntime r = (UnixRuntime) super.clone();
261 r.activeChildren = r.exitedChildren = null;
265 private int sys_fork() {
266 CPUState state = new CPUState();
268 int sp = state.r[SP];
272 r = (UnixRuntime) clone();
273 } catch(Exception e) {
282 } catch(ProcessTableFullExn e) {
286 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
287 if(children == null) {
288 children = new Object();
289 activeChildren = new Vector();
290 exitedChildren = new Vector();
292 activeChildren.addElement(r);
294 state.r[V0] = 0; // return 0 to child
295 state.pc += 4; // skip over syscall instruction
296 r.setCPUState(state);
299 new ForkedProcess(r);
304 public static final class ForkedProcess extends Thread {
305 private final UnixRuntime initial;
306 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
307 public void run() { UnixRuntime.executeAndExec(initial); }
310 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
311 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
313 public static int executeAndExec(UnixRuntime r) {
316 if(r.execute()) break;
317 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
319 if(r.state != EXECED) return r.exitStatus();
324 private String[] readStringArray(int addr) throws ReadFaultException {
326 for(int p=addr;memRead(p) != 0;p+=4) count++;
327 String[] a = new String[count];
328 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
332 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
333 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
336 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
337 if(argv.length == 0) argv = new String[]{""};
339 // NOTE: For this little hack to work nestedvm.root MUST be "."
341 System.err.println("Execing normalized path: " + normalizedPath);
342 if(true) return exec(new Interpreter(normalizedPath),argv,envp);
343 } catch(IOException e) { throw new Error(e); }*/
345 Object o = gs.exec(this,normalizedPath);
346 if(o == null) return -ENOENT;
348 if(o instanceof Class) {
351 return exec((UnixRuntime) c.newInstance(),argv,envp);
352 } catch(Exception e) {
357 String[] command = (String[]) o;
358 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
359 int p = command[0].lastIndexOf('/');
360 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
362 if(command[1] != null) newArgv[p++] = command[1];
363 newArgv[p++] = "/" + normalizedPath;
364 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
365 return exec(command[0],newArgv,envp);
369 private int exec(UnixRuntime r, String[] argv, String[] envp) {
371 //System.err.println("Execing " + r);
372 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
374 r.closeOnExec = closeOnExec;
375 // make sure this doesn't get messed with these since we didn't copy them
392 // FEATURE: Make sure fstat info is correct
393 // FEATURE: This could be faster if we did direct copies from each process' memory
394 // FEATURE: Check this logic one more time
395 public static class Pipe {
396 private final byte[] pipebuf = new byte[PIPE_BUF*4];
398 private int writePos;
400 public final FD reader = new Reader();
401 public final FD writer = new Writer();
403 public class Reader extends FD {
404 protected FStat _fstat() { return new FStat(); }
405 public int read(byte[] buf, int off, int len) throws ErrnoException {
406 if(len == 0) return 0;
407 synchronized(Pipe.this) {
408 while(writePos != -1 && readPos == writePos) {
409 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
411 if(writePos == -1) return 0; // eof
412 len = Math.min(len,writePos-readPos);
413 System.arraycopy(pipebuf,readPos,buf,off,len);
415 if(readPos == writePos) Pipe.this.notify();
419 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
422 public class Writer extends FD {
423 protected FStat _fstat() { return new FStat(); }
424 public int write(byte[] buf, int off, int len) throws ErrnoException {
425 if(len == 0) return 0;
426 synchronized(Pipe.this) {
427 if(readPos == -1) throw new ErrnoException(EPIPE);
428 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
429 // not enough space to atomicly write the data
430 while(readPos != -1 && readPos != writePos) {
431 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
433 if(readPos == -1) throw new ErrnoException(EPIPE);
434 readPos = writePos = 0;
436 len = Math.min(len,pipebuf.length - writePos);
437 System.arraycopy(buf,off,pipebuf,writePos,len);
438 if(readPos == writePos) Pipe.this.notify();
443 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
447 private int sys_pipe(int addr) {
448 Pipe pipe = new Pipe();
450 int fd1 = addFD(pipe.reader);
451 if(fd1 < 0) return -ENFILE;
452 int fd2 = addFD(pipe.writer);
453 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
457 memWrite(addr+4,fd2);
458 } catch(FaultException e) {
466 private int sys_dup2(int oldd, int newd) {
467 if(oldd == newd) return 0;
468 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
469 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
470 if(fds[oldd] == null) return -EBADFD;
471 if(fds[newd] != null) fds[newd].close();
472 fds[newd] = fds[oldd].dup();
476 private int sys_dup(int oldd) {
477 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
478 if(fds[oldd] == null) return -EBADFD;
479 FD fd = fds[oldd].dup();
480 int newd = addFD(fd);
481 if(newd < 0) { fd.close(); return -ENFILE; }
485 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
486 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
487 if(s == null) return -ENOENT;
491 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
492 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
493 if(s == null) return -ENOENT;
497 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
498 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
502 private int sys_unlink(int cstring) throws FaultException, ErrnoException {
503 gs.unlink(this,normalizePath(cstring(cstring)));
507 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
508 byte[] b = getBytes(cwd);
509 if(size == 0) return -EINVAL;
510 if(size < b.length+2) return -ERANGE;
512 copyout(b,addr+1,b.length);
513 memset(addr+b.length+1,0,1);
517 private int sys_chdir(int addr) throws ErrnoException, FaultException {
518 String path = normalizePath(cstring(addr));
519 FStat st = gs.stat(this,path);
520 if(st == null) return -ENOENT;
521 if(st.type() != FStat.S_IFDIR) return -ENOTDIR;
526 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
527 count = Math.min(count,MAX_CHUNK);
528 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
529 if(fds[fdn] == null) return -EBADFD;
530 byte[] buf = byteBuf(count);
531 int n = fds[fdn].getdents(buf,0,count);
536 // FIXME: UDP is totally broken
538 static class SocketFD extends FD {
539 public static final int TYPE_STREAM = 0;
540 public static final int TYPE_DGRAM = 1;
541 public static final int LISTEN = 2;
542 public int type() { return flags & 1; }
543 public boolean listen() { return (flags & 2) != 0; }
548 InetAddress bindAddr;
554 public SocketFD(int type) { flags = type; }
556 public void setOptions() {
558 if(o != null && type() == TYPE_STREAM && !listen()) {
559 Platform.socketSetKeepAlive((Socket)o,(options & SO_KEEPALIVE) != 0);
561 } catch(SocketException e) {
562 if(STDERR_DIAG) e.printStackTrace();
566 public void _close() {
569 if(type() == TYPE_STREAM) {
570 if(listen()) ((ServerSocket)o).close();
571 else ((Socket)o).close();
573 ((DatagramSocket)o).close();
575 } catch(IOException e) {
581 public int read(byte[] a, int off, int length) throws ErrnoException {
582 if(type() == TYPE_STREAM) {
583 if(is == null) throw new ErrnoException(EPIPE);
585 int n = is.read(a,off,length);
586 return n < 0 ? 0 : n;
587 } catch(IOException e) {
588 throw new ErrnoException(EIO);
591 if(off != 0) throw new IllegalArgumentException("off must be 0");
592 DatagramSocket ds = (DatagramSocket) o;
594 dp.setLength(length);
597 } catch(IOException e) {
598 throw new ErrnoException(EIO);
600 return dp.getLength();
604 public int write(byte[] a, int off, int length) throws ErrnoException {
605 if(type() == TYPE_STREAM) {
606 if(os == null) throw new ErrnoException(EPIPE);
608 os.write(a,off,length);
610 } catch(IOException e) {
611 throw new ErrnoException(EIO);
614 if(off != 0) throw new IllegalArgumentException("off must be 0");
615 DatagramSocket ds = (DatagramSocket) o;
617 dp.setLength(length);
620 } catch(IOException e) {
621 throw new ErrnoException(EIO);
623 return dp.getLength();
627 // FEATURE: Check that these are correct
629 if(is != null && os != null) return O_RDWR;
630 if(is != null) return O_RDONLY;
631 if(os != null) return O_WRONLY;
635 // FEATURE: Populate this properly
636 public FStat _fstat() { return new FStat(); }
639 private int sys_socket(int domain, int type, int proto) {
640 if(domain != AF_INET || (type != SOCK_STREAM && type != SOCK_DGRAM)) return -EPROTONOSUPPORT;
641 return addFD(new SocketFD(type == SOCK_STREAM ? SocketFD.TYPE_STREAM : SocketFD.TYPE_DGRAM));
644 private SocketFD getSocketFD(int fdn) throws ErrnoException {
645 if(fdn < 0 || fdn >= OPEN_MAX) throw new ErrnoException(EBADFD);
646 if(fds[fdn] == null) throw new ErrnoException(EBADFD);
647 if(!(fds[fdn] instanceof SocketFD)) throw new ErrnoException(ENOTSOCK);
649 return (SocketFD) fds[fdn];
652 private int sys_connect(int fdn, int addr, int namelen) throws ErrnoException, FaultException {
653 SocketFD fd = getSocketFD(fdn);
655 if(fd.type() == SocketFD.TYPE_STREAM && fd.o != null) return -EISCONN;
656 int word1 = memRead(addr);
657 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
658 int port = word1 & 0xffff;
659 byte[] ip = new byte[4];
662 InetAddress inetAddr;
664 inetAddr = Platform.inetAddressFromBytes(ip);
665 } catch(UnknownHostException e) {
666 return -EADDRNOTAVAIL;
671 case SocketFD.TYPE_STREAM: {
672 Socket s = new Socket(inetAddr,port);
675 fd.is = s.getInputStream();
676 fd.os = s.getOutputStream();
679 case SocketFD.TYPE_DGRAM: {
680 if(fd.dp == null) fd.dp = new DatagramPacket(null,0);
681 fd.dp.setAddress(inetAddr);
686 throw new Error("should never happen");
688 } catch(IOException e) {
689 return -ECONNREFUSED;
695 private int sys_resolve_hostname(int chostname, int addr, int sizeAddr) throws FaultException {
696 String hostname = cstring(chostname);
697 int size = memRead(sizeAddr);
698 InetAddress[] inetAddrs;
700 inetAddrs = InetAddress.getAllByName(hostname);
701 } catch(UnknownHostException e) {
702 return HOST_NOT_FOUND;
704 int count = min(size/4,inetAddrs.length);
705 for(int i=0;i<count;i++,addr+=4) {
706 byte[] b = inetAddrs[i].getAddress();
709 memWrite(sizeAddr,count*4);
713 private int sys_setsockopt(int fdn, int level, int name, int valaddr, int len) throws ReadFaultException, ErrnoException {
714 SocketFD fd = getSocketFD(fdn);
720 if(len != 4) return -EINVAL;
721 int val = memRead(valaddr);
722 if(val != 0) fd.options |= name;
723 else fd.options &= ~name;
728 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
732 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
737 private int sys_getsockopt(int fdn, int level, int name, int valaddr, int lenaddr) throws ErrnoException, FaultException {
738 SocketFD fd = getSocketFD(fdn);
744 int len = memRead(lenaddr);
745 if(len < 4) return -EINVAL;
746 int val = (fd.options & name) != 0 ? 1 : 0;
747 memWrite(valaddr,val);
752 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
756 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
761 private int sys_bind(int fdn, int addr, int namelen) throws FaultException, ErrnoException {
762 SocketFD fd = getSocketFD(fdn);
764 if(fd.type() == SocketFD.TYPE_STREAM && fd.o != null) return -EISCONN;
765 int word1 = memRead(addr);
766 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
767 int port = word1 & 0xffff;
768 InetAddress inetAddr = null;
769 if(memRead(addr+4) != 0) {
770 byte[] ip = new byte[4];
774 inetAddr = Platform.inetAddressFromBytes(ip);
775 } catch(UnknownHostException e) {
776 return -EADDRNOTAVAIL;
781 case SocketFD.TYPE_STREAM: {
782 fd.bindAddr = inetAddr;
786 case SocketFD.TYPE_DGRAM: {
787 DatagramSocket s = (DatagramSocket) fd.o;
788 if(s != null) s.close();
790 fd.o = inetAddr != null ? new DatagramSocket(port,inetAddr) : new DatagramSocket(port);
791 } catch(IOException e) {
797 throw new Error("should never happen");
801 private int sys_listen(int fdn, int backlog) throws ErrnoException {
802 SocketFD fd = getSocketFD(fdn);
803 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
804 if(fd.o != null) return -EISCONN;
805 if(fd.bindPort < 0) return -EOPNOTSUPP;
808 fd.o = new ServerSocket(fd.bindPort,backlog,fd.bindAddr);
809 fd.flags |= SocketFD.LISTEN;
811 } catch(IOException e) {
817 private int sys_accept(int fdn, int addr, int lenaddr) throws ErrnoException, FaultException {
818 SocketFD fd = getSocketFD(fdn);
819 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
820 if(!fd.listen()) return -EOPNOTSUPP;
822 int size = memRead(lenaddr);
824 ServerSocket s = (ServerSocket) fd.o;
828 } catch(IOException e) {
833 memWrite(addr,(6 << 24) | (AF_INET << 16) | client.getPort());
834 byte[] b = client.getInetAddress().getAddress();
839 SocketFD clientFD = new SocketFD(SocketFD.TYPE_STREAM);
842 clientFD.is = client.getInputStream();
843 clientFD.os = client.getOutputStream();
844 } catch(IOException e) {
847 int n = addFD(clientFD);
848 if(n == -1) { clientFD.close(); return -ENFILE; }
852 private int sys_shutdown(int fdn, int how) throws ErrnoException {
853 SocketFD fd = getSocketFD(fdn);
854 if(fd.type() != SocketFD.TYPE_STREAM || fd.listen()) return -EOPNOTSUPP;
855 if(fd.o == null) return -ENOTCONN;
857 Socket s = (Socket) fd.o;
860 if(how == SHUT_RD || how == SHUT_RDWR) Platform.socketHalfClose(s,false);
861 if(how == SHUT_WR || how == SHUT_RDWR) Platform.socketHalfClose(s,true);
862 } catch(IOException e) {
869 private static String hostName() {
871 return InetAddress.getLocalHost().getHostName();
872 } catch(UnknownHostException e) {
877 private int sys_sysctl(int nameaddr, int namelen, int oldp, int oldlenaddr, int newp, int newlen) throws FaultException {
878 if(newp != 0) return -EPERM;
879 if(namelen == 0) return -ENOENT;
880 if(oldp == 0) return 0;
883 switch(memRead(nameaddr)) {
885 if(namelen != 2) break;
886 switch(memRead(nameaddr+4)) {
887 case KERN_OSTYPE: o = "NestedVM"; break;
888 case KERN_HOSTNAME: o = hostName(); break;
889 case KERN_OSRELEASE: o = VERSION; break;
890 case KERN_VERSION: o = "NestedVM Kernel Version " + VERSION; break;
894 if(namelen != 2) break;
895 switch(memRead(nameaddr+4)) {
896 case HW_MACHINE: o = "NestedVM Virtual Machine"; break;
900 if(o == null) return -ENOENT;
901 int len = memRead(oldlenaddr);
902 if(o instanceof String) {
903 byte[] b = getNullTerminatedBytes((String)o);
904 if(len < b.length) return -ENOMEM;
907 memWrite(oldlenaddr,len);
908 } else if(o instanceof Integer) {
909 if(len < 4) return -ENOMEM;
910 memWrite(oldp,((Integer)o).intValue());
912 throw new Error("should never happen");
918 /*public int sys_opensocket(int cstring, int port) throws FaultException, ErrnoException {
919 String hostname = cstring(cstring);
921 FD fd = new SocketFD(new Socket(hostname,port));
923 if(n == -1) fd.close();
925 } catch(IOException e) {
930 private static class ListenSocketFD extends FD {
932 public ListenSocketFD(ServerSocket s) { this.s = s; }
933 public int flags() { return 0; }
934 // FEATURE: What should these be?
935 public FStat _fstat() { return new FStat(); }
936 public void _close() { try { s.close(); } catch(IOException e) { } }
939 public int sys_listensocket(int port) {
941 ListenSocketFD fd = new ListenSocketFD(new ServerSocket(port));
943 if(n == -1) fd.close();
945 } catch(IOException e) {
950 public int sys_accept(int fdn) {
951 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
952 if(fds[fdn] == null) return -EBADFD;
953 if(!(fds[fdn] instanceof ListenSocketFD)) return -EBADFD;
955 ServerSocket s = ((ListenSocketFD)fds[fdn]).s;
956 SocketFD fd = new SocketFD(s.accept());
958 if(n == -1) fd.close();
960 } catch(IOException e) {
965 // FEATURE: Run through the fork/wait stuff one more time
966 public static class GlobalState {
967 protected static final int OPEN = 1;
968 protected static final int STAT = 2;
969 protected static final int LSTAT = 3;
970 protected static final int MKDIR = 4;
971 protected static final int UNLINK = 5;
973 final UnixRuntime[] tasks;
976 private MP[] mps = new MP[0];
979 public GlobalState() { this(255); }
980 public GlobalState(int maxProcs) { this(maxProcs,true); }
981 public GlobalState(int maxProcs, boolean defaultMounts) {
982 tasks = new UnixRuntime[maxProcs+1];
984 addMount("/",new HostFS());
985 addMount("/dev",new DevFS());
989 private static class MP implements Sort.Sortable {
990 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
993 public int compareTo(Object o) {
994 if(!(o instanceof MP)) return 1;
995 return -path.compareTo(((MP)o).path);
999 public synchronized FS getMount(String path) {
1000 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1001 if(path.equals("/")) return root;
1002 path = path.substring(1);
1003 for(int i=0;i<mps.length;i++)
1004 if(mps[i].path.equals(path)) return mps[i].fs;
1008 public synchronized void addMount(String path, FS fs) {
1009 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
1010 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1012 if(fs.owner != null) fs.owner.removeMount(fs);
1015 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
1016 path = path.substring(1);
1017 int oldLength = mps.length;
1018 MP[] newMPS = new MP[oldLength + 1];
1019 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
1020 newMPS[oldLength] = new MP(path,fs);
1024 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
1025 fs.devno = highdevno + 2;
1028 public synchronized void removeMount(FS fs) {
1029 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
1030 throw new IllegalArgumentException("mount point doesn't exist");
1033 public synchronized void removeMount(String path) {
1034 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1035 if(path.equals("/")) {
1038 path = path.substring(1);
1040 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
1041 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
1046 private void removeMount(int index) {
1047 if(index == -1) { root.owner = null; root = null; return; }
1048 MP[] newMPS = new MP[mps.length - 1];
1049 System.arraycopy(mps,0,newMPS,0,index);
1050 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
1054 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
1055 int pl = normalizedPath.length();
1058 synchronized(this) { list = mps; }
1059 for(int i=0;i<list.length;i++) {
1061 int mpl = mp.path.length();
1062 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
1063 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
1066 return dispatch(root,op,r,normalizedPath,arg1,arg2);
1069 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
1071 case OPEN: return fs.open(r,path,arg1,arg2);
1072 case STAT: return fs.stat(r,path);
1073 case LSTAT: return fs.lstat(r,path);
1074 case MKDIR: fs.mkdir(r,path,arg1); return null;
1075 case UNLINK: fs.unlink(r,path); return null;
1076 default: throw new Error("should never happen");
1080 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
1081 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
1082 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
1083 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
1084 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
1086 private Hashtable execCache = new Hashtable();
1087 private static class CacheEnt {
1088 public final long time;
1089 public final long size;
1090 public final Object o;
1091 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
1094 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
1095 // FIXME: Hideous hack to make a standalone busybox possible
1096 if(path.equals("bin/busybox") && Boolean.valueOf(getSystemProperty("nestedvm.busyboxhack")).booleanValue())
1097 return r.getClass();
1098 FStat fstat = stat(r,path);
1099 if(fstat == null) return null;
1100 long mtime = fstat.mtime();
1101 long size = fstat.size();
1102 CacheEnt ent = (CacheEnt) execCache.get(path);
1104 //System.err.println("Found cached entry for " + path);
1105 if(ent.time == mtime && ent.size == size) return ent.o;
1106 //System.err.println("Cache was out of date");
1107 execCache.remove(path);
1109 FD fd = open(r,path,RD_ONLY,0);
1110 if(fd == null) return null;
1111 Seekable s = fd.seekable();
1113 String[] command = null;
1115 if(s == null) throw new ErrnoException(EACCES);
1116 byte[] buf = new byte[4096];
1119 int n = s.read(buf,0,buf.length);
1120 if(n == -1) throw new ErrnoException(ENOEXEC);
1123 case '\177': // possible ELF
1124 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
1125 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
1129 int n2 = s.read(buf,1,buf.length-1);
1130 if(n2 == -1) throw new ErrnoException(ENOEXEC);
1133 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
1137 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
1139 if(p == buf.length) break OUTER;
1140 n = s.read(buf,p,buf.length-p);
1142 command = new String[2];
1144 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
1147 while(arg < p && buf[arg] == ' ') arg++;
1148 command[0] = new String(buf,2,cmdEnd);
1149 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
1151 command[0] = new String(buf,2,p-2);
1153 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
1156 throw new ErrnoException(ENOEXEC);
1158 } catch(IOException e) {
1160 throw new ErrnoException(EIO);
1163 if(command == null) {
1164 // its an elf binary
1167 Class c = RuntimeCompiler.compile(s);
1168 //System.err.println("Compile succeeded: " + c);
1169 ent = new CacheEnt(mtime,size,c);
1170 } catch(Compiler.Exn e) {
1171 if(STDERR_DIAG) e.printStackTrace();
1172 throw new ErrnoException(ENOEXEC);
1173 } catch(IOException e) {
1174 if(STDERR_DIAG) e.printStackTrace();
1175 throw new ErrnoException(EIO);
1178 ent = new CacheEnt(mtime,size,command);
1183 execCache.put(path,ent);
1188 public abstract static class FS {
1192 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1194 // If this returns null it'll be truned into an ENOENT
1195 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
1196 // If this returns null it'll be turned into an ENOENT
1197 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
1198 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
1199 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
1202 // FEATURE: chroot support in here
1203 private String normalizePath(String path) {
1204 boolean absolute = path.startsWith("/");
1205 int cwdl = cwd.length();
1206 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
1207 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
1208 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
1210 char[] in = new char[path.length()+1];
1211 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
1215 do { inp++; } while(in[inp] == '/');
1216 } else if(cwdl != 0) {
1217 cwd.getChars(0,cwdl,out,0);
1221 path.getChars(0,path.length(),in,0);
1222 while(in[inp] != 0) {
1223 if(inp != 0 || cwdl==0) {
1224 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
1225 while(in[inp] == '/') inp++;
1227 if(in[inp] == '\0') continue;
1228 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
1229 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
1230 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
1232 if(outp > 0) outp--;
1233 while(outp > 0 && out[outp] != '/') outp--;
1234 //System.err.println("After ..: " + new String(out,0,outp));
1241 if(outp > 0 && out[outp-1] == '/') outp--;
1242 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
1243 return new String(out,0,outp);
1246 FStat hostFStat(final File f, Object data) {
1249 FileInputStream fis = new FileInputStream(f);
1250 switch(fis.read()) {
1251 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
1252 case '#': e = fis.read() == '!';
1255 } catch(IOException e2) { }
1256 HostFS fs = (HostFS) data;
1257 final int inode = fs.inodes.get(f.getAbsolutePath());
1258 final int devno = fs.devno;
1259 return new HostFStat(f,e) {
1260 public int inode() { return inode; }
1261 public int dev() { return devno; }
1265 FD hostFSDirFD(File f, Object _fs) {
1266 HostFS fs = (HostFS) _fs;
1267 return fs.new HostDirFD(f);
1270 public static class HostFS extends FS {
1271 InodeCache inodes = new InodeCache(4000);
1272 protected File root;
1273 public File getRoot() { return root; }
1275 private static File hostRootDir() {
1276 if(getSystemProperty("nestedvm.root") != null) {
1277 File f = new File(getSystemProperty("nestedvm.root"));
1278 if(f.isDirectory()) return f;
1279 // fall through to case below
1281 String cwd = getSystemProperty("user.dir");
1282 File f = new File(cwd != null ? cwd : ".");
1283 if(!f.exists()) throw new Error("Couldn't get File for cwd");
1284 f = new File(f.getAbsolutePath());
1285 while(f.getParent() != null) f = new File(f.getParent());
1289 private File hostFile(String path) {
1290 char sep = File.separatorChar;
1292 char buf[] = path.toCharArray();
1293 for(int i=0;i<buf.length;i++) {
1295 if(c == '/') buf[i] = sep;
1296 else if(c == sep) buf[i] = '/';
1298 path = new String(buf);
1300 return new File(root,path);
1303 public HostFS() { this(hostRootDir()); }
1304 public HostFS(String root) { this(new File(root)); }
1305 public HostFS(File root) { this.root = root; }
1308 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1309 final File f = hostFile(path);
1310 return r.hostFSOpen(f,flags,mode,this);
1313 public void unlink(UnixRuntime r, String path) throws ErrnoException {
1314 File f = hostFile(path);
1315 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1316 if(!f.exists()) throw new ErrnoException(ENOENT);
1317 if(!f.delete()) throw new ErrnoException(EPERM);
1320 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1321 File f = hostFile(path);
1322 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1323 if(!f.exists()) return null;
1324 return r.hostFStat(f,this);
1327 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1328 File f = hostFile(path);
1329 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1330 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1331 if(f.exists()) throw new ErrnoException(ENOTDIR);
1332 File parent = getParentFile(f);
1333 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1334 if(!f.mkdir()) throw new ErrnoException(EIO);
1337 private static File getParentFile(File f) {
1338 String p = f.getParent();
1339 return p == null ? null : new File(f,p);
1342 public class HostDirFD extends DirFD {
1343 private final File f;
1344 private final File[] children;
1345 public HostDirFD(File f) {
1347 String[] l = f.list();
1348 children = new File[l.length];
1349 for(int i=0;i<l.length;i++) children[i] = new File(f,l[i]);
1351 public int size() { return children.length; }
1352 public String name(int n) { return children[n].getName(); }
1353 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1354 public int parentInode() {
1355 File parent = getParentFile(f);
1356 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
1358 public int myInode() { return inodes.get(f.getAbsolutePath()); }
1359 public int myDev() { return devno; }
1363 private static void putInt(byte[] buf, int off, int n) {
1364 buf[off+0] = (byte)((n>>>24)&0xff);
1365 buf[off+1] = (byte)((n>>>16)&0xff);
1366 buf[off+2] = (byte)((n>>> 8)&0xff);
1367 buf[off+3] = (byte)((n>>> 0)&0xff);
1370 public static abstract class DirFD extends FD {
1371 private int pos = -2;
1373 protected abstract int size();
1374 protected abstract String name(int n);
1375 protected abstract int inode(int n);
1376 protected abstract int myDev();
1377 protected int parentInode() { return -1; }
1378 protected int myInode() { return -1; }
1380 public int getdents(byte[] buf, int off, int len) {
1384 OUTER: for(;len > 0 && pos < size();pos++){
1388 ino = pos == -1 ? parentInode() : myInode();
1389 if(ino == -1) continue;
1390 reclen = 9 + (pos == -1 ? 2 : 1);
1391 if(reclen > len) break OUTER;
1393 if(pos == -1) buf[off+9] = '.';
1396 String f = name(pos);
1397 byte[] fb = getBytes(f);
1398 reclen = fb.length + 9;
1399 if(reclen > len) break OUTER;
1401 System.arraycopy(fb,0,buf,off+8,fb.length);
1404 buf[off+reclen-1] = 0; // null terminate
1405 reclen = (reclen + 3) & ~3; // add padding
1406 putInt(buf,off,reclen);
1407 putInt(buf,off+4,ino);
1414 protected FStat _fstat() {
1415 return new FStat() {
1416 public int type() { return S_IFDIR; }
1417 public int inode() { return myInode(); }
1418 public int dev() { return myDev(); }
1423 public static class DevFS extends FS {
1424 private static final int ROOT_INODE = 1;
1425 private static final int NULL_INODE = 2;
1426 private static final int ZERO_INODE = 3;
1427 private static final int FD_INODE = 4;
1428 private static final int FD_INODES = 32;
1430 private class DevFStat extends FStat {
1431 public int dev() { return devno; }
1432 public int mode() { return 0666; }
1433 public int type() { return S_IFCHR; }
1434 public int nlink() { return 1; }
1437 private abstract class DevDirFD extends DirFD {
1438 public int myDev() { return devno; }
1441 private FD devZeroFD = new FD() {
1442 public int read(byte[] a, int off, int length) {
1443 /*Arrays.fill(a,off,off+length,(byte)0);*/
1444 for(int i=off;i<off+length;i++) a[i] = 0;
1447 public int write(byte[] a, int off, int length) { return length; }
1448 public int seek(int n, int whence) { return 0; }
1449 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1451 private FD devNullFD = new FD() {
1452 public int read(byte[] a, int off, int length) { return 0; }
1453 public int write(byte[] a, int off, int length) { return length; }
1454 public int seek(int n, int whence) { return 0; }
1455 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1458 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1459 if(path.equals("null")) return devNullFD;
1460 if(path.equals("zero")) return devZeroFD;
1461 if(path.startsWith("fd/")) {
1464 n = Integer.parseInt(path.substring(4));
1465 } catch(NumberFormatException e) {
1468 if(n < 0 || n >= OPEN_MAX) return null;
1469 if(r.fds[n] == null) return null;
1470 return r.fds[n].dup();
1472 if(path.equals("fd")) {
1474 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1475 final int[] files = new int[count];
1477 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1478 return new DevDirFD() {
1479 public int myInode() { return FD_INODE; }
1480 public int parentInode() { return ROOT_INODE; }
1481 public int inode(int n) { return FD_INODES + n; }
1482 public String name(int n) { return Integer.toString(files[n]); }
1483 public int size() { return files.length; }
1486 if(path.equals("")) {
1487 return new DevDirFD() {
1488 public int myInode() { return ROOT_INODE; }
1489 // FEATURE: Get the real parent inode somehow
1490 public int parentInode() { return -1; }
1491 public int inode(int n) {
1493 case 0: return NULL_INODE;
1494 case 1: return ZERO_INODE;
1495 case 2: return FD_INODE;
1500 public String name(int n) {
1502 case 0: return "null";
1503 case 1: return "zero";
1504 case 2: return "fd";
1505 default: return null;
1508 public int size() { return 3; }
1514 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1515 if(path.equals("null")) return devNullFD.fstat();
1516 if(path.equals("zero")) return devZeroFD.fstat();
1517 if(path.startsWith("fd/")) {
1520 n = Integer.parseInt(path.substring(4));
1521 } catch(NumberFormatException e) {
1524 if(n < 0 || n >= OPEN_MAX) return null;
1525 if(r.fds[n] == null) return null;
1526 return r.fds[n].fstat();
1528 // FEATURE: inode stuff
1529 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1530 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1534 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1535 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }