1 package org.ibex.nestedvm;
3 import org.ibex.nestedvm.util.*;
4 // FEATURE: This is ugly, this stuff needs to be in org.ibex.util or something
5 import org.ibex.classgen.util.Sort;
12 public abstract class UnixRuntime extends Runtime implements Cloneable {
13 /** The pid of this "process" */
15 private UnixRuntime parent;
16 public final int getPid() { return pid; }
18 private static final GlobalState defaultGS = new GlobalState();
19 private GlobalState gs = defaultGS;
20 public void setGlobalState(GlobalState gs) {
21 if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running");
25 /** proceses' current working directory - absolute path WITHOUT leading slash
26 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
29 /** The runtime that should be run next when in state == EXECED */
30 private UnixRuntime execedRuntime;
32 private Object children; // used only for synchronizatin
33 private Vector activeChildren;
34 private Vector exitedChildren;
36 protected UnixRuntime(int pageSize, int totalPages) {
37 super(pageSize,totalPages);
39 // FEATURE: Do the proper mangling for non-unix hosts
40 String userdir = getSystemProperty("user.dir");
42 userdir != null && userdir.startsWith("/") && File.separatorChar == '/' && getSystemProperty("nestedvm.root") == null
43 ? userdir.substring(1) : "";
46 private static String posixTZ() {
47 StringBuffer sb = new StringBuffer();
48 TimeZone zone = TimeZone.getDefault();
49 int off = zone.getRawOffset() / 1000;
50 sb.append(Platform.timeZoneGetDisplayName(zone,false,false));
51 if(off > 0) sb.append("-");
53 sb.append(off/3600); off = off%3600;
54 if(off > 0) sb.append(":").append(off/60); off=off%60;
55 if(off > 0) sb.append(":").append(off);
56 if(zone.useDaylightTime())
57 sb.append(Platform.timeZoneGetDisplayName(zone,true,false));
61 private static boolean envHas(String key,String[] environ) {
62 for(int i=0;i<environ.length;i++)
63 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
67 String[] createEnv(String[] extra) {
68 String[] defaults = new String[6];
70 if(extra == null) extra = new String[0];
71 if(!envHas("USER",extra) && getSystemProperty("user.name") != null)
72 defaults[n++] = "USER=" + getSystemProperty("user.name");
73 if(!envHas("HOME",extra) && getSystemProperty("user.home") != null)
74 defaults[n++] = "HOME=" + getSystemProperty("user.home");
75 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
76 if(!envHas("TERM",extra)) defaults[n++] = "TERM=vt100";
77 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
78 if(!envHas("PATH",extra)) defaults[n++] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin";
79 String[] env = new String[extra.length+n];
80 for(int i=0;i<n;i++) env[i] = defaults[i];
81 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
85 private static class ProcessTableFullExn extends RuntimeException { }
88 UnixRuntime[] tasks = gs.tasks;
91 UnixRuntime prev = tasks[pid];
92 if(prev == null || prev == this || prev.pid != pid || prev.parent != parent)
93 throw new Error("should never happen");
94 synchronized(parent.children) {
95 int i = parent.activeChildren.indexOf(prev);
96 if(i == -1) throw new Error("should never happen");
97 parent.activeChildren.setElementAt(this,i);
101 int nextPID = gs.nextPID;
102 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
103 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
104 if(newpid == -1) throw new ProcessTableFullExn();
106 gs.nextPID = newpid + 1;
112 int _syscall(int syscall, int a, int b, int c, int d, int e, int f) throws ErrnoException, FaultException {
114 case SYS_kill: return sys_kill(a,b);
115 case SYS_fork: return sys_fork();
116 case SYS_pipe: return sys_pipe(a);
117 case SYS_dup2: return sys_dup2(a,b);
118 case SYS_dup: return sys_dup(a);
119 case SYS_waitpid: return sys_waitpid(a,b,c);
120 case SYS_stat: return sys_stat(a,b);
121 case SYS_lstat: return sys_lstat(a,b);
122 case SYS_mkdir: return sys_mkdir(a,b);
123 case SYS_getcwd: return sys_getcwd(a,b);
124 case SYS_chdir: return sys_chdir(a);
125 case SYS_exec: return sys_exec(a,b,c);
126 case SYS_getdents: return sys_getdents(a,b,c,d);
127 case SYS_unlink: return sys_unlink(a);
128 case SYS_getppid: return sys_getppid();
129 case SYS_socket: return sys_socket(a,b,c);
130 case SYS_connect: return sys_connect(a,b,c);
131 case SYS_resolve_hostname: return sys_resolve_hostname(a,b,c);
132 case SYS_setsockopt: return sys_setsockopt(a,b,c,d,e);
133 case SYS_getsockopt: return sys_getsockopt(a,b,c,d,e);
134 case SYS_bind: return sys_bind(a,b,c);
135 case SYS_listen: return sys_listen(a,b);
136 case SYS_accept: return sys_accept(a,b,c);
137 case SYS_shutdown: return sys_shutdown(a,b);
138 case SYS_sysctl: return sys_sysctl(a,b,c,d,e,f);
140 default: return super._syscall(syscall,a,b,c,d,e,f);
144 FD _open(String path, int flags, int mode) throws ErrnoException {
145 return gs.open(this,normalizePath(path),flags,mode);
148 private int sys_getppid() {
149 return parent == null ? 1 : parent.pid;
152 /** The kill syscall.
153 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
154 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
155 Anything else terminates the process. */
156 private int sys_kill(int pid, int signal) {
157 // This will only be called by raise() in newlib to invoke the default handler
158 // We don't have to worry about actually delivering the signal
159 if(pid != pid) return -ESRCH;
160 if(signal < 0 || signal >= 32) return -EINVAL;
175 // FEATURE: This is ugly, make a clean interface to sys_exit
176 return syscall(SYS_exit,128+signal,0,0,0,0,0);
181 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
182 final int WNOHANG = 1;
183 if((options & ~(WNOHANG)) != 0) return -EINVAL;
184 if(pid == 0 || pid < -1) {
185 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
188 boolean blocking = (options&WNOHANG)==0;
190 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
191 if(children == null) return blocking ? -ECHILD : 0;
193 UnixRuntime done = null;
195 synchronized(children) {
198 if(exitedChildren.size() > 0) {
199 done = (UnixRuntime)exitedChildren.elementAt(exitedChildren.size() - 1);
200 exitedChildren.removeElementAt(exitedChildren.size() - 1);
203 UnixRuntime t = gs.tasks[pid];
204 if(t.parent != this) return -ECHILD;
205 if(t.state == EXITED) {
206 if(!exitedChildren.removeElement(t)) throw new Error("should never happen");
210 // process group stuff, EINVAL returned above
211 throw new Error("should never happen");
214 if(!blocking) return 0;
215 try { children.wait(); } catch(InterruptedException e) {}
216 //System.err.println("waitpid woke up: " + exitedChildren.size());
218 gs.tasks[done.pid] = null;
223 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
229 if(children != null) synchronized(children) {
230 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
231 UnixRuntime child = (UnixRuntime) e.nextElement();
232 gs.tasks[child.pid] = null;
234 exitedChildren.removeAllElements();
235 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
236 UnixRuntime child = (UnixRuntime) e.nextElement();
239 activeChildren.removeAllElements();
242 UnixRuntime _parent = parent;
243 if(_parent == null) {
244 gs.tasks[pid] = null;
246 synchronized(_parent.children) {
248 gs.tasks[pid] = null;
250 if(!parent.activeChildren.removeElement(this)) throw new Error("should never happen _exited: pid: " + pid);
251 parent.exitedChildren.addElement(this);
252 parent.children.notify();
258 protected Object clone() throws CloneNotSupportedException {
259 UnixRuntime r = (UnixRuntime) super.clone();
263 r.activeChildren = r.exitedChildren = null;
267 private int sys_fork() {
268 CPUState state = new CPUState();
270 int sp = state.r[SP];
274 r = (UnixRuntime) clone();
275 } catch(Exception e) {
284 } catch(ProcessTableFullExn e) {
288 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
289 if(children == null) {
290 children = new Object();
291 activeChildren = new Vector();
292 exitedChildren = new Vector();
294 activeChildren.addElement(r);
296 state.r[V0] = 0; // return 0 to child
297 state.pc += 4; // skip over syscall instruction
298 r.setCPUState(state);
301 new ForkedProcess(r);
306 public static final class ForkedProcess extends Thread {
307 private final UnixRuntime initial;
308 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
309 public void run() { UnixRuntime.executeAndExec(initial); }
312 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
313 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
315 public static int executeAndExec(UnixRuntime r) {
318 if(r.execute()) break;
319 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
321 if(r.state != EXECED) return r.exitStatus();
326 private String[] readStringArray(int addr) throws ReadFaultException {
328 for(int p=addr;memRead(p) != 0;p+=4) count++;
329 String[] a = new String[count];
330 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
334 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
335 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
338 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
339 if(argv.length == 0) argv = new String[]{""};
341 // NOTE: For this little hack to work nestedvm.root MUST be "."
343 System.err.println("Execing normalized path: " + normalizedPath);
344 if(true) return exec(new Interpreter(normalizedPath),argv,envp);
345 } catch(IOException e) { throw new Error(e); }*/
347 Object o = gs.exec(this,normalizedPath);
348 if(o == null) return -ENOENT;
350 if(o instanceof Class) {
353 return exec((UnixRuntime) c.newInstance(),argv,envp);
354 } catch(Exception e) {
359 String[] command = (String[]) o;
360 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
361 int p = command[0].lastIndexOf('/');
362 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
364 if(command[1] != null) newArgv[p++] = command[1];
365 newArgv[p++] = "/" + normalizedPath;
366 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
367 return exec(command[0],newArgv,envp);
371 private int exec(UnixRuntime r, String[] argv, String[] envp) {
373 //System.err.println("Execing " + r);
374 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
376 r.closeOnExec = closeOnExec;
377 // make sure this doesn't get messed with these since we didn't copy them
394 // FEATURE: Make sure fstat info is correct
395 // FEATURE: This could be faster if we did direct copies from each process' memory
396 // FEATURE: Check this logic one more time
397 public static class Pipe {
398 private final byte[] pipebuf = new byte[PIPE_BUF*4];
400 private int writePos;
402 public final FD reader = new Reader();
403 public final FD writer = new Writer();
405 public class Reader extends FD {
406 protected FStat _fstat() { return new FStat(); }
407 public int read(byte[] buf, int off, int len) throws ErrnoException {
408 if(len == 0) return 0;
409 synchronized(Pipe.this) {
410 while(writePos != -1 && readPos == writePos) {
411 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
413 if(writePos == -1) return 0; // eof
414 len = Math.min(len,writePos-readPos);
415 System.arraycopy(pipebuf,readPos,buf,off,len);
417 if(readPos == writePos) Pipe.this.notify();
421 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
424 public class Writer extends FD {
425 protected FStat _fstat() { return new FStat(); }
426 public int write(byte[] buf, int off, int len) throws ErrnoException {
427 if(len == 0) return 0;
428 synchronized(Pipe.this) {
429 if(readPos == -1) throw new ErrnoException(EPIPE);
430 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
431 // not enough space to atomicly write the data
432 while(readPos != -1 && readPos != writePos) {
433 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
435 if(readPos == -1) throw new ErrnoException(EPIPE);
436 readPos = writePos = 0;
438 len = Math.min(len,pipebuf.length - writePos);
439 System.arraycopy(buf,off,pipebuf,writePos,len);
440 if(readPos == writePos) Pipe.this.notify();
445 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
449 private int sys_pipe(int addr) {
450 Pipe pipe = new Pipe();
452 int fd1 = addFD(pipe.reader);
453 if(fd1 < 0) return -ENFILE;
454 int fd2 = addFD(pipe.writer);
455 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
459 memWrite(addr+4,fd2);
460 } catch(FaultException e) {
468 private int sys_dup2(int oldd, int newd) {
469 if(oldd == newd) return 0;
470 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
471 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
472 if(fds[oldd] == null) return -EBADFD;
473 if(fds[newd] != null) fds[newd].close();
474 fds[newd] = fds[oldd].dup();
478 private int sys_dup(int oldd) {
479 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
480 if(fds[oldd] == null) return -EBADFD;
481 FD fd = fds[oldd].dup();
482 int newd = addFD(fd);
483 if(newd < 0) { fd.close(); return -ENFILE; }
487 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
488 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
489 if(s == null) return -ENOENT;
493 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
494 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
495 if(s == null) return -ENOENT;
499 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
500 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
504 private int sys_unlink(int cstring) throws FaultException, ErrnoException {
505 gs.unlink(this,normalizePath(cstring(cstring)));
509 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
510 byte[] b = getBytes(cwd);
511 if(size == 0) return -EINVAL;
512 if(size < b.length+2) return -ERANGE;
514 copyout(b,addr+1,b.length);
515 memset(addr+b.length+1,0,1);
519 private int sys_chdir(int addr) throws ErrnoException, FaultException {
520 String path = normalizePath(cstring(addr));
521 FStat st = gs.stat(this,path);
522 if(st == null) return -ENOENT;
523 if(st.type() != FStat.S_IFDIR) return -ENOTDIR;
528 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
529 count = Math.min(count,MAX_CHUNK);
530 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
531 if(fds[fdn] == null) return -EBADFD;
532 byte[] buf = byteBuf(count);
533 int n = fds[fdn].getdents(buf,0,count);
538 // FEATURE: UDP is totally broken
540 static class SocketFD extends FD {
541 public static final int TYPE_STREAM = 0;
542 public static final int TYPE_DGRAM = 1;
543 public static final int LISTEN = 2;
544 public int type() { return flags & 1; }
545 public boolean listen() { return (flags & 2) != 0; }
550 InetAddress bindAddr;
556 public SocketFD(int type) { flags = type; }
558 public void setOptions() {
560 if(o != null && type() == TYPE_STREAM && !listen()) {
561 Platform.socketSetKeepAlive((Socket)o,(options & SO_KEEPALIVE) != 0);
563 } catch(SocketException e) {
564 if(STDERR_DIAG) e.printStackTrace();
568 public void _close() {
571 if(type() == TYPE_STREAM) {
572 if(listen()) ((ServerSocket)o).close();
573 else ((Socket)o).close();
575 ((DatagramSocket)o).close();
577 } catch(IOException e) {
583 public int read(byte[] a, int off, int length) throws ErrnoException {
584 if(type() == TYPE_STREAM) {
585 if(is == null) throw new ErrnoException(EPIPE);
587 int n = is.read(a,off,length);
588 return n < 0 ? 0 : n;
589 } catch(IOException e) {
590 throw new ErrnoException(EIO);
593 if(off != 0) throw new IllegalArgumentException("off must be 0");
594 DatagramSocket ds = (DatagramSocket) o;
596 dp.setLength(length);
599 } catch(IOException e) {
600 throw new ErrnoException(EIO);
602 return dp.getLength();
606 public int write(byte[] a, int off, int length) throws ErrnoException {
607 if(type() == TYPE_STREAM) {
608 if(os == null) throw new ErrnoException(EPIPE);
610 os.write(a,off,length);
612 } catch(IOException e) {
613 throw new ErrnoException(EIO);
616 if(off != 0) throw new IllegalArgumentException("off must be 0");
617 DatagramSocket ds = (DatagramSocket) o;
619 dp.setLength(length);
622 } catch(IOException e) {
623 throw new ErrnoException(EIO);
625 return dp.getLength();
629 // FEATURE: Check that these are correct
631 if(is != null && os != null) return O_RDWR;
632 if(is != null) return O_RDONLY;
633 if(os != null) return O_WRONLY;
637 // FEATURE: Populate this properly
638 public FStat _fstat() { return new FStat(); }
641 private int sys_socket(int domain, int type, int proto) {
642 if(domain != AF_INET || (type != SOCK_STREAM && type != SOCK_DGRAM)) return -EPROTONOSUPPORT;
643 return addFD(new SocketFD(type == SOCK_STREAM ? SocketFD.TYPE_STREAM : SocketFD.TYPE_DGRAM));
646 private SocketFD getSocketFD(int fdn) throws ErrnoException {
647 if(fdn < 0 || fdn >= OPEN_MAX) throw new ErrnoException(EBADFD);
648 if(fds[fdn] == null) throw new ErrnoException(EBADFD);
649 if(!(fds[fdn] instanceof SocketFD)) throw new ErrnoException(ENOTSOCK);
651 return (SocketFD) fds[fdn];
654 private int sys_connect(int fdn, int addr, int namelen) throws ErrnoException, FaultException {
655 SocketFD fd = getSocketFD(fdn);
657 if(fd.type() == SocketFD.TYPE_STREAM && fd.o != null) return -EISCONN;
658 int word1 = memRead(addr);
659 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
660 int port = word1 & 0xffff;
661 byte[] ip = new byte[4];
664 InetAddress inetAddr;
666 inetAddr = Platform.inetAddressFromBytes(ip);
667 } catch(UnknownHostException e) {
668 return -EADDRNOTAVAIL;
673 case SocketFD.TYPE_STREAM: {
674 Socket s = new Socket(inetAddr,port);
677 fd.is = s.getInputStream();
678 fd.os = s.getOutputStream();
681 case SocketFD.TYPE_DGRAM: {
682 if(fd.dp == null) fd.dp = new DatagramPacket(null,0);
683 fd.dp.setAddress(inetAddr);
688 throw new Error("should never happen");
690 } catch(IOException e) {
691 return -ECONNREFUSED;
697 private int sys_resolve_hostname(int chostname, int addr, int sizeAddr) throws FaultException {
698 String hostname = cstring(chostname);
699 int size = memRead(sizeAddr);
700 InetAddress[] inetAddrs;
702 inetAddrs = InetAddress.getAllByName(hostname);
703 } catch(UnknownHostException e) {
704 return HOST_NOT_FOUND;
706 int count = min(size/4,inetAddrs.length);
707 for(int i=0;i<count;i++,addr+=4) {
708 byte[] b = inetAddrs[i].getAddress();
711 memWrite(sizeAddr,count*4);
715 private int sys_setsockopt(int fdn, int level, int name, int valaddr, int len) throws ReadFaultException, ErrnoException {
716 SocketFD fd = getSocketFD(fdn);
722 if(len != 4) return -EINVAL;
723 int val = memRead(valaddr);
724 if(val != 0) fd.options |= name;
725 else fd.options &= ~name;
730 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
734 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
739 private int sys_getsockopt(int fdn, int level, int name, int valaddr, int lenaddr) throws ErrnoException, FaultException {
740 SocketFD fd = getSocketFD(fdn);
746 int len = memRead(lenaddr);
747 if(len < 4) return -EINVAL;
748 int val = (fd.options & name) != 0 ? 1 : 0;
749 memWrite(valaddr,val);
754 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
758 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
763 private int sys_bind(int fdn, int addr, int namelen) throws FaultException, ErrnoException {
764 SocketFD fd = getSocketFD(fdn);
766 if(fd.type() == SocketFD.TYPE_STREAM && fd.o != null) return -EISCONN;
767 int word1 = memRead(addr);
768 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
769 int port = word1 & 0xffff;
770 InetAddress inetAddr = null;
771 if(memRead(addr+4) != 0) {
772 byte[] ip = new byte[4];
776 inetAddr = Platform.inetAddressFromBytes(ip);
777 } catch(UnknownHostException e) {
778 return -EADDRNOTAVAIL;
783 case SocketFD.TYPE_STREAM: {
784 fd.bindAddr = inetAddr;
788 case SocketFD.TYPE_DGRAM: {
789 DatagramSocket s = (DatagramSocket) fd.o;
790 if(s != null) s.close();
792 fd.o = inetAddr != null ? new DatagramSocket(port,inetAddr) : new DatagramSocket(port);
793 } catch(IOException e) {
799 throw new Error("should never happen");
803 private int sys_listen(int fdn, int backlog) throws ErrnoException {
804 SocketFD fd = getSocketFD(fdn);
805 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
806 if(fd.o != null) return -EISCONN;
807 if(fd.bindPort < 0) return -EOPNOTSUPP;
810 fd.o = new ServerSocket(fd.bindPort,backlog,fd.bindAddr);
811 fd.flags |= SocketFD.LISTEN;
813 } catch(IOException e) {
819 private int sys_accept(int fdn, int addr, int lenaddr) throws ErrnoException, FaultException {
820 SocketFD fd = getSocketFD(fdn);
821 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
822 if(!fd.listen()) return -EOPNOTSUPP;
824 int size = memRead(lenaddr);
826 ServerSocket s = (ServerSocket) fd.o;
830 } catch(IOException e) {
835 memWrite(addr,(6 << 24) | (AF_INET << 16) | client.getPort());
836 byte[] b = client.getInetAddress().getAddress();
841 SocketFD clientFD = new SocketFD(SocketFD.TYPE_STREAM);
844 clientFD.is = client.getInputStream();
845 clientFD.os = client.getOutputStream();
846 } catch(IOException e) {
849 int n = addFD(clientFD);
850 if(n == -1) { clientFD.close(); return -ENFILE; }
854 private int sys_shutdown(int fdn, int how) throws ErrnoException {
855 SocketFD fd = getSocketFD(fdn);
856 if(fd.type() != SocketFD.TYPE_STREAM || fd.listen()) return -EOPNOTSUPP;
857 if(fd.o == null) return -ENOTCONN;
859 Socket s = (Socket) fd.o;
862 if(how == SHUT_RD || how == SHUT_RDWR) Platform.socketHalfClose(s,false);
863 if(how == SHUT_WR || how == SHUT_RDWR) Platform.socketHalfClose(s,true);
864 } catch(IOException e) {
871 private static String hostName() {
873 return InetAddress.getLocalHost().getHostName();
874 } catch(UnknownHostException e) {
879 private int sys_sysctl(int nameaddr, int namelen, int oldp, int oldlenaddr, int newp, int newlen) throws FaultException {
880 if(newp != 0) return -EPERM;
881 if(namelen == 0) return -ENOENT;
882 if(oldp == 0) return 0;
885 switch(memRead(nameaddr)) {
887 if(namelen != 2) break;
888 switch(memRead(nameaddr+4)) {
889 case KERN_OSTYPE: o = "NestedVM"; break;
890 case KERN_HOSTNAME: o = hostName(); break;
891 case KERN_OSRELEASE: o = VERSION; break;
892 case KERN_VERSION: o = "NestedVM Kernel Version " + VERSION; break;
896 if(namelen != 2) break;
897 switch(memRead(nameaddr+4)) {
898 case HW_MACHINE: o = "NestedVM Virtual Machine"; break;
902 if(o == null) return -ENOENT;
903 int len = memRead(oldlenaddr);
904 if(o instanceof String) {
905 byte[] b = getNullTerminatedBytes((String)o);
906 if(len < b.length) return -ENOMEM;
909 memWrite(oldlenaddr,len);
910 } else if(o instanceof Integer) {
911 if(len < 4) return -ENOMEM;
912 memWrite(oldp,((Integer)o).intValue());
914 throw new Error("should never happen");
919 // FEATURE: Run through the fork/wait stuff one more time
920 public static class GlobalState {
921 protected static final int OPEN = 1;
922 protected static final int STAT = 2;
923 protected static final int LSTAT = 3;
924 protected static final int MKDIR = 4;
925 protected static final int UNLINK = 5;
927 final UnixRuntime[] tasks;
930 private MP[] mps = new MP[0];
933 public GlobalState() { this(255); }
934 public GlobalState(int maxProcs) { this(maxProcs,true); }
935 public GlobalState(int maxProcs, boolean defaultMounts) {
936 tasks = new UnixRuntime[maxProcs+1];
938 addMount("/",new HostFS());
939 addMount("/dev",new DevFS());
943 private static class MP implements Sort.Comparable {
944 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
947 public int compareTo(Object o) {
948 if(!(o instanceof MP)) return 1;
949 return -path.compareTo(((MP)o).path);
953 public synchronized FS getMount(String path) {
954 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
955 if(path.equals("/")) return root;
956 path = path.substring(1);
957 for(int i=0;i<mps.length;i++)
958 if(mps[i].path.equals(path)) return mps[i].fs;
962 public synchronized void addMount(String path, FS fs) {
963 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
964 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
966 if(fs.owner != null) fs.owner.removeMount(fs);
969 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
970 path = path.substring(1);
971 int oldLength = mps.length;
972 MP[] newMPS = new MP[oldLength + 1];
973 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
974 newMPS[oldLength] = new MP(path,fs);
978 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
979 fs.devno = highdevno + 2;
982 public synchronized void removeMount(FS fs) {
983 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
984 throw new IllegalArgumentException("mount point doesn't exist");
987 public synchronized void removeMount(String path) {
988 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
989 if(path.equals("/")) {
992 path = path.substring(1);
994 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
995 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
1000 private void removeMount(int index) {
1001 if(index == -1) { root.owner = null; root = null; return; }
1002 MP[] newMPS = new MP[mps.length - 1];
1003 System.arraycopy(mps,0,newMPS,0,index);
1004 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
1008 // FEATURE: We shouldn't need to special case the root dir, it should work in the MP array
1009 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
1010 int pl = normalizedPath.length();
1013 synchronized(this) { list = mps; }
1014 for(int i=0;i<list.length;i++) {
1016 int mpl = mp.path.length();
1017 if(normalizedPath.startsWith(mp.path) && (pl == mpl || normalizedPath.charAt(mpl) == '/'))
1018 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
1021 return dispatch(root,op,r,normalizedPath,arg1,arg2);
1024 // FEATURE: move this into FS so some filesystem can override it directly (devfs)
1025 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
1027 case OPEN: return fs.open(r,path,arg1,arg2);
1028 case STAT: return fs.stat(r,path);
1029 case LSTAT: return fs.lstat(r,path);
1030 case MKDIR: fs.mkdir(r,path,arg1); return null;
1031 case UNLINK: fs.unlink(r,path); return null;
1032 default: throw new Error("should never happen");
1036 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
1037 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
1038 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
1039 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
1040 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
1042 private Hashtable execCache = new Hashtable();
1043 private static class CacheEnt {
1044 public final long time;
1045 public final long size;
1046 public final Object o;
1047 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
1050 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
1051 // HACK: Hideous hack to make a standalone busybox possible
1052 if(path.equals("bin/busybox") && Boolean.valueOf(getSystemProperty("nestedvm.busyboxhack")).booleanValue())
1053 return r.getClass();
1054 FStat fstat = stat(r,path);
1055 if(fstat == null) return null;
1056 long mtime = fstat.mtime();
1057 long size = fstat.size();
1058 CacheEnt ent = (CacheEnt) execCache.get(path);
1060 //System.err.println("Found cached entry for " + path);
1061 if(ent.time == mtime && ent.size == size) return ent.o;
1062 //System.err.println("Cache was out of date");
1063 execCache.remove(path);
1065 FD fd = open(r,path,RD_ONLY,0);
1066 if(fd == null) return null;
1067 Seekable s = fd.seekable();
1069 String[] command = null;
1071 if(s == null) throw new ErrnoException(EACCES);
1072 byte[] buf = new byte[4096];
1075 int n = s.read(buf,0,buf.length);
1076 if(n == -1) throw new ErrnoException(ENOEXEC);
1079 case '\177': // possible ELF
1080 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
1081 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
1085 int n2 = s.read(buf,1,buf.length-1);
1086 if(n2 == -1) throw new ErrnoException(ENOEXEC);
1089 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
1093 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
1095 if(p == buf.length) break OUTER;
1096 n = s.read(buf,p,buf.length-p);
1098 command = new String[2];
1100 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
1103 while(arg < p && buf[arg] == ' ') arg++;
1104 command[0] = new String(buf,2,cmdEnd);
1105 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
1107 command[0] = new String(buf,2,p-2);
1109 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
1112 throw new ErrnoException(ENOEXEC);
1114 } catch(IOException e) {
1116 throw new ErrnoException(EIO);
1119 if(command == null) {
1120 // its an elf binary
1123 Class c = RuntimeCompiler.compile(s,"unixruntime");
1124 //System.err.println("Compile succeeded: " + c);
1125 ent = new CacheEnt(mtime,size,c);
1126 } catch(Compiler.Exn e) {
1127 if(STDERR_DIAG) e.printStackTrace();
1128 throw new ErrnoException(ENOEXEC);
1129 } catch(IOException e) {
1130 if(STDERR_DIAG) e.printStackTrace();
1131 throw new ErrnoException(EIO);
1134 ent = new CacheEnt(mtime,size,command);
1139 execCache.put(path,ent);
1144 public abstract static class FS {
1148 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1150 // If this returns null it'll be truned into an ENOENT
1151 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
1152 // If this returns null it'll be turned into an ENOENT
1153 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
1154 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
1155 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
1158 // FEATURE: chroot support in here
1159 private String normalizePath(String path) {
1160 boolean absolute = path.startsWith("/");
1161 int cwdl = cwd.length();
1162 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
1163 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
1164 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
1166 char[] in = new char[path.length()+1];
1167 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
1171 do { inp++; } while(in[inp] == '/');
1172 } else if(cwdl != 0) {
1173 cwd.getChars(0,cwdl,out,0);
1177 path.getChars(0,path.length(),in,0);
1178 while(in[inp] != 0) {
1179 if(inp != 0 || cwdl==0) {
1180 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
1181 while(in[inp] == '/') inp++;
1183 if(in[inp] == '\0') continue;
1184 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
1185 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
1186 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
1188 if(outp > 0) outp--;
1189 while(outp > 0 && out[outp] != '/') outp--;
1190 //System.err.println("After ..: " + new String(out,0,outp));
1197 if(outp > 0 && out[outp-1] == '/') outp--;
1198 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
1199 return new String(out,0,outp);
1202 FStat hostFStat(final File f, Object data) {
1205 FileInputStream fis = new FileInputStream(f);
1206 switch(fis.read()) {
1207 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
1208 case '#': e = fis.read() == '!';
1211 } catch(IOException e2) { }
1212 HostFS fs = (HostFS) data;
1213 final int inode = fs.inodes.get(f.getAbsolutePath());
1214 final int devno = fs.devno;
1215 return new HostFStat(f,e) {
1216 public int inode() { return inode; }
1217 public int dev() { return devno; }
1221 FD hostFSDirFD(File f, Object _fs) {
1222 HostFS fs = (HostFS) _fs;
1223 return fs.new HostDirFD(f);
1226 public static class HostFS extends FS {
1227 InodeCache inodes = new InodeCache(4000);
1228 protected File root;
1229 public File getRoot() { return root; }
1231 private static File hostRootDir() {
1232 if(getSystemProperty("nestedvm.root") != null) {
1233 File f = new File(getSystemProperty("nestedvm.root"));
1234 if(f.isDirectory()) return f;
1235 // fall through to case below
1237 String cwd = getSystemProperty("user.dir");
1238 File f = new File(cwd != null ? cwd : ".");
1239 if(!f.exists()) throw new Error("Couldn't get File for cwd");
1240 f = new File(f.getAbsolutePath());
1241 while(f.getParent() != null) f = new File(f.getParent());
1245 private File hostFile(String path) {
1246 char sep = File.separatorChar;
1248 char buf[] = path.toCharArray();
1249 for(int i=0;i<buf.length;i++) {
1251 if(c == '/') buf[i] = sep;
1252 else if(c == sep) buf[i] = '/';
1254 path = new String(buf);
1256 return new File(root,path);
1259 public HostFS() { this(hostRootDir()); }
1260 public HostFS(String root) { this(new File(root)); }
1261 public HostFS(File root) { this.root = root; }
1264 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1265 final File f = hostFile(path);
1266 return r.hostFSOpen(f,flags,mode,this);
1269 public void unlink(UnixRuntime r, String path) throws ErrnoException {
1270 File f = hostFile(path);
1271 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1272 if(!f.exists()) throw new ErrnoException(ENOENT);
1273 if(!f.delete()) throw new ErrnoException(EPERM);
1276 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1277 File f = hostFile(path);
1278 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1279 if(!f.exists()) return null;
1280 return r.hostFStat(f,this);
1283 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1284 File f = hostFile(path);
1285 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1286 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1287 if(f.exists()) throw new ErrnoException(ENOTDIR);
1288 File parent = getParentFile(f);
1289 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1290 if(!f.mkdir()) throw new ErrnoException(EIO);
1293 private static File getParentFile(File f) {
1294 String p = f.getParent();
1295 return p == null ? null : new File(f,p);
1298 public class HostDirFD extends DirFD {
1299 private final File f;
1300 private final File[] children;
1301 public HostDirFD(File f) {
1303 String[] l = f.list();
1304 children = new File[l.length];
1305 for(int i=0;i<l.length;i++) children[i] = new File(f,l[i]);
1307 public int size() { return children.length; }
1308 public String name(int n) { return children[n].getName(); }
1309 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1310 public int parentInode() {
1311 File parent = getParentFile(f);
1312 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
1314 public int myInode() { return inodes.get(f.getAbsolutePath()); }
1315 public int myDev() { return devno; }
1319 private static void putInt(byte[] buf, int off, int n) {
1320 buf[off+0] = (byte)((n>>>24)&0xff);
1321 buf[off+1] = (byte)((n>>>16)&0xff);
1322 buf[off+2] = (byte)((n>>> 8)&0xff);
1323 buf[off+3] = (byte)((n>>> 0)&0xff);
1326 public static abstract class DirFD extends FD {
1327 private int pos = -2;
1329 protected abstract int size();
1330 protected abstract String name(int n);
1331 protected abstract int inode(int n);
1332 protected abstract int myDev();
1333 protected int parentInode() { return -1; }
1334 protected int myInode() { return -1; }
1336 public int getdents(byte[] buf, int off, int len) {
1340 OUTER: for(;len > 0 && pos < size();pos++){
1344 ino = pos == -1 ? parentInode() : myInode();
1345 if(ino == -1) continue;
1346 reclen = 9 + (pos == -1 ? 2 : 1);
1347 if(reclen > len) break OUTER;
1349 if(pos == -1) buf[off+9] = '.';
1352 String f = name(pos);
1353 byte[] fb = getBytes(f);
1354 reclen = fb.length + 9;
1355 if(reclen > len) break OUTER;
1357 System.arraycopy(fb,0,buf,off+8,fb.length);
1360 buf[off+reclen-1] = 0; // null terminate
1361 reclen = (reclen + 3) & ~3; // add padding
1362 putInt(buf,off,reclen);
1363 putInt(buf,off+4,ino);
1370 protected FStat _fstat() {
1371 return new FStat() {
1372 public int type() { return S_IFDIR; }
1373 public int inode() { return myInode(); }
1374 public int dev() { return myDev(); }
1379 public static class DevFS extends FS {
1380 private static final int ROOT_INODE = 1;
1381 private static final int NULL_INODE = 2;
1382 private static final int ZERO_INODE = 3;
1383 private static final int FD_INODE = 4;
1384 private static final int FD_INODES = 32;
1386 private class DevFStat extends FStat {
1387 public int dev() { return devno; }
1388 public int mode() { return 0666; }
1389 public int type() { return S_IFCHR; }
1390 public int nlink() { return 1; }
1393 private abstract class DevDirFD extends DirFD {
1394 public int myDev() { return devno; }
1397 private FD devZeroFD = new FD() {
1398 public int read(byte[] a, int off, int length) {
1399 /*Arrays.fill(a,off,off+length,(byte)0);*/
1400 for(int i=off;i<off+length;i++) a[i] = 0;
1403 public int write(byte[] a, int off, int length) { return length; }
1404 public int seek(int n, int whence) { return 0; }
1405 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1407 private FD devNullFD = new FD() {
1408 public int read(byte[] a, int off, int length) { return 0; }
1409 public int write(byte[] a, int off, int length) { return length; }
1410 public int seek(int n, int whence) { return 0; }
1411 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1414 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1415 if(path.equals("null")) return devNullFD;
1416 if(path.equals("zero")) return devZeroFD;
1417 if(path.startsWith("fd/")) {
1420 n = Integer.parseInt(path.substring(4));
1421 } catch(NumberFormatException e) {
1424 if(n < 0 || n >= OPEN_MAX) return null;
1425 if(r.fds[n] == null) return null;
1426 return r.fds[n].dup();
1428 if(path.equals("fd")) {
1430 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1431 final int[] files = new int[count];
1433 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1434 return new DevDirFD() {
1435 public int myInode() { return FD_INODE; }
1436 public int parentInode() { return ROOT_INODE; }
1437 public int inode(int n) { return FD_INODES + n; }
1438 public String name(int n) { return Integer.toString(files[n]); }
1439 public int size() { return files.length; }
1442 if(path.equals("")) {
1443 return new DevDirFD() {
1444 public int myInode() { return ROOT_INODE; }
1445 // FEATURE: Get the real parent inode somehow
1446 public int parentInode() { return -1; }
1447 public int inode(int n) {
1449 case 0: return NULL_INODE;
1450 case 1: return ZERO_INODE;
1451 case 2: return FD_INODE;
1456 public String name(int n) {
1458 case 0: return "null";
1459 case 1: return "zero";
1460 case 2: return "fd";
1461 default: return null;
1464 public int size() { return 3; }
1470 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1471 if(path.equals("null")) return devNullFD.fstat();
1472 if(path.equals("zero")) return devZeroFD.fstat();
1473 if(path.startsWith("fd/")) {
1476 n = Integer.parseInt(path.substring(3));
1477 } catch(NumberFormatException e) {
1480 if(n < 0 || n >= OPEN_MAX) return null;
1481 if(r.fds[n] == null) return null;
1482 return r.fds[n].fstat();
1484 // FEATURE: inode stuff
1485 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1486 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1490 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1491 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }