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 // 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("-");
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));
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;
66 String[] createEnv(String[] extra) {
67 String[] defaults = new String[6];
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];
84 private static class ProcessTableFullExn extends RuntimeException { }
87 UnixRuntime[] tasks = gs.tasks;
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);
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();
105 gs.nextPID = newpid + 1;
111 int _syscall(int syscall, int a, int b, int c, int d, int e, int f) throws ErrnoException, FaultException {
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);
139 default: return super._syscall(syscall,a,b,c,d,e,f);
143 FD _open(String path, int flags, int mode) throws ErrnoException {
144 return gs.open(this,normalizePath(path),flags,mode);
147 private int sys_getppid() {
148 return parent == null ? 1 : parent.pid;
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;
174 // FEATURE: This is ugly, make a clean interface to sys_exit
175 return syscall(SYS_exit,128+signal,0,0,0,0,0);
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);
187 boolean blocking = (options&WNOHANG)==0;
189 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
190 if(children == null) return blocking ? -ECHILD : 0;
192 UnixRuntime done = null;
194 synchronized(children) {
197 if(exitedChildren.size() > 0) done = (UnixRuntime)exitedChildren.remove(exitedChildren.size() - 1);
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");
206 // process group stuff, EINVAL returned above
207 throw new Error("should never happen");
210 if(!blocking) return 0;
211 try { children.wait(); } catch(InterruptedException e) {}
212 //System.err.println("waitpid woke up: " + exitedChildren.size());
214 gs.tasks[done.pid] = null;
219 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
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;
230 exitedChildren.clear();
231 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
232 UnixRuntime child = (UnixRuntime) e.nextElement();
235 activeChildren.clear();
238 UnixRuntime _parent = parent;
239 if(_parent == null) {
240 gs.tasks[pid] = null;
242 synchronized(_parent.children) {
244 gs.tasks[pid] = null;
246 if(!parent.activeChildren.remove(this)) throw new Error("should never happen _exited: pid: " + pid);
247 parent.exitedChildren.add(this);
248 parent.children.notify();
254 protected Object clone() throws CloneNotSupportedException {
255 UnixRuntime r = (UnixRuntime) super.clone();
259 r.activeChildren = r.exitedChildren = null;
263 private int sys_fork() {
264 CPUState state = new CPUState();
266 int sp = state.r[SP];
270 r = (UnixRuntime) clone();
271 } catch(Exception e) {
280 } catch(ProcessTableFullExn e) {
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();
290 activeChildren.add(r);
292 state.r[V0] = 0; // return 0 to child
293 state.pc += 4; // skip over syscall instruction
294 r.setCPUState(state);
297 new ForkedProcess(r);
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); }
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); }
311 public static int executeAndExec(UnixRuntime r) {
314 if(r.execute()) break;
315 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
317 if(r.state != EXECED) return r.exitStatus();
322 private String[] readStringArray(int addr) throws ReadFaultException {
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));
330 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
331 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
334 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
335 if(argv.length == 0) argv = new String[]{""};
337 // NOTE: For this little hack to work nestedvm.root MUST be "."
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); }*/
343 Object o = gs.exec(this,normalizedPath);
344 if(o == null) return -ENOENT;
346 if(o instanceof Class) {
349 return exec((UnixRuntime) c.newInstance(),argv,envp);
350 } catch(Exception e) {
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);
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);
367 private int exec(UnixRuntime r, String[] argv, String[] envp) {
369 //System.err.println("Execing " + r);
370 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
372 r.closeOnExec = closeOnExec;
373 // make sure this doesn't get messed with these since we didn't copy them
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];
396 private int writePos;
398 public final FD reader = new Reader();
399 public final FD writer = new Writer();
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 */ }
409 if(writePos == -1) return 0; // eof
410 len = Math.min(len,writePos-readPos);
411 System.arraycopy(pipebuf,readPos,buf,off,len);
413 if(readPos == writePos) Pipe.this.notify();
417 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
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 */ }
431 if(readPos == -1) throw new ErrnoException(EPIPE);
432 readPos = writePos = 0;
434 len = Math.min(len,pipebuf.length - writePos);
435 System.arraycopy(buf,off,pipebuf,writePos,len);
436 if(readPos == writePos) Pipe.this.notify();
441 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
445 private int sys_pipe(int addr) {
446 Pipe pipe = new Pipe();
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; }
455 memWrite(addr+4,fd2);
456 } catch(FaultException e) {
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();
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; }
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;
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;
495 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
496 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
500 private int sys_unlink(int cstring) throws FaultException, ErrnoException {
501 gs.unlink(this,normalizePath(cstring(cstring)));
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;
510 copyout(b,addr+1,b.length);
511 memset(addr+b.length+1,0,1);
515 private int sys_chdir(int addr) throws ErrnoException, FaultException {
516 String path = normalizePath(cstring(addr));
517 FStat st = gs.stat(this,path);
518 if(st == null) return -ENOENT;
519 if(st.type() != FStat.S_IFDIR) return -ENOTDIR;
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);
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; }
544 InetAddress bindAddr;
550 public SocketFD(int type) { flags = type; }
552 public void setOptions() {
554 if(o != null && type() == TYPE_STREAM && !listen()) {
555 ((Socket)o).setKeepAlive((options & SO_KEEPALIVE) != 0);
557 } catch(SocketException e) {
558 if(STDERR_DIAG) e.printStackTrace();
562 public void _close() {
565 if(type() == TYPE_STREAM) {
566 if(listen()) ((ServerSocket)o).close();
567 else ((Socket)o).close();
569 ((DatagramSocket)o).close();
571 } catch(IOException e) {
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);
581 int n = is.read(a,off,length);
582 return n < 0 ? 0 : n;
583 } catch(IOException e) {
584 throw new ErrnoException(EIO);
587 DatagramSocket ds = (DatagramSocket) o;
588 dp.setData(a,off,length);
591 } catch(IOException e) {
592 throw new ErrnoException(EIO);
594 return dp.getLength();
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);
602 os.write(a,off,length);
604 } catch(IOException e) {
605 throw new ErrnoException(EIO);
608 DatagramSocket ds = (DatagramSocket) o;
609 dp.setData(a,off,length);
612 } catch(IOException e) {
613 throw new ErrnoException(EIO);
615 return dp.getLength();
619 // FEATURE: Check that these are correct
621 if(is != null && os != null) return O_RDWR;
622 if(is != null) return O_RDONLY;
623 if(os != null) return O_WRONLY;
627 // FEATURE: Populate this properly
628 public FStat _fstat() { return new FStat(); }
631 private int sys_socket(int domain, int type, int proto) {
632 if(domain != AF_INET || (type != SOCK_STREAM && type != SOCK_DGRAM)) return -EPROTONOSUPPORT;
633 return addFD(new SocketFD(type == SOCK_STREAM ? SocketFD.TYPE_STREAM : SocketFD.TYPE_DGRAM));
636 private SocketFD getSocketFD(int fdn) throws ErrnoException {
637 if(fdn < 0 || fdn >= OPEN_MAX) throw new ErrnoException(EBADFD);
638 if(fds[fdn] == null) throw new ErrnoException(EBADFD);
639 if(!(fds[fdn] instanceof SocketFD)) throw new ErrnoException(ENOTSOCK);
641 return (SocketFD) fds[fdn];
644 private int sys_connect(int fdn, int addr, int namelen) throws ErrnoException, FaultException {
645 SocketFD fd = getSocketFD(fdn);
647 if(fd.type() == SocketFD.TYPE_STREAM && fd.o != null) return -EISCONN;
648 int word1 = memRead(addr);
649 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
650 int port = word1 & 0xffff;
651 byte[] ip = new byte[4];
654 InetAddress inetAddr;
656 inetAddr = InetAddress.getByAddress(ip);
657 } catch(UnknownHostException e) {
658 return -EADDRNOTAVAIL;
663 case SocketFD.TYPE_STREAM: {
664 Socket s = new Socket(inetAddr,port);
667 fd.is = s.getInputStream();
668 fd.os = s.getOutputStream();
671 case SocketFD.TYPE_DGRAM: {
672 DatagramSocket s = (DatagramSocket) fd.o;
673 if(s == null) s = new DatagramSocket();
674 s.connect(inetAddr,port);
678 throw new Error("should never happen");
680 } catch(IOException e) {
681 return -ECONNREFUSED;
687 private int sys_resolve_hostname(int chostname, int addr, int sizeAddr) throws FaultException {
688 String hostname = cstring(chostname);
689 int size = memRead(sizeAddr);
690 InetAddress[] inetAddrs;
692 inetAddrs = InetAddress.getAllByName(hostname);
693 } catch(UnknownHostException e) {
694 return HOST_NOT_FOUND;
696 int count = min(size/4,inetAddrs.length);
697 for(int i=0;i<count;i++,addr+=4) {
698 byte[] b = inetAddrs[i].getAddress();
701 memWrite(sizeAddr,count*4);
705 private int sys_setsockopt(int fdn, int level, int name, int valaddr, int len) throws ReadFaultException, ErrnoException {
706 SocketFD fd = getSocketFD(fdn);
712 if(len != 4) return -EINVAL;
713 int val = memRead(valaddr);
714 if(val != 0) fd.options |= name;
715 else fd.options &= ~name;
720 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
724 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
729 private int sys_getsockopt(int fdn, int level, int name, int valaddr, int lenaddr) throws ErrnoException, FaultException {
730 SocketFD fd = getSocketFD(fdn);
736 int len = memRead(lenaddr);
737 if(len < 4) return -EINVAL;
738 int val = (fd.options & name) != 0 ? 1 : 0;
739 memWrite(valaddr,val);
744 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
748 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
753 private int sys_bind(int fdn, int addr, int namelen) throws FaultException, ErrnoException {
754 SocketFD fd = getSocketFD(fdn);
756 if(fd.type() == SocketFD.TYPE_STREAM && fd.o != null) return -EISCONN;
757 int word1 = memRead(addr);
758 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
759 int port = word1 & 0xffff;
760 InetAddress inetAddr = null;
761 if(memRead(addr+4) != 0) {
762 byte[] ip = new byte[4];
766 inetAddr = InetAddress.getByAddress(ip);
767 } catch(UnknownHostException e) {
768 return -EADDRNOTAVAIL;
773 case SocketFD.TYPE_STREAM: {
774 fd.bindAddr = inetAddr;
778 case SocketFD.TYPE_DGRAM: {
779 DatagramSocket s = (DatagramSocket) fd.o;
780 if(s != null) s.close();
782 fd.o = inetAddr != null ? new DatagramSocket(port,inetAddr) : new DatagramSocket(port);
783 } catch(IOException e) {
789 throw new Error("should never happen");
793 private int sys_listen(int fdn, int backlog) throws ErrnoException {
794 SocketFD fd = getSocketFD(fdn);
795 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
796 if(fd.o != null) return -EISCONN;
797 if(fd.bindPort < 0) return -EOPNOTSUPP;
800 fd.o = new ServerSocket(fd.bindPort,backlog,fd.bindAddr);
801 fd.flags |= SocketFD.LISTEN;
803 } catch(IOException e) {
809 private int sys_accept(int fdn, int addr, int lenaddr) throws ErrnoException, FaultException {
810 SocketFD fd = getSocketFD(fdn);
811 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
812 if(!fd.listen()) return -EOPNOTSUPP;
814 int size = memRead(lenaddr);
816 ServerSocket s = (ServerSocket) fd.o;
820 } catch(IOException e) {
825 memWrite(addr,(6 << 24) | (AF_INET << 16) | client.getPort());
826 byte[] b = client.getInetAddress().getAddress();
831 SocketFD clientFD = new SocketFD(SocketFD.TYPE_STREAM);
834 clientFD.is = client.getInputStream();
835 clientFD.os = client.getOutputStream();
836 } catch(IOException e) {
839 int n = addFD(clientFD);
840 if(n == -1) { clientFD.close(); return -ENFILE; }
844 private int sys_shutdown(int fdn, int how) throws ErrnoException {
845 SocketFD fd = getSocketFD(fdn);
846 if(fd.type() != SocketFD.TYPE_STREAM || fd.listen()) return -EOPNOTSUPP;
847 if(fd.o == null) return -ENOTCONN;
849 Socket s = (Socket) fd.o;
852 if(how == SHUT_RD || how == SHUT_RDWR) s.shutdownInput();
853 if(how == SHUT_WR || how == SHUT_RDWR) s.shutdownOutput();
854 } catch(IOException e) {
861 private static String hostName() {
863 return InetAddress.getLocalHost().getHostName();
864 } catch(UnknownHostException e) {
869 private int sys_sysctl(int nameaddr, int namelen, int oldp, int oldlenaddr, int newp, int newlen) throws FaultException {
870 if(newp != 0) return -EPERM;
871 if(namelen == 0) return -ENOENT;
872 if(oldp == 0) return 0;
875 switch(memRead(nameaddr)) {
877 if(namelen != 2) break;
878 switch(memRead(nameaddr+4)) {
879 case KERN_OSTYPE: o = "NestedVM"; break;
880 case KERN_HOSTNAME: o = hostName(); break;
881 case KERN_OSRELEASE: o = VERSION; break;
882 case KERN_VERSION: o = "NestedVM Kernel Version " + VERSION; break;
886 if(namelen != 2) break;
887 switch(memRead(nameaddr+4)) {
888 case HW_MACHINE: o = "NestedVM Virtual Machine"; break;
892 if(o == null) return -ENOENT;
893 int len = memRead(oldlenaddr);
894 if(o instanceof String) {
895 byte[] b = getNullTerminatedBytes((String)o);
896 if(len < b.length) return -ENOMEM;
899 memWrite(oldlenaddr,len);
900 } else if(o instanceof Integer) {
901 if(len < 4) return -ENOMEM;
902 memWrite(oldp,((Integer)o).intValue());
904 throw new Error("should never happen");
910 /*public int sys_opensocket(int cstring, int port) throws FaultException, ErrnoException {
911 String hostname = cstring(cstring);
913 FD fd = new SocketFD(new Socket(hostname,port));
915 if(n == -1) fd.close();
917 } catch(IOException e) {
922 private static class ListenSocketFD extends FD {
924 public ListenSocketFD(ServerSocket s) { this.s = s; }
925 public int flags() { return 0; }
926 // FEATURE: What should these be?
927 public FStat _fstat() { return new FStat(); }
928 public void _close() { try { s.close(); } catch(IOException e) { } }
931 public int sys_listensocket(int port) {
933 ListenSocketFD fd = new ListenSocketFD(new ServerSocket(port));
935 if(n == -1) fd.close();
937 } catch(IOException e) {
942 public int sys_accept(int fdn) {
943 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
944 if(fds[fdn] == null) return -EBADFD;
945 if(!(fds[fdn] instanceof ListenSocketFD)) return -EBADFD;
947 ServerSocket s = ((ListenSocketFD)fds[fdn]).s;
948 SocketFD fd = new SocketFD(s.accept());
950 if(n == -1) fd.close();
952 } catch(IOException e) {
957 // FEATURE: Run through the fork/wait stuff one more time
958 public static class GlobalState {
959 protected static final int OPEN = 1;
960 protected static final int STAT = 2;
961 protected static final int LSTAT = 3;
962 protected static final int MKDIR = 4;
963 protected static final int UNLINK = 5;
965 final UnixRuntime[] tasks;
968 private MP[] mps = new MP[0];
971 public GlobalState() { this(255); }
972 public GlobalState(int maxProcs) { this(maxProcs,true); }
973 public GlobalState(int maxProcs, boolean defaultMounts) {
974 tasks = new UnixRuntime[maxProcs+1];
976 addMount("/",new HostFS());
977 addMount("/dev",new DevFS());
981 private static class MP implements Comparable {
982 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
985 public int compareTo(Object o) {
986 if(!(o instanceof MP)) return 1;
987 return -path.compareTo(((MP)o).path);
991 public synchronized FS getMount(String path) {
992 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
993 if(path.equals("/")) return root;
994 path = path.substring(1);
995 for(int i=0;i<mps.length;i++)
996 if(mps[i].path.equals(path)) return mps[i].fs;
1000 public synchronized void addMount(String path, FS fs) {
1001 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
1002 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1004 if(fs.owner != null) fs.owner.removeMount(fs);
1007 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
1008 path = path.substring(1);
1009 int oldLength = mps.length;
1010 MP[] newMPS = new MP[oldLength + 1];
1011 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
1012 newMPS[oldLength] = new MP(path,fs);
1013 Arrays.sort(newMPS);
1016 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
1017 fs.devno = highdevno + 2;
1020 public synchronized void removeMount(FS fs) {
1021 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
1022 throw new IllegalArgumentException("mount point doesn't exist");
1025 public synchronized void removeMount(String path) {
1026 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1027 if(path.equals("/")) {
1030 path = path.substring(1);
1032 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
1033 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
1038 private void removeMount(int index) {
1039 if(index == -1) { root.owner = null; root = null; return; }
1040 MP[] newMPS = new MP[mps.length - 1];
1041 System.arraycopy(mps,0,newMPS,0,index);
1042 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
1046 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
1047 int pl = normalizedPath.length();
1050 synchronized(this) { list = mps; }
1051 for(int i=0;i<list.length;i++) {
1053 int mpl = mp.path.length();
1054 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
1055 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
1058 return dispatch(root,op,r,normalizedPath,arg1,arg2);
1061 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
1063 case OPEN: return fs.open(r,path,arg1,arg2);
1064 case STAT: return fs.stat(r,path);
1065 case LSTAT: return fs.lstat(r,path);
1066 case MKDIR: fs.mkdir(r,path,arg1); return null;
1067 case UNLINK: fs.unlink(r,path); return null;
1068 default: throw new Error("should never happen");
1072 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
1073 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
1074 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
1075 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
1076 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
1078 private Hashtable execCache = new Hashtable();
1079 private static class CacheEnt {
1080 public final long time;
1081 public final long size;
1082 public final Object o;
1083 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
1086 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
1087 // FIXME: Hideous hack to make a standalone busybox possible
1088 if(path.equals("bin/busybox") && Boolean.valueOf(getSystemProperty("nestedvm.busyboxhack")).booleanValue())
1089 return r.getClass();
1090 FStat fstat = stat(r,path);
1091 if(fstat == null) return null;
1092 long mtime = fstat.mtime();
1093 long size = fstat.size();
1094 CacheEnt ent = (CacheEnt) execCache.get(path);
1096 //System.err.println("Found cached entry for " + path);
1097 if(ent.time == mtime && ent.size == size) return ent.o;
1098 //System.err.println("Cache was out of date");
1099 execCache.remove(path);
1101 FD fd = open(r,path,RD_ONLY,0);
1102 if(fd == null) return null;
1103 Seekable s = fd.seekable();
1105 String[] command = null;
1107 if(s == null) throw new ErrnoException(EACCES);
1108 byte[] buf = new byte[4096];
1111 int n = s.read(buf,0,buf.length);
1112 if(n == -1) throw new ErrnoException(ENOEXEC);
1115 case '\177': // possible ELF
1116 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
1117 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
1121 int n2 = s.read(buf,1,buf.length-1);
1122 if(n2 == -1) throw new ErrnoException(ENOEXEC);
1125 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
1129 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
1131 if(p == buf.length) break OUTER;
1132 n = s.read(buf,p,buf.length-p);
1134 command = new String[2];
1136 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
1139 while(arg < p && buf[arg] == ' ') arg++;
1140 command[0] = new String(buf,2,cmdEnd);
1141 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
1143 command[0] = new String(buf,2,p-2);
1145 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
1148 throw new ErrnoException(ENOEXEC);
1150 } catch(IOException e) {
1152 throw new ErrnoException(EIO);
1155 if(command == null) {
1156 // its an elf binary
1159 Class c = RuntimeCompiler.compile(s);
1160 //System.err.println("Compile succeeded: " + c);
1161 ent = new CacheEnt(mtime,size,c);
1162 } catch(Compiler.Exn e) {
1163 if(STDERR_DIAG) e.printStackTrace();
1164 throw new ErrnoException(ENOEXEC);
1165 } catch(IOException e) {
1166 if(STDERR_DIAG) e.printStackTrace();
1167 throw new ErrnoException(EIO);
1170 ent = new CacheEnt(mtime,size,command);
1175 execCache.put(path,ent);
1180 public abstract static class FS {
1184 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1186 // If this returns null it'll be truned into an ENOENT
1187 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
1188 // If this returns null it'll be turned into an ENOENT
1189 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
1190 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
1191 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
1194 // FEATURE: chroot support in here
1195 private String normalizePath(String path) {
1196 boolean absolute = path.startsWith("/");
1197 int cwdl = cwd.length();
1198 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
1199 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
1200 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
1202 char[] in = new char[path.length()+1];
1203 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
1207 do { inp++; } while(in[inp] == '/');
1208 } else if(cwdl != 0) {
1209 cwd.getChars(0,cwdl,out,0);
1213 path.getChars(0,path.length(),in,0);
1214 while(in[inp] != 0) {
1215 if(inp != 0 || cwdl==0) {
1216 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
1217 while(in[inp] == '/') inp++;
1219 if(in[inp] == '\0') continue;
1220 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
1221 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
1222 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
1224 if(outp > 0) outp--;
1225 while(outp > 0 && out[outp] != '/') outp--;
1226 //System.err.println("After ..: " + new String(out,0,outp));
1233 if(outp > 0 && out[outp-1] == '/') outp--;
1234 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
1235 return new String(out,0,outp);
1238 FStat hostFStat(final File f, Object data) {
1241 FileInputStream fis = new FileInputStream(f);
1242 switch(fis.read()) {
1243 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
1244 case '#': e = fis.read() == '!';
1247 } catch(IOException e2) { }
1248 HostFS fs = (HostFS) data;
1249 final int inode = fs.inodes.get(f.getAbsolutePath());
1250 final int devno = fs.devno;
1251 return new HostFStat(f,e) {
1252 public int inode() { return inode; }
1253 public int dev() { return devno; }
1257 FD hostFSDirFD(File f, Object _fs) {
1258 HostFS fs = (HostFS) _fs;
1259 return fs.new HostDirFD(f);
1262 public static class HostFS extends FS {
1263 InodeCache inodes = new InodeCache(4000);
1264 protected File root;
1265 public File getRoot() { return root; }
1267 private static File hostRootDir() {
1268 if(getSystemProperty("nestedvm.root") != null) {
1269 File f = new File(getSystemProperty("nestedvm.root"));
1270 if(f.isDirectory()) return f;
1271 // fall through to case below
1273 String cwd = getSystemProperty("user.dir");
1274 File f = new File(cwd != null ? cwd : ".");
1275 if(!f.exists()) throw new Error("Couldn't get File for cwd");
1276 f = new File(f.getAbsolutePath());
1277 while(f.getParent() != null) f = new File(f.getParent());
1281 private File hostFile(String path) {
1282 char sep = File.separatorChar;
1284 char buf[] = path.toCharArray();
1285 for(int i=0;i<buf.length;i++) {
1287 if(c == '/') buf[i] = sep;
1288 else if(c == sep) buf[i] = '/';
1290 path = new String(buf);
1292 return new File(root,path);
1295 public HostFS() { this(hostRootDir()); }
1296 public HostFS(String root) { this(new File(root)); }
1297 public HostFS(File root) { this.root = root; }
1300 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1301 // FIXME: horrendous, ugly hack needed by TeX... sorry Brian...
1303 final File f = hostFile(path);
1304 return r.hostFSOpen(f,flags,mode,this);
1307 public void unlink(UnixRuntime r, String path) throws ErrnoException {
1308 File f = hostFile(path);
1309 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1310 if(!f.exists()) throw new ErrnoException(ENOENT);
1311 if(!f.delete()) throw new ErrnoException(EPERM);
1314 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1315 File f = hostFile(path);
1316 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1317 if(!f.exists()) return null;
1318 return r.hostFStat(f,this);
1321 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1322 File f = hostFile(path);
1323 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1324 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1325 if(f.exists()) throw new ErrnoException(ENOTDIR);
1326 File parent = f.getParentFile();
1327 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1328 if(!f.mkdir()) throw new ErrnoException(EIO);
1331 public class HostDirFD extends DirFD {
1332 private final File f;
1333 private final File[] children;
1334 public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
1335 public int size() { return children.length; }
1336 public String name(int n) { return children[n].getName(); }
1337 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1338 public int parentInode() {
1339 File parent = f.getParentFile();
1340 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
1342 public int myInode() { return inodes.get(f.getAbsolutePath()); }
1343 public int myDev() { return devno; }
1347 private static void putInt(byte[] buf, int off, int n) {
1348 buf[off+0] = (byte)((n>>>24)&0xff);
1349 buf[off+1] = (byte)((n>>>16)&0xff);
1350 buf[off+2] = (byte)((n>>> 8)&0xff);
1351 buf[off+3] = (byte)((n>>> 0)&0xff);
1354 public static abstract class DirFD extends FD {
1355 private int pos = -2;
1357 protected abstract int size();
1358 protected abstract String name(int n);
1359 protected abstract int inode(int n);
1360 protected abstract int myDev();
1361 protected int parentInode() { return -1; }
1362 protected int myInode() { return -1; }
1364 public int getdents(byte[] buf, int off, int len) {
1368 OUTER: for(;len > 0 && pos < size();pos++){
1372 ino = pos == -1 ? parentInode() : myInode();
1373 if(ino == -1) continue;
1374 reclen = 9 + (pos == -1 ? 2 : 1);
1375 if(reclen > len) break OUTER;
1377 if(pos == -1) buf[off+9] = '.';
1380 String f = name(pos);
1381 byte[] fb = getBytes(f);
1382 reclen = fb.length + 9;
1383 if(reclen > len) break OUTER;
1385 System.arraycopy(fb,0,buf,off+8,fb.length);
1388 buf[off+reclen-1] = 0; // null terminate
1389 reclen = (reclen + 3) & ~3; // add padding
1390 putInt(buf,off,reclen);
1391 putInt(buf,off+4,ino);
1398 protected FStat _fstat() {
1399 return new FStat() {
1400 public int type() { return S_IFDIR; }
1401 public int inode() { return myInode(); }
1402 public int dev() { return myDev(); }
1407 public static class DevFS extends FS {
1408 private static final int ROOT_INODE = 1;
1409 private static final int NULL_INODE = 2;
1410 private static final int ZERO_INODE = 3;
1411 private static final int FD_INODE = 4;
1412 private static final int FD_INODES = 32;
1414 private class DevFStat extends FStat {
1415 public int dev() { return devno; }
1416 public int mode() { return 0666; }
1417 public int type() { return S_IFCHR; }
1418 public int nlink() { return 1; }
1421 private abstract class DevDirFD extends DirFD {
1422 public int myDev() { return devno; }
1425 private FD devZeroFD = new FD() {
1426 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
1427 public int write(byte[] a, int off, int length) { return length; }
1428 public int seek(int n, int whence) { return 0; }
1429 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1431 private FD devNullFD = new FD() {
1432 public int read(byte[] a, int off, int length) { return 0; }
1433 public int write(byte[] a, int off, int length) { return length; }
1434 public int seek(int n, int whence) { return 0; }
1435 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1438 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1439 if(path.equals("null")) return devNullFD;
1440 if(path.equals("zero")) return devZeroFD;
1441 if(path.startsWith("fd/")) {
1444 n = Integer.parseInt(path.substring(4));
1445 } catch(NumberFormatException e) {
1448 if(n < 0 || n >= OPEN_MAX) return null;
1449 if(r.fds[n] == null) return null;
1450 return r.fds[n].dup();
1452 if(path.equals("fd")) {
1454 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1455 final int[] files = new int[count];
1457 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1458 return new DevDirFD() {
1459 public int myInode() { return FD_INODE; }
1460 public int parentInode() { return ROOT_INODE; }
1461 public int inode(int n) { return FD_INODES + n; }
1462 public String name(int n) { return Integer.toString(files[n]); }
1463 public int size() { return files.length; }
1466 if(path.equals("")) {
1467 return new DevDirFD() {
1468 public int myInode() { return ROOT_INODE; }
1469 // FEATURE: Get the real parent inode somehow
1470 public int parentInode() { return -1; }
1471 public int inode(int n) {
1473 case 0: return NULL_INODE;
1474 case 1: return ZERO_INODE;
1475 case 2: return FD_INODE;
1480 public String name(int n) {
1482 case 0: return "null";
1483 case 1: return "zero";
1484 case 2: return "fd";
1485 default: return null;
1488 public int size() { return 3; }
1494 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1495 if(path.equals("null")) return devNullFD.fstat();
1496 if(path.equals("zero")) return devZeroFD.fstat();
1497 if(path.startsWith("fd/")) {
1500 n = Integer.parseInt(path.substring(4));
1501 } catch(NumberFormatException e) {
1504 if(n < 0 || n >= OPEN_MAX) return null;
1505 if(r.fds[n] == null) return null;
1506 return r.fds[n].fstat();
1508 // FEATURE: inode stuff
1509 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1510 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1514 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1515 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }