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 //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
518 if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
520 //System.err.println("Now: [" + cwd + "]");
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 public int sys_opensocket(int cstring, int port) throws FaultException, ErrnoException {
632 String hostname = cstring(cstring);
634 FD fd = new SocketFD(new Socket(hostname,port));
636 if(n == -1) fd.close();
638 } catch(IOException e) {
643 private static class ListenSocketFD extends FD {
645 public ListenSocketFD(ServerSocket s) { this.s = s; }
646 public int flags() { return 0; }
647 // FEATURE: What should these be?
648 public FStat _fstat() { return new FStat(); }
649 public void _close() { try { s.close(); } catch(IOException e) { } }
652 public int sys_listensocket(int port) {
654 ListenSocketFD fd = new ListenSocketFD(new ServerSocket(port));
656 if(n == -1) fd.close();
658 } catch(IOException e) {
663 public int sys_accept(int fdn) {
664 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
665 if(fds[fdn] == null) return -EBADFD;
666 if(!(fds[fdn] instanceof ListenSocketFD)) return -EBADFD;
668 ServerSocket s = ((ListenSocketFD)fds[fdn]).s;
669 SocketFD fd = new SocketFD(s.accept());
671 if(n == -1) fd.close();
673 } catch(IOException e) {
678 // FEATURE: Run through the fork/wait stuff one more time
679 public static class GlobalState {
680 protected static final int OPEN = 1;
681 protected static final int STAT = 2;
682 protected static final int LSTAT = 3;
683 protected static final int MKDIR = 4;
684 protected static final int UNLINK = 5;
686 final UnixRuntime[] tasks;
689 private MP[] mps = new MP[0];
692 public GlobalState() { this(255); }
693 public GlobalState(int maxProcs) { this(maxProcs,true); }
694 public GlobalState(int maxProcs, boolean defaultMounts) {
695 tasks = new UnixRuntime[maxProcs+1];
697 addMount("/",new HostFS());
698 addMount("/dev",new DevFS());
702 private static class MP implements Comparable {
703 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
706 public int compareTo(Object o) {
707 if(!(o instanceof MP)) return 1;
708 return -path.compareTo(((MP)o).path);
712 public synchronized FS getMount(String path) {
713 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
714 if(path.equals("/")) return root;
715 path = path.substring(1);
716 for(int i=0;i<mps.length;i++)
717 if(mps[i].path.equals(path)) return mps[i].fs;
721 public synchronized void addMount(String path, FS fs) {
722 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
723 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
725 if(fs.owner != null) fs.owner.removeMount(fs);
728 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
729 path = path.substring(1);
730 int oldLength = mps.length;
731 MP[] newMPS = new MP[oldLength + 1];
732 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
733 newMPS[oldLength] = new MP(path,fs);
737 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
738 fs.devno = highdevno + 2;
741 public synchronized void removeMount(FS fs) {
742 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
743 throw new IllegalArgumentException("mount point doesn't exist");
746 public synchronized void removeMount(String path) {
747 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
748 if(path.equals("/")) {
751 path = path.substring(1);
753 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
754 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
759 private void removeMount(int index) {
760 if(index == -1) { root.owner = null; root = null; return; }
761 MP[] newMPS = new MP[mps.length - 1];
762 System.arraycopy(mps,0,newMPS,0,index);
763 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
767 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
768 int pl = normalizedPath.length();
771 synchronized(this) { list = mps; }
772 for(int i=0;i<list.length;i++) {
774 int mpl = mp.path.length();
775 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
776 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
779 return dispatch(root,op,r,normalizedPath,arg1,arg2);
782 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
784 case OPEN: return fs.open(r,path,arg1,arg2);
785 case STAT: return fs.stat(r,path);
786 case LSTAT: return fs.lstat(r,path);
787 case MKDIR: fs.mkdir(r,path,arg1); return null;
788 case UNLINK: fs.unlink(r,path); return null;
789 default: throw new Error("should never happen");
793 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
794 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
795 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
796 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
797 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
799 private Hashtable execCache = new Hashtable();
800 private static class CacheEnt {
801 public final long time;
802 public final long size;
803 public final Object o;
804 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
807 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
808 // FIXME: Hideous hack to make a standalone busybox possible
809 if(path.equals("bin/busybox") && Boolean.valueOf(getSystemProperty("nestedvm.busyboxhack")).booleanValue())
811 FStat fstat = stat(r,path);
812 if(fstat == null) return null;
813 long mtime = fstat.mtime();
814 long size = fstat.size();
815 CacheEnt ent = (CacheEnt) execCache.get(path);
817 //System.err.println("Found cached entry for " + path);
818 if(ent.time == mtime && ent.size == size) return ent.o;
819 //System.err.println("Cache was out of date");
820 execCache.remove(path);
822 FD fd = open(r,path,RD_ONLY,0);
823 if(fd == null) return null;
824 Seekable s = fd.seekable();
826 String[] command = null;
828 if(s == null) throw new ErrnoException(EACCES);
829 byte[] buf = new byte[4096];
832 int n = s.read(buf,0,buf.length);
833 if(n == -1) throw new ErrnoException(ENOEXEC);
836 case '\177': // possible ELF
837 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
838 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
842 int n2 = s.read(buf,1,buf.length-1);
843 if(n2 == -1) throw new ErrnoException(ENOEXEC);
846 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
850 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
852 if(p == buf.length) break OUTER;
853 n = s.read(buf,p,buf.length-p);
855 command = new String[2];
857 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
860 while(arg < p && buf[arg] == ' ') arg++;
861 command[0] = new String(buf,2,cmdEnd);
862 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
864 command[0] = new String(buf,2,p-2);
866 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
869 throw new ErrnoException(ENOEXEC);
871 } catch(IOException e) {
873 throw new ErrnoException(EIO);
876 if(command == null) {
880 Class c = RuntimeCompiler.compile(s);
881 //System.err.println("Compile succeeded: " + c);
882 ent = new CacheEnt(mtime,size,c);
883 } catch(Compiler.Exn e) {
884 if(STDERR_DIAG) e.printStackTrace();
885 throw new ErrnoException(ENOEXEC);
886 } catch(IOException e) {
887 if(STDERR_DIAG) e.printStackTrace();
888 throw new ErrnoException(EIO);
891 ent = new CacheEnt(mtime,size,command);
896 execCache.put(path,ent);
901 public abstract static class FS {
905 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
907 // If this returns null it'll be truned into an ENOENT
908 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
909 // If this returns null it'll be turned into an ENOENT
910 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
911 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
912 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
915 // FEATURE: chroot support in here
916 private String normalizePath(String path) {
917 boolean absolute = path.startsWith("/");
918 int cwdl = cwd.length();
919 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
920 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
921 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
923 char[] in = new char[path.length()+1];
924 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
928 do { inp++; } while(in[inp] == '/');
929 } else if(cwdl != 0) {
930 cwd.getChars(0,cwdl,out,0);
934 path.getChars(0,path.length(),in,0);
935 while(in[inp] != 0) {
936 if(inp != 0 || cwdl==0) {
937 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
938 while(in[inp] == '/') inp++;
940 if(in[inp] == '\0') continue;
941 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
942 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
943 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
946 while(outp > 0 && out[outp] != '/') outp--;
947 //System.err.println("After ..: " + new String(out,0,outp));
954 if(outp > 0 && out[outp-1] == '/') outp--;
955 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
956 return new String(out,0,outp);
959 FStat hostFStat(final File f, Object data) {
962 FileInputStream fis = new FileInputStream(f);
964 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
965 case '#': e = fis.read() == '!';
968 } catch(IOException e2) { }
969 HostFS fs = (HostFS) data;
970 final int inode = fs.inodes.get(f.getAbsolutePath());
971 final int devno = fs.devno;
972 return new HostFStat(f,e) {
973 public int inode() { return inode; }
974 public int dev() { return devno; }
978 FD hostFSDirFD(File f, Object _fs) {
979 HostFS fs = (HostFS) _fs;
980 return fs.new HostDirFD(f);
983 public static class HostFS extends FS {
984 InodeCache inodes = new InodeCache(4000);
986 public File getRoot() { return root; }
988 private static File hostRootDir() {
989 if(getSystemProperty("nestedvm.root") != null) {
990 File f = new File(getSystemProperty("nestedvm.root"));
991 if(f.isDirectory()) return f;
992 // fall through to case below
994 String cwd = getSystemProperty("user.dir");
995 File f = new File(cwd != null ? cwd : ".");
996 if(!f.exists()) throw new Error("Couldn't get File for cwd");
997 f = new File(f.getAbsolutePath());
998 while(f.getParent() != null) f = new File(f.getParent());
1002 private File hostFile(String path) {
1003 char sep = File.separatorChar;
1005 char buf[] = path.toCharArray();
1006 for(int i=0;i<buf.length;i++) {
1008 if(c == '/') buf[i] = sep;
1009 else if(c == sep) buf[i] = '/';
1011 path = new String(buf);
1013 return new File(root,path);
1016 public HostFS() { this(hostRootDir()); }
1017 public HostFS(String root) { this(new File(root)); }
1018 public HostFS(File root) { this.root = root; }
1021 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1022 // FIXME: horrendous, ugly hack needed by TeX... sorry Brian...
1024 final File f = hostFile(path);
1025 return r.hostFSOpen(f,flags,mode,this);
1028 public void unlink(UnixRuntime r, String path) throws ErrnoException {
1029 File f = hostFile(path);
1030 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1031 if(!f.exists()) throw new ErrnoException(ENOENT);
1032 if(!f.delete()) throw new ErrnoException(EPERM);
1035 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1036 File f = hostFile(path);
1037 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1038 if(!f.exists()) return null;
1039 return r.hostFStat(f,this);
1042 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1043 File f = hostFile(path);
1044 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1045 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1046 if(f.exists()) throw new ErrnoException(ENOTDIR);
1047 File parent = f.getParentFile();
1048 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1049 if(!f.mkdir()) throw new ErrnoException(EIO);
1052 public class HostDirFD extends DirFD {
1053 private final File f;
1054 private final File[] children;
1055 public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
1056 public int size() { return children.length; }
1057 public String name(int n) { return children[n].getName(); }
1058 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1059 public int parentInode() {
1060 File parent = f.getParentFile();
1061 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
1063 public int myInode() { return inodes.get(f.getAbsolutePath()); }
1064 public int myDev() { return devno; }
1068 private static void putInt(byte[] buf, int off, int n) {
1069 buf[off+0] = (byte)((n>>>24)&0xff);
1070 buf[off+1] = (byte)((n>>>16)&0xff);
1071 buf[off+2] = (byte)((n>>> 8)&0xff);
1072 buf[off+3] = (byte)((n>>> 0)&0xff);
1075 public static abstract class DirFD extends FD {
1076 private int pos = -2;
1078 protected abstract int size();
1079 protected abstract String name(int n);
1080 protected abstract int inode(int n);
1081 protected abstract int myDev();
1082 protected int parentInode() { return -1; }
1083 protected int myInode() { return -1; }
1085 public int getdents(byte[] buf, int off, int len) {
1089 OUTER: for(;len > 0 && pos < size();pos++){
1093 ino = pos == -1 ? parentInode() : myInode();
1094 if(ino == -1) continue;
1095 reclen = 9 + (pos == -1 ? 2 : 1);
1096 if(reclen > len) break OUTER;
1098 if(pos == -1) buf[off+9] = '.';
1101 String f = name(pos);
1102 byte[] fb = getBytes(f);
1103 reclen = fb.length + 9;
1104 if(reclen > len) break OUTER;
1106 System.arraycopy(fb,0,buf,off+8,fb.length);
1109 buf[off+reclen-1] = 0; // null terminate
1110 reclen = (reclen + 3) & ~3; // add padding
1111 putInt(buf,off,reclen);
1112 putInt(buf,off+4,ino);
1119 protected FStat _fstat() {
1120 return new FStat() {
1121 public int type() { return S_IFDIR; }
1122 public int inode() { return myInode(); }
1123 public int dev() { return myDev(); }
1128 public static class DevFS extends FS {
1129 private static final int ROOT_INODE = 1;
1130 private static final int NULL_INODE = 2;
1131 private static final int ZERO_INODE = 3;
1132 private static final int FD_INODE = 4;
1133 private static final int FD_INODES = 32;
1135 private class DevFStat extends FStat {
1136 public int dev() { return devno; }
1137 public int mode() { return 0666; }
1138 public int type() { return S_IFCHR; }
1139 public int nlink() { return 1; }
1142 private abstract class DevDirFD extends DirFD {
1143 public int myDev() { return devno; }
1146 private FD devZeroFD = new FD() {
1147 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
1148 public int write(byte[] a, int off, int length) { return length; }
1149 public int seek(int n, int whence) { return 0; }
1150 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1152 private FD devNullFD = new FD() {
1153 public int read(byte[] a, int off, int length) { return 0; }
1154 public int write(byte[] a, int off, int length) { return length; }
1155 public int seek(int n, int whence) { return 0; }
1156 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1159 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1160 if(path.equals("null")) return devNullFD;
1161 if(path.equals("zero")) return devZeroFD;
1162 if(path.startsWith("fd/")) {
1165 n = Integer.parseInt(path.substring(4));
1166 } catch(NumberFormatException e) {
1169 if(n < 0 || n >= OPEN_MAX) return null;
1170 if(r.fds[n] == null) return null;
1171 return r.fds[n].dup();
1173 if(path.equals("fd")) {
1175 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1176 final int[] files = new int[count];
1178 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1179 return new DevDirFD() {
1180 public int myInode() { return FD_INODE; }
1181 public int parentInode() { return ROOT_INODE; }
1182 public int inode(int n) { return FD_INODES + n; }
1183 public String name(int n) { return Integer.toString(files[n]); }
1184 public int size() { return files.length; }
1187 if(path.equals("")) {
1188 return new DevDirFD() {
1189 public int myInode() { return ROOT_INODE; }
1190 // FEATURE: Get the real parent inode somehow
1191 public int parentInode() { return -1; }
1192 public int inode(int n) {
1194 case 0: return NULL_INODE;
1195 case 1: return ZERO_INODE;
1196 case 2: return FD_INODE;
1201 public String name(int n) {
1203 case 0: return "null";
1204 case 1: return "zero";
1205 case 2: return "fd";
1206 default: return null;
1209 public int size() { return 3; }
1215 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1216 if(path.equals("null")) return devNullFD.fstat();
1217 if(path.equals("zero")) return devZeroFD.fstat();
1218 if(path.startsWith("fd/")) {
1221 n = Integer.parseInt(path.substring(4));
1222 } catch(NumberFormatException e) {
1225 if(n < 0 || n >= OPEN_MAX) return null;
1226 if(r.fds[n] == null) return null;
1227 return r.fds[n].fstat();
1229 // FEATURE: inode stuff
1230 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1231 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1235 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1236 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }