1 package org.ibex.nestedvm;
3 import org.ibex.nestedvm.util.*;
6 import java.net.Socket;
7 import java.net.ServerSocket;
11 public abstract class UnixRuntime extends Runtime implements Cloneable {
12 /** The pid of this "process" */
14 private UnixRuntime parent;
15 public final int getPid() { return pid; }
17 private static final GlobalState defaultGS = new GlobalState();
18 private GlobalState gs = defaultGS;
19 public void setGlobalState(GlobalState gs) {
20 if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running");
24 /** proceses' current working directory - absolute path WITHOUT leading slash
25 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
28 /** The runtime that should be run next when in state == EXECED */
29 private UnixRuntime execedRuntime;
31 private Object children; // used only for synchronizatin
32 private Vector activeChildren;
33 private Vector exitedChildren;
35 protected UnixRuntime(int pageSize, int totalPages) {
36 super(pageSize,totalPages);
38 // FEATURE: Do the proper mangling for non-unix hosts
39 String userdir = getSystemProperty("user.dir");
41 userdir != null && userdir.startsWith("/") && File.separatorChar == '/' && getSystemProperty("nestedvm.root") == null
42 ? userdir.substring(1) : "";
45 // NOTE: getDisplayName() is a Java2 function
46 private static String posixTZ() {
47 StringBuffer sb = new StringBuffer();
48 TimeZone zone = TimeZone.getDefault();
49 int off = zone.getRawOffset() / 1000;
50 sb.append(zone.getDisplayName(false,TimeZone.SHORT));
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(zone.getDisplayName(true,TimeZone.SHORT));
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.set(i,this);
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) 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_opensocket: return sys_opensocket(a,b);
130 case SYS_listensocket: return sys_listensocket(a);
131 case SYS_accept: return sys_accept(a);
133 default: return super._syscall(syscall,a,b,c,d);
137 FD _open(String path, int flags, int mode) throws ErrnoException {
138 return gs.open(this,normalizePath(path),flags,mode);
141 private int sys_getppid() {
142 return parent == null ? 1 : parent.pid;
145 /** The kill syscall.
146 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
147 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
148 Anything else terminates the process. */
149 private int sys_kill(int pid, int signal) {
150 // This will only be called by raise() in newlib to invoke the default handler
151 // We don't have to worry about actually delivering the signal
152 if(pid != pid) return -ESRCH;
153 if(signal < 0 || signal >= 32) return -EINVAL;
168 return syscall(SYS_exit,128+signal,0,0,0);
173 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
174 final int WNOHANG = 1;
175 if((options & ~(WNOHANG)) != 0) return -EINVAL;
176 if(pid == 0 || pid < -1) {
177 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
180 boolean blocking = (options&WNOHANG)==0;
182 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
183 if(children == null) return blocking ? -ECHILD : 0;
185 UnixRuntime done = null;
187 synchronized(children) {
190 if(exitedChildren.size() > 0) done = (UnixRuntime)exitedChildren.remove(exitedChildren.size() - 1);
192 UnixRuntime t = gs.tasks[pid];
193 if(t.parent != this) return -ECHILD;
194 if(t.state == EXITED) {
195 if(!exitedChildren.remove(t)) throw new Error("should never happen");
199 // process group stuff, EINVAL returned above
200 throw new Error("should never happen");
203 if(!blocking) return 0;
204 try { children.wait(); } catch(InterruptedException e) {}
205 //System.err.println("waitpid woke up: " + exitedChildren.size());
207 gs.tasks[done.pid] = null;
212 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
218 if(children != null) synchronized(children) {
219 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
220 UnixRuntime child = (UnixRuntime) e.nextElement();
221 gs.tasks[child.pid] = null;
223 exitedChildren.clear();
224 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
225 UnixRuntime child = (UnixRuntime) e.nextElement();
228 activeChildren.clear();
231 UnixRuntime _parent = parent;
232 if(_parent == null) {
233 gs.tasks[pid] = null;
235 synchronized(_parent.children) {
237 gs.tasks[pid] = null;
239 if(!parent.activeChildren.remove(this)) throw new Error("should never happen _exited: pid: " + pid);
240 parent.exitedChildren.add(this);
241 parent.children.notify();
247 protected Object clone() throws CloneNotSupportedException {
248 UnixRuntime r = (UnixRuntime) super.clone();
252 r.activeChildren = r.exitedChildren = null;
256 private int sys_fork() {
257 CPUState state = new CPUState();
259 int sp = state.r[SP];
263 r = (UnixRuntime) clone();
264 } catch(Exception e) {
273 } catch(ProcessTableFullExn e) {
277 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
278 if(children == null) {
279 children = new Object();
280 activeChildren = new Vector();
281 exitedChildren = new Vector();
283 activeChildren.add(r);
285 state.r[V0] = 0; // return 0 to child
286 state.pc += 4; // skip over syscall instruction
287 r.setCPUState(state);
290 new ForkedProcess(r);
295 public static final class ForkedProcess extends Thread {
296 private final UnixRuntime initial;
297 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
298 public void run() { UnixRuntime.executeAndExec(initial); }
301 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
302 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
304 public static int executeAndExec(UnixRuntime r) {
307 if(r.execute()) break;
308 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
310 if(r.state != EXECED) return r.exitStatus();
315 private String[] readStringArray(int addr) throws ReadFaultException {
317 for(int p=addr;memRead(p) != 0;p+=4) count++;
318 String[] a = new String[count];
319 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
323 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
324 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
327 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
328 if(argv.length == 0) argv = new String[]{""};
330 // NOTE: For this little hack to work nestedvm.root MUST be "."
332 System.err.println("Execing normalized path: " + normalizedPath);
333 if(true) return exec(new Interpreter(normalizedPath),argv,envp);
334 } catch(IOException e) { throw new Error(e); }*/
336 Object o = gs.exec(this,normalizedPath);
337 if(o == null) return -ENOENT;
339 if(o instanceof Class) {
342 return exec((UnixRuntime) c.newInstance(),argv,envp);
343 } catch(Exception e) {
348 String[] command = (String[]) o;
349 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
350 int p = command[0].lastIndexOf('/');
351 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
353 if(command[1] != null) newArgv[p++] = command[1];
354 newArgv[p++] = "/" + normalizedPath;
355 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
356 return exec(command[0],newArgv,envp);
360 private int exec(UnixRuntime r, String[] argv, String[] envp) {
362 //System.err.println("Execing " + r);
363 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
365 r.closeOnExec = closeOnExec;
366 // make sure this doesn't get messed with these since we didn't copy them
383 // FEATURE: Make sure fstat info is correct
384 // FEATURE: This could be faster if we did direct copies from each process' memory
385 // FEATURE: Check this logic one more time
386 public static class Pipe {
387 private final byte[] pipebuf = new byte[PIPE_BUF*4];
389 private int writePos;
391 public final FD reader = new Reader();
392 public final FD writer = new Writer();
394 public class Reader extends FD {
395 protected FStat _fstat() { return new FStat(); }
396 public int read(byte[] buf, int off, int len) throws ErrnoException {
397 if(len == 0) return 0;
398 synchronized(Pipe.this) {
399 while(writePos != -1 && readPos == writePos) {
400 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
402 if(writePos == -1) return 0; // eof
403 len = Math.min(len,writePos-readPos);
404 System.arraycopy(pipebuf,readPos,buf,off,len);
406 if(readPos == writePos) Pipe.this.notify();
410 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
413 public class Writer extends FD {
414 protected FStat _fstat() { return new FStat(); }
415 public int write(byte[] buf, int off, int len) throws ErrnoException {
416 if(len == 0) return 0;
417 synchronized(Pipe.this) {
418 if(readPos == -1) throw new ErrnoException(EPIPE);
419 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
420 // not enough space to atomicly write the data
421 while(readPos != -1 && readPos != writePos) {
422 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
424 if(readPos == -1) throw new ErrnoException(EPIPE);
425 readPos = writePos = 0;
427 len = Math.min(len,pipebuf.length - writePos);
428 System.arraycopy(buf,off,pipebuf,writePos,len);
429 if(readPos == writePos) Pipe.this.notify();
434 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
438 private int sys_pipe(int addr) {
439 Pipe pipe = new Pipe();
441 int fd1 = addFD(pipe.reader);
442 if(fd1 < 0) return -ENFILE;
443 int fd2 = addFD(pipe.writer);
444 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
448 memWrite(addr+4,fd2);
449 } catch(FaultException e) {
457 private int sys_dup2(int oldd, int newd) {
458 if(oldd == newd) return 0;
459 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
460 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
461 if(fds[oldd] == null) return -EBADFD;
462 if(fds[newd] != null) fds[newd].close();
463 fds[newd] = fds[oldd].dup();
467 private int sys_dup(int oldd) {
468 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
469 if(fds[oldd] == null) return -EBADFD;
470 FD fd = fds[oldd].dup();
471 int newd = addFD(fd);
472 if(newd < 0) { fd.close(); return -ENFILE; }
476 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
477 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
478 if(s == null) return -ENOENT;
482 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
483 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
484 if(s == null) return -ENOENT;
488 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
489 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
493 private int sys_unlink(int cstring) throws FaultException, ErrnoException {
494 gs.unlink(this,normalizePath(cstring(cstring)));
498 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
499 byte[] b = getBytes(cwd);
500 if(size == 0) return -EINVAL;
501 if(size < b.length+2) return -ERANGE;
503 copyout(b,addr+1,b.length);
504 memset(addr+b.length+1,0,1);
508 private int sys_chdir(int addr) throws ErrnoException, FaultException {
509 String path = normalizePath(cstring(addr));
510 //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
511 if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
513 //System.err.println("Now: [" + cwd + "]");
517 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
518 count = Math.min(count,MAX_CHUNK);
519 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
520 if(fds[fdn] == null) return -EBADFD;
521 byte[] buf = byteBuf(count);
522 int n = fds[fdn].getdents(buf,0,count);
527 private static class SocketFD extends InputOutputStreamFD {
528 private final Socket s;
530 public SocketFD(Socket s) throws IOException {
531 super(s.getInputStream(),s.getOutputStream());
535 public void _close() { try { s.close(); } catch(IOException e) { } }
538 public int sys_opensocket(int cstring, int port) throws FaultException, ErrnoException {
539 String hostname = cstring(cstring);
541 FD fd = new SocketFD(new Socket(hostname,port));
543 if(n == -1) fd.close();
545 } catch(IOException e) {
550 private static class ListenSocketFD extends FD {
552 public ListenSocketFD(ServerSocket s) { this.s = s; }
553 public int flags() { return 0; }
554 // FEATURE: What should these be?
555 public FStat _fstat() { return new FStat(); }
556 public void _close() { try { s.close(); } catch(IOException e) { } }
559 public int sys_listensocket(int port) {
561 ListenSocketFD fd = new ListenSocketFD(new ServerSocket(port));
563 if(n == -1) fd.close();
565 } catch(IOException e) {
570 public int sys_accept(int fdn) {
571 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
572 if(fds[fdn] == null) return -EBADFD;
573 if(!(fds[fdn] instanceof ListenSocketFD)) return -EBADFD;
575 ServerSocket s = ((ListenSocketFD)fds[fdn]).s;
576 SocketFD fd = new SocketFD(s.accept());
578 if(n == -1) fd.close();
580 } catch(IOException e) {
585 // FEATURE: Run through the fork/wait stuff one more time
586 public static class GlobalState {
587 protected static final int OPEN = 1;
588 protected static final int STAT = 2;
589 protected static final int LSTAT = 3;
590 protected static final int MKDIR = 4;
591 protected static final int UNLINK = 5;
593 final UnixRuntime[] tasks;
596 private MP[] mps = new MP[0];
599 public GlobalState() { this(255); }
600 public GlobalState(int maxProcs) { this(maxProcs,true); }
601 public GlobalState(int maxProcs, boolean defaultMounts) {
602 tasks = new UnixRuntime[maxProcs+1];
604 addMount("/",new HostFS());
605 addMount("/dev",new DevFS());
609 private static class MP implements Comparable {
610 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
613 public int compareTo(Object o) {
614 if(!(o instanceof MP)) return 1;
615 return -path.compareTo(((MP)o).path);
619 public synchronized FS getMount(String path) {
620 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
621 if(path.equals("/")) return root;
622 path = path.substring(1);
623 for(int i=0;i<mps.length;i++)
624 if(mps[i].path.equals(path)) return mps[i].fs;
628 public synchronized void addMount(String path, FS fs) {
629 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
630 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
632 if(fs.owner != null) fs.owner.removeMount(fs);
635 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
636 path = path.substring(1);
637 int oldLength = mps.length;
638 MP[] newMPS = new MP[oldLength + 1];
639 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
640 newMPS[oldLength] = new MP(path,fs);
644 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
645 fs.devno = highdevno + 2;
648 public synchronized void removeMount(FS fs) {
649 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
650 throw new IllegalArgumentException("mount point doesn't exist");
653 public synchronized void removeMount(String path) {
654 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
655 if(path.equals("/")) {
658 path = path.substring(1);
660 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
661 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
666 private void removeMount(int index) {
667 if(index == -1) { root.owner = null; root = null; return; }
668 MP[] newMPS = new MP[mps.length - 1];
669 System.arraycopy(mps,0,newMPS,0,index);
670 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
674 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
675 int pl = normalizedPath.length();
678 synchronized(this) { list = mps; }
679 for(int i=0;i<list.length;i++) {
681 int mpl = mp.path.length();
682 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
683 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
686 return dispatch(root,op,r,normalizedPath,arg1,arg2);
689 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
691 case OPEN: return fs.open(r,path,arg1,arg2);
692 case STAT: return fs.stat(r,path);
693 case LSTAT: return fs.lstat(r,path);
694 case MKDIR: fs.mkdir(r,path,arg1); return null;
695 case UNLINK: fs.unlink(r,path); return null;
696 default: throw new Error("should never happen");
700 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
701 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
702 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
703 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
704 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
706 private Hashtable execCache = new Hashtable();
707 private static class CacheEnt {
708 public final long time;
709 public final long size;
710 public final Object o;
711 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
714 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
715 // FIXME: Hideous hack to make a standalone busybox possible
716 if(path.equals("bin/busybox") && Boolean.valueOf(getSystemProperty("nestedvm.busyboxhack")).booleanValue())
718 FStat fstat = stat(r,path);
719 if(fstat == null) return null;
720 long mtime = fstat.mtime();
721 long size = fstat.size();
722 CacheEnt ent = (CacheEnt) execCache.get(path);
724 //System.err.println("Found cached entry for " + path);
725 if(ent.time == mtime && ent.size == size) return ent.o;
726 //System.err.println("Cache was out of date");
727 execCache.remove(path);
729 FD fd = open(r,path,RD_ONLY,0);
730 if(fd == null) return null;
731 Seekable s = fd.seekable();
733 String[] command = null;
735 if(s == null) throw new ErrnoException(EACCES);
736 byte[] buf = new byte[4096];
739 int n = s.read(buf,0,buf.length);
740 if(n == -1) throw new ErrnoException(ENOEXEC);
743 case '\177': // possible ELF
744 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
745 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
749 int n2 = s.read(buf,1,buf.length-1);
750 if(n2 == -1) throw new ErrnoException(ENOEXEC);
753 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
757 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
759 if(p == buf.length) break OUTER;
760 n = s.read(buf,p,buf.length-p);
762 command = new String[2];
764 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
767 while(arg < p && buf[arg] == ' ') arg++;
768 command[0] = new String(buf,2,cmdEnd);
769 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
771 command[0] = new String(buf,2,p-2);
773 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
776 throw new ErrnoException(ENOEXEC);
778 } catch(IOException e) {
780 throw new ErrnoException(EIO);
783 if(command == null) {
787 Class c = RuntimeCompiler.compile(s);
788 //System.err.println("Compile succeeded: " + c);
789 ent = new CacheEnt(mtime,size,c);
790 } catch(Compiler.Exn e) {
791 if(STDERR_DIAG) e.printStackTrace();
792 throw new ErrnoException(ENOEXEC);
793 } catch(IOException e) {
794 if(STDERR_DIAG) e.printStackTrace();
795 throw new ErrnoException(EIO);
798 ent = new CacheEnt(mtime,size,command);
803 execCache.put(path,ent);
808 public abstract static class FS {
812 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
814 // If this returns null it'll be truned into an ENOENT
815 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
816 // If this returns null it'll be turned into an ENOENT
817 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
818 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
819 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
822 // FEATURE: chroot support in here
823 private String normalizePath(String path) {
824 boolean absolute = path.startsWith("/");
825 int cwdl = cwd.length();
826 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
827 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
828 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
830 char[] in = new char[path.length()+1];
831 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
835 do { inp++; } while(in[inp] == '/');
836 } else if(cwdl != 0) {
837 cwd.getChars(0,cwdl,out,0);
841 path.getChars(0,path.length(),in,0);
842 while(in[inp] != 0) {
843 if(inp != 0 || cwdl==0) {
844 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
845 while(in[inp] == '/') inp++;
847 if(in[inp] == '\0') continue;
848 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
849 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
850 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
853 while(outp > 0 && out[outp] != '/') outp--;
854 //System.err.println("After ..: " + new String(out,0,outp));
861 if(outp > 0 && out[outp-1] == '/') outp--;
862 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
863 return new String(out,0,outp);
866 FStat hostFStat(final File f, Object data) {
869 FileInputStream fis = new FileInputStream(f);
871 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
872 case '#': e = fis.read() == '!';
875 } catch(IOException e2) { }
876 HostFS fs = (HostFS) data;
877 final int inode = fs.inodes.get(f.getAbsolutePath());
878 final int devno = fs.devno;
879 return new HostFStat(f,e) {
880 public int inode() { return inode; }
881 public int dev() { return devno; }
885 FD hostFSDirFD(File f, Object _fs) {
886 HostFS fs = (HostFS) _fs;
887 return fs.new HostDirFD(f);
890 public static class HostFS extends FS {
891 InodeCache inodes = new InodeCache(4000);
893 public File getRoot() { return root; }
895 private static File hostRootDir() {
896 if(getSystemProperty("nestedvm.root") != null) {
897 File f = new File(getSystemProperty("nestedvm.root"));
898 if(f.isDirectory()) return f;
899 // fall through to case below
901 String cwd = getSystemProperty("user.dir");
902 File f = new File(cwd != null ? cwd : ".");
903 if(!f.exists()) throw new Error("Couldn't get File for cwd");
904 f = new File(f.getAbsolutePath());
905 while(f.getParent() != null) f = new File(f.getParent());
909 private File hostFile(String path) {
910 char sep = File.separatorChar;
912 char buf[] = path.toCharArray();
913 for(int i=0;i<buf.length;i++) {
915 if(c == '/') buf[i] = sep;
916 else if(c == sep) buf[i] = '/';
918 path = new String(buf);
920 return new File(root,path);
923 public HostFS() { this(hostRootDir()); }
924 public HostFS(String root) { this(new File(root)); }
925 public HostFS(File root) { this.root = root; }
928 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
929 final File f = hostFile(path);
930 return r.hostFSOpen(f,flags,mode,this);
933 public void unlink(UnixRuntime r, String path) throws ErrnoException {
934 File f = hostFile(path);
935 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
936 if(!f.exists()) throw new ErrnoException(ENOENT);
937 if(!f.delete()) throw new ErrnoException(EPERM);
940 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
941 File f = hostFile(path);
942 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
943 if(!f.exists()) return null;
944 return r.hostFStat(f,this);
947 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
948 File f = hostFile(path);
949 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
950 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
951 if(f.exists()) throw new ErrnoException(ENOTDIR);
952 File parent = f.getParentFile();
953 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
954 if(!f.mkdir()) throw new ErrnoException(EIO);
957 public class HostDirFD extends DirFD {
958 private final File f;
959 private final File[] children;
960 public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
961 public int size() { return children.length; }
962 public String name(int n) { return children[n].getName(); }
963 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
964 public int parentInode() {
965 File parent = f.getParentFile();
966 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
968 public int myInode() { return inodes.get(f.getAbsolutePath()); }
969 public int myDev() { return devno; }
973 private static void putInt(byte[] buf, int off, int n) {
974 buf[off+0] = (byte)((n>>>24)&0xff);
975 buf[off+1] = (byte)((n>>>16)&0xff);
976 buf[off+2] = (byte)((n>>> 8)&0xff);
977 buf[off+3] = (byte)((n>>> 0)&0xff);
980 public static abstract class DirFD extends FD {
981 private int pos = -2;
983 protected abstract int size();
984 protected abstract String name(int n);
985 protected abstract int inode(int n);
986 protected abstract int myDev();
987 protected int parentInode() { return -1; }
988 protected int myInode() { return -1; }
990 public int getdents(byte[] buf, int off, int len) {
994 OUTER: for(;len > 0 && pos < size();pos++){
998 ino = pos == -1 ? parentInode() : myInode();
999 if(ino == -1) continue;
1000 reclen = 9 + (pos == -1 ? 2 : 1);
1001 if(reclen > len) break OUTER;
1003 if(pos == -1) buf[off+9] = '.';
1006 String f = name(pos);
1007 byte[] fb = getBytes(f);
1008 reclen = fb.length + 9;
1009 if(reclen > len) break OUTER;
1011 System.arraycopy(fb,0,buf,off+8,fb.length);
1014 buf[off+reclen-1] = 0; // null terminate
1015 reclen = (reclen + 3) & ~3; // add padding
1016 putInt(buf,off,reclen);
1017 putInt(buf,off+4,ino);
1024 protected FStat _fstat() {
1025 return new FStat() {
1026 public int type() { return S_IFDIR; }
1027 public int inode() { return myInode(); }
1028 public int dev() { return myDev(); }
1033 public static class DevFS extends FS {
1034 private static final int ROOT_INODE = 1;
1035 private static final int NULL_INODE = 2;
1036 private static final int ZERO_INODE = 3;
1037 private static final int FD_INODE = 4;
1038 private static final int FD_INODES = 32;
1040 private class DevFStat extends FStat {
1041 public int dev() { return devno; }
1042 public int mode() { return 0666; }
1043 public int type() { return S_IFCHR; }
1044 public int nlink() { return 1; }
1047 private abstract class DevDirFD extends DirFD {
1048 public int myDev() { return devno; }
1051 private FD devZeroFD = new FD() {
1052 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
1053 public int write(byte[] a, int off, int length) { return length; }
1054 public int seek(int n, int whence) { return 0; }
1055 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1057 private FD devNullFD = new FD() {
1058 public int read(byte[] a, int off, int length) { return 0; }
1059 public int write(byte[] a, int off, int length) { return length; }
1060 public int seek(int n, int whence) { return 0; }
1061 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1064 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1065 if(path.equals("null")) return devNullFD;
1066 if(path.equals("zero")) return devZeroFD;
1067 if(path.startsWith("fd/")) {
1070 n = Integer.parseInt(path.substring(4));
1071 } catch(NumberFormatException e) {
1074 if(n < 0 || n >= OPEN_MAX) return null;
1075 if(r.fds[n] == null) return null;
1076 return r.fds[n].dup();
1078 if(path.equals("fd")) {
1080 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1081 final int[] files = new int[count];
1083 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1084 return new DevDirFD() {
1085 public int myInode() { return FD_INODE; }
1086 public int parentInode() { return ROOT_INODE; }
1087 public int inode(int n) { return FD_INODES + n; }
1088 public String name(int n) { return Integer.toString(files[n]); }
1089 public int size() { return files.length; }
1092 if(path.equals("")) {
1093 return new DevDirFD() {
1094 public int myInode() { return ROOT_INODE; }
1095 // FEATURE: Get the real parent inode somehow
1096 public int parentInode() { return -1; }
1097 public int inode(int n) {
1099 case 0: return NULL_INODE;
1100 case 1: return ZERO_INODE;
1101 case 2: return FD_INODE;
1106 public String name(int n) {
1108 case 0: return "null";
1109 case 1: return "zero";
1110 case 2: return "fd";
1111 default: return null;
1114 public int size() { return 3; }
1120 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1121 if(path.equals("null")) return devNullFD.fstat();
1122 if(path.equals("zero")) return devZeroFD.fstat();
1123 if(path.startsWith("fd/")) {
1126 n = Integer.parseInt(path.substring(4));
1127 } catch(NumberFormatException e) {
1130 if(n < 0 || n >= OPEN_MAX) return null;
1131 if(r.fds[n] == null) return null;
1132 return r.fds[n].fstat();
1134 // FEATURE: inode stuff
1135 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1136 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1140 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1141 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }