1 package org.ibex.nestedvm;
3 import org.ibex.nestedvm.util.*;
7 public abstract class UnixRuntime extends Runtime implements Cloneable {
8 /** The pid of this "process" */
10 private UnixRuntime parent;
11 public final int getPid() { return pid; }
13 private static final GlobalState defaultGS = new GlobalState();
14 private GlobalState gs = defaultGS;
15 public void setGlobalState(GlobalState gs) {
16 if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running");
20 /** proceses' current working directory - absolute path WITHOUT leading slash
21 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
24 /** The runtime that should be run next when in state == EXECED */
25 private UnixRuntime execedRuntime;
27 private Object children; // used only for synchronizatin
28 private Vector activeChildren;
29 private Vector exitedChildren;
31 protected UnixRuntime(int pageSize, int totalPages) {
32 super(pageSize,totalPages);
34 // FEATURE: Do the proper mangling for non-unix hosts
35 String userdir = getSystemProperty("user.dir");
37 userdir != null && userdir.startsWith("/") && File.separatorChar == '/' && getSystemProperty("nestedvm.root") == null
38 ? userdir.substring(1) : "";
41 // NOTE: getDisplayName() is a Java2 function
42 private static String posixTZ() {
43 StringBuffer sb = new StringBuffer();
44 TimeZone zone = TimeZone.getDefault();
45 int off = zone.getRawOffset() / 1000;
46 sb.append(zone.getDisplayName(false,TimeZone.SHORT));
47 if(off > 0) sb.append("-");
49 sb.append(off/3600); off = off%3600;
50 if(off > 0) sb.append(":").append(off/60); off=off%60;
51 if(off > 0) sb.append(":").append(off);
52 if(zone.useDaylightTime())
53 sb.append(zone.getDisplayName(true,TimeZone.SHORT));
57 private static boolean envHas(String key,String[] environ) {
58 for(int i=0;i<environ.length;i++)
59 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
63 String[] createEnv(String[] extra) {
64 String[] defaults = new String[6];
66 if(extra == null) extra = new String[0];
67 if(!envHas("USER",extra) && getSystemProperty("user.name") != null)
68 defaults[n++] = "USER=" + getSystemProperty("user.name");
69 if(!envHas("HOME",extra) && getSystemProperty("user.home") != null)
70 defaults[n++] = "HOME=" + getSystemProperty("user.home");
71 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
72 if(!envHas("TERM",extra)) defaults[n++] = "TERM=vt100";
73 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
74 if(!envHas("PATH",extra)) defaults[n++] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin";
75 String[] env = new String[extra.length+n];
76 for(int i=0;i<n;i++) env[i] = defaults[i];
77 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
81 private static class ProcessTableFullExn extends RuntimeException { }
84 UnixRuntime[] tasks = gs.tasks;
87 if(tasks[pid] == null || tasks[pid].pid != pid) throw new Error("should never happen");
90 int nextPID = gs.nextPID;
91 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
92 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
93 if(newpid == -1) throw new ProcessTableFullExn();
95 gs.nextPID = newpid + 1;
101 int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
103 case SYS_kill: return sys_kill(a,b);
104 case SYS_fork: return sys_fork();
105 case SYS_pipe: return sys_pipe(a);
106 case SYS_dup2: return sys_dup2(a,b);
107 case SYS_dup: return sys_dup(a);
108 case SYS_waitpid: return sys_waitpid(a,b,c);
109 case SYS_stat: return sys_stat(a,b);
110 case SYS_lstat: return sys_lstat(a,b);
111 case SYS_mkdir: return sys_mkdir(a,b);
112 case SYS_getcwd: return sys_getcwd(a,b);
113 case SYS_chdir: return sys_chdir(a);
114 case SYS_exec: return sys_exec(a,b,c);
115 case SYS_getdents: return sys_getdents(a,b,c,d);
116 case SYS_unlink: return sys_unlink(a);
118 default: return super._syscall(syscall,a,b,c,d);
122 FD _open(String path, int flags, int mode) throws ErrnoException {
123 return gs.open(this,normalizePath(path),flags,mode);
126 /** The kill syscall.
127 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
128 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
129 Anything else terminates the process. */
130 private int sys_kill(int pid, int signal) {
131 // This will only be called by raise() in newlib to invoke the default handler
132 // We don't have to worry about actually delivering the signal
133 if(pid != pid) return -ESRCH;
134 if(signal < 0 || signal >= 32) return -EINVAL;
149 return syscall(SYS_exit,128+signal,0,0,0);
154 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
155 final int WNOHANG = 1;
156 if((options & ~(WNOHANG)) != 0) return -EINVAL;
157 if(pid == 0 || pid < -1) {
158 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
161 boolean blocking = (options&WNOHANG)==0;
163 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
164 if(children == null) return blocking ? -ECHILD : 0;
166 UnixRuntime done = null;
168 synchronized(children) {
171 if(exitedChildren.size() > 0) done = (UnixRuntime)exitedChildren.remove(exitedChildren.size() - 1);
173 UnixRuntime t = gs.tasks[pid];
174 if(t.parent != this) return -ECHILD;
175 if(t.state == EXITED) {
176 if(!exitedChildren.remove(t)) throw new Error("should never happen");
180 // process group stuff, EINVAL returned above
181 throw new Error("should never happen");
184 if(!blocking) return 0;
185 try { children.wait(); } catch(InterruptedException e) {}
186 //System.err.println("waitpid woke up: " + exitedChildren.size());
188 gs.tasks[done.pid] = null;
193 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
199 if(children != null) synchronized(children) {
200 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
201 UnixRuntime child = (UnixRuntime) e.nextElement();
202 gs.tasks[child.pid] = null;
204 exitedChildren.clear();
205 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
206 UnixRuntime child = (UnixRuntime) e.nextElement();
209 activeChildren.clear();
212 UnixRuntime _parent = parent;
213 if(_parent == null) {
214 gs.tasks[pid] = null;
216 synchronized(_parent.children) {
218 gs.tasks[pid] = null;
220 parent.activeChildren.remove(this);
221 parent.exitedChildren.add(this);
222 parent.children.notify();
228 protected Object clone() throws CloneNotSupportedException {
229 UnixRuntime r = (UnixRuntime) super.clone();
233 r.activeChildren = r.exitedChildren = null;
237 private int sys_fork() {
238 CPUState state = new CPUState();
240 int sp = state.r[SP];
244 r = (UnixRuntime) clone();
245 } catch(Exception e) {
254 } catch(ProcessTableFullExn e) {
258 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
259 if(children == null) {
260 children = new Object();
261 activeChildren = new Vector();
262 exitedChildren = new Vector();
264 activeChildren.add(r);
266 state.r[V0] = 0; // return 0 to child
267 state.pc += 4; // skip over syscall instruction
268 r.setCPUState(state);
271 new ForkedProcess(r);
276 public static final class ForkedProcess extends Thread {
277 private final UnixRuntime initial;
278 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
279 public void run() { UnixRuntime.executeAndExec(initial); }
282 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
283 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
285 public static int executeAndExec(UnixRuntime r) {
288 if(r.execute()) break;
289 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
291 if(r.state != EXECED) return r.exitStatus();
296 private String[] readStringArray(int addr) throws ReadFaultException {
298 for(int p=addr;memRead(p) != 0;p+=4) count++;
299 String[] a = new String[count];
300 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
304 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
305 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
308 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
309 if(argv.length == 0) argv = new String[]{""};
311 // NOTE: For this little hack to work nestedvm.root MUST be "."
313 System.err.println("Execing normalized path: " + normalizedPath);
314 if(true) return exec(new Interpreter(normalizedPath),argv,envp);
315 } catch(IOException e) { throw new Error(e); }*/
317 Object o = gs.exec(this,normalizedPath);
318 if(o == null) return -ENOENT;
320 if(o instanceof Class) {
323 return exec((UnixRuntime) c.newInstance(),argv,envp);
324 } catch(Exception e) {
329 String[] command = (String[]) o;
330 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
331 int p = command[0].lastIndexOf('/');
332 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
334 if(command[1] != null) newArgv[p++] = command[1];
335 newArgv[p++] = "/" + normalizedPath;
336 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
337 return exec(command[0],newArgv,envp);
341 private int exec(UnixRuntime r, String[] argv, String[] envp) {
343 //System.err.println("Execing " + r);
344 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
346 r.closeOnExec = closeOnExec;
347 // make sure this doesn't get messed with these since we didn't copy them
364 // FEATURE: Make sure fstat info is correct
365 // FEATURE: This could be faster if we did direct copies from each process' memory
366 // FEATURE: Check this logic one more time
367 public static class Pipe {
368 private final byte[] pipebuf = new byte[PIPE_BUF*4];
370 private int writePos;
372 public final FD reader = new Reader();
373 public final FD writer = new Writer();
375 public class Reader extends FD {
376 protected FStat _fstat() { return new FStat(); }
377 public int read(byte[] buf, int off, int len) throws ErrnoException {
378 if(len == 0) return 0;
379 synchronized(Pipe.this) {
380 while(writePos != -1 && readPos == writePos) {
381 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
383 if(writePos == -1) return 0; // eof
384 len = Math.min(len,writePos-readPos);
385 System.arraycopy(pipebuf,readPos,buf,off,len);
387 if(readPos == writePos) Pipe.this.notify();
391 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
394 public class Writer extends FD {
395 protected FStat _fstat() { return new FStat(); }
396 public int write(byte[] buf, int off, int len) throws ErrnoException {
397 if(len == 0) return 0;
398 synchronized(Pipe.this) {
399 if(readPos == -1) throw new ErrnoException(EPIPE);
400 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
401 // not enough space to atomicly write the data
402 while(readPos != -1 && readPos != writePos) {
403 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
405 if(readPos == -1) throw new ErrnoException(EPIPE);
406 readPos = writePos = 0;
408 len = Math.min(len,pipebuf.length - writePos);
409 System.arraycopy(buf,off,pipebuf,writePos,len);
410 if(readPos == writePos) Pipe.this.notify();
415 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
419 private int sys_pipe(int addr) {
420 Pipe pipe = new Pipe();
422 int fd1 = addFD(pipe.reader);
423 if(fd1 < 0) return -ENFILE;
424 int fd2 = addFD(pipe.writer);
425 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
429 memWrite(addr+4,fd2);
430 } catch(FaultException e) {
438 private int sys_dup2(int oldd, int newd) {
439 if(oldd == newd) return 0;
440 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
441 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
442 if(fds[oldd] == null) return -EBADFD;
443 if(fds[newd] != null) fds[newd].close();
444 fds[newd] = fds[oldd].dup();
448 private int sys_dup(int oldd) {
449 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
450 if(fds[oldd] == null) return -EBADFD;
451 FD fd = fds[oldd].dup();
452 int newd = addFD(fd);
453 if(newd < 0) { fd.close(); return -ENFILE; }
457 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
458 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
459 if(s == null) return -ENOENT;
463 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
464 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
465 if(s == null) return -ENOENT;
469 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
470 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
474 private int sys_unlink(int cstring) throws FaultException, ErrnoException {
475 gs.unlink(this,normalizePath(cstring(cstring)));
479 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
480 byte[] b = getBytes(cwd);
481 if(size == 0) return -EINVAL;
482 if(size < b.length+2) return -ERANGE;
484 copyout(b,addr+1,b.length);
485 memset(addr+b.length+1,0,1);
489 private int sys_chdir(int addr) throws ErrnoException, FaultException {
490 String path = normalizePath(cstring(addr));
491 //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
492 if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
494 //System.err.println("Now: [" + cwd + "]");
498 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
499 count = Math.min(count,MAX_CHUNK);
500 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
501 if(fds[fdn] == null) return -EBADFD;
502 byte[] buf = byteBuf(count);
503 int n = fds[fdn].getdents(buf,0,count);
508 // FEATURE: Run through the fork/wait stuff one more time
509 public static class GlobalState {
510 protected static final int OPEN = 1;
511 protected static final int STAT = 2;
512 protected static final int LSTAT = 3;
513 protected static final int MKDIR = 4;
514 protected static final int UNLINK = 5;
516 final UnixRuntime[] tasks;
519 private MP[] mps = new MP[0];
522 public GlobalState() { this(255); }
523 public GlobalState(int maxProcs) { this(maxProcs,true); }
524 public GlobalState(int maxProcs, boolean defaultMounts) {
525 tasks = new UnixRuntime[maxProcs+1];
527 addMount("/",new HostFS());
528 addMount("/dev",new DevFS());
532 private static class MP {
533 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
536 public int compareTo(Object o) {
537 if(!(o instanceof MP)) return 1;
538 return -path.compareTo(((MP)o).path);
542 public synchronized FS getMount(String path) {
543 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
544 if(path.equals("/")) return root;
545 path = path.substring(1);
546 for(int i=0;i<mps.length;i++)
547 if(mps[i].path.equals(path)) return mps[i].fs;
551 public synchronized void addMount(String path, FS fs) {
552 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
553 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
555 if(fs.owner != null) fs.owner.removeMount(fs);
558 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
559 path = path.substring(1);
560 int oldLength = mps.length;
561 MP[] newMPS = new MP[oldLength + 1];
562 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
563 newMPS[oldLength] = new MP(path,fs);
567 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
568 fs.devno = highdevno + 2;
571 public synchronized void removeMount(FS fs) {
572 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
573 throw new IllegalArgumentException("mount point doesn't exist");
576 public synchronized void removeMount(String path) {
577 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
578 if(path.equals("/")) {
581 path = path.substring(1);
583 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
584 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
589 private void removeMount(int index) {
590 if(index == -1) { root.owner = null; root = null; return; }
591 MP[] newMPS = new MP[mps.length - 1];
592 System.arraycopy(mps,0,newMPS,0,index);
593 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
597 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
598 int pl = normalizedPath.length();
601 synchronized(this) { list = mps; }
602 for(int i=0;i<list.length;i++) {
604 int mpl = mp.path.length();
605 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
606 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
609 return dispatch(root,op,r,normalizedPath,arg1,arg2);
612 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
614 case OPEN: return fs.open(r,path,arg1,arg2);
615 case STAT: return fs.stat(r,path);
616 case LSTAT: return fs.lstat(r,path);
617 case MKDIR: fs.mkdir(r,path,arg1); return null;
618 case UNLINK: fs.unlink(r,path); return null;
619 default: throw new Error("should never happen");
623 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
624 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
625 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
626 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
627 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
629 private Hashtable execCache = new Hashtable();
630 private static class CacheEnt {
631 public final long time;
632 public final long size;
633 public final Object o;
634 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
637 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
638 FStat fstat = stat(r,path);
639 if(fstat == null) return null;
640 long mtime = fstat.mtime();
641 long size = fstat.size();
642 CacheEnt ent = (CacheEnt) execCache.get(path);
644 //System.err.println("Found cached entry for " + path);
645 if(ent.time == mtime && ent.size == size) return ent.o;
646 //System.err.println("Cache was out of date");
647 execCache.remove(path);
649 FD fd = open(r,path,RD_ONLY,0);
650 if(fd == null) return null;
651 Seekable s = fd.seekable();
653 String[] command = null;
655 if(s == null) throw new ErrnoException(EACCES);
656 byte[] buf = new byte[4096];
659 int n = s.read(buf,0,buf.length);
660 if(n == -1) throw new ErrnoException(ENOEXEC);
663 case '\177': // possible ELF
664 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
665 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
669 int n2 = s.read(buf,1,buf.length-1);
670 if(n2 == -1) throw new ErrnoException(ENOEXEC);
673 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
677 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
679 if(p == buf.length) break OUTER;
680 n = s.read(buf,p,buf.length-p);
682 command = new String[2];
684 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
687 while(arg < p && buf[arg] == ' ') arg++;
688 command[0] = new String(buf,2,cmdEnd);
689 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
691 command[0] = new String(buf,2,p-2);
693 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
696 throw new ErrnoException(ENOEXEC);
698 } catch(IOException e) {
700 throw new ErrnoException(EIO);
703 if(command == null) {
707 Class c = RuntimeCompiler.compile(s);
708 //System.err.println("Compile succeeded: " + c);
709 ent = new CacheEnt(mtime,size,c);
710 } catch(Compiler.Exn e) {
711 if(STDERR_DIAG) e.printStackTrace();
712 throw new ErrnoException(ENOEXEC);
713 } catch(IOException e) {
714 if(STDERR_DIAG) e.printStackTrace();
715 throw new ErrnoException(EIO);
718 ent = new CacheEnt(mtime,size,command);
723 execCache.put(path,ent);
728 public abstract static class FS {
732 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
734 // If this returns null it'll be truned into an ENOENT
735 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
736 // If this returns null it'll be turned into an ENOENT
737 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
738 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
739 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
742 // FEATURE: chroot support in here
743 private String normalizePath(String path) {
744 boolean absolute = path.startsWith("/");
745 int cwdl = cwd.length();
746 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
747 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
748 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
750 char[] in = new char[path.length()+1];
751 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
755 do { inp++; } while(in[inp] == '/');
756 } else if(cwdl != 0) {
757 cwd.getChars(0,cwdl,out,0);
761 path.getChars(0,path.length(),in,0);
762 while(in[inp] != 0) {
763 if(inp != 0 || cwdl==0) {
764 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
765 while(in[inp] == '/') inp++;
767 if(in[inp] == '\0') continue;
768 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
769 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
770 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
773 while(outp > 0 && out[outp] != '/') outp--;
774 //System.err.println("After ..: " + new String(out,0,outp));
781 if(outp > 0 && out[outp-1] == '/') outp--;
782 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
783 return new String(out,0,outp);
786 FStat hostFStat(final File f, Object data) {
789 FileInputStream fis = new FileInputStream(f);
791 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
792 case '#': e = fis.read() == '!';
795 } catch(IOException e2) { }
796 HostFS fs = (HostFS) data;
797 final int inode = fs.inodes.get(f.getAbsolutePath());
798 final int devno = fs.devno;
799 return new HostFStat(f,e) {
800 public int inode() { return inode; }
801 public int dev() { return devno; }
805 FD hostFSDirFD(File f, Object _fs) {
806 HostFS fs = (HostFS) _fs;
807 return fs.new HostDirFD(f);
810 public static class HostFS extends FS {
811 InodeCache inodes = new InodeCache(4000);
813 public File getRoot() { return root; }
815 private static File hostRootDir() {
816 if(getSystemProperty("nestedvm.root") != null) {
817 File f = new File(getSystemProperty("nestedvm.root"));
818 if(f.isDirectory()) return f;
819 // fall through to case below
821 String cwd = getSystemProperty("user.dir");
822 File f = new File(cwd != null ? cwd : ".");
823 if(!f.exists()) throw new Error("Couldn't get File for cwd");
824 f = new File(f.getAbsolutePath());
825 while(f.getParent() != null) f = new File(f.getParent());
829 private File hostFile(String path) {
830 char sep = File.separatorChar;
832 char buf[] = path.toCharArray();
833 for(int i=0;i<buf.length;i++) {
835 if(c == '/') buf[i] = sep;
836 else if(c == sep) buf[i] = '/';
838 path = new String(buf);
840 return new File(root,path);
843 public HostFS() { this(hostRootDir()); }
844 public HostFS(String root) { this(new File(root)); }
845 public HostFS(File root) { this.root = root; }
848 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
849 final File f = hostFile(path);
850 return r.hostFSOpen(f,flags,mode,this);
853 public void unlink(UnixRuntime r, String path) throws ErrnoException {
854 File f = hostFile(path);
855 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
856 if(!f.exists()) throw new ErrnoException(ENOENT);
857 if(!f.delete()) throw new ErrnoException(EPERM);
860 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
861 File f = hostFile(path);
862 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
863 if(!f.exists()) return null;
864 return r.hostFStat(f,this);
867 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
868 File f = hostFile(path);
869 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
870 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
871 if(f.exists()) throw new ErrnoException(ENOTDIR);
872 File parent = f.getParentFile();
873 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
874 if(!f.mkdir()) throw new ErrnoException(EIO);
877 public class HostDirFD extends DirFD {
878 private final File f;
879 private final File[] children;
880 public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
881 public int size() { return children.length; }
882 public String name(int n) { return children[n].getName(); }
883 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
884 public int parentInode() {
885 File parent = f.getParentFile();
886 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
888 public int myInode() { return inodes.get(f.getAbsolutePath()); }
889 public int myDev() { return devno; }
893 private static void putInt(byte[] buf, int off, int n) {
894 buf[off+0] = (byte)((n>>>24)&0xff);
895 buf[off+1] = (byte)((n>>>16)&0xff);
896 buf[off+2] = (byte)((n>>> 8)&0xff);
897 buf[off+3] = (byte)((n>>> 0)&0xff);
900 public static abstract class DirFD extends FD {
901 private int pos = -2;
903 protected abstract int size();
904 protected abstract String name(int n);
905 protected abstract int inode(int n);
906 protected abstract int myDev();
907 protected int parentInode() { return -1; }
908 protected int myInode() { return -1; }
910 public int getdents(byte[] buf, int off, int len) {
914 OUTER: for(;len > 0 && pos < size();pos++){
918 ino = pos == -1 ? parentInode() : myInode();
919 if(ino == -1) continue;
920 reclen = 9 + (pos == -1 ? 2 : 1);
921 if(reclen > len) break OUTER;
923 if(pos == -1) buf[off+9] = '.';
926 String f = name(pos);
927 byte[] fb = getBytes(f);
928 reclen = fb.length + 9;
929 if(reclen > len) break OUTER;
931 System.arraycopy(fb,0,buf,off+8,fb.length);
934 buf[off+reclen-1] = 0; // null terminate
935 reclen = (reclen + 3) & ~3; // add padding
936 putInt(buf,off,reclen);
937 putInt(buf,off+4,ino);
944 protected FStat _fstat() {
946 public int type() { return S_IFDIR; }
947 public int inode() { return myInode(); }
948 public int dev() { return myDev(); }
953 public static class DevFS extends FS {
954 private static final int ROOT_INODE = 1;
955 private static final int NULL_INODE = 2;
956 private static final int ZERO_INODE = 3;
957 private static final int FD_INODE = 4;
958 private static final int FD_INODES = 32;
960 private class DevFStat extends FStat {
961 public int dev() { return devno; }
962 public int mode() { return 0666; }
963 public int type() { return S_IFCHR; }
964 public int nlink() { return 1; }
967 private abstract class DevDirFD extends DirFD {
968 public int myDev() { return devno; }
971 private FD devZeroFD = new FD() {
972 public boolean readable() { return true; }
973 public boolean writable() { return true; }
974 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
975 public int write(byte[] a, int off, int length) { return length; }
976 public int seek(int n, int whence) { return 0; }
977 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
979 private FD devNullFD = new FD() {
980 public boolean readable() { return true; }
981 public boolean writable() { return true; }
982 public int read(byte[] a, int off, int length) { return 0; }
983 public int write(byte[] a, int off, int length) { return length; }
984 public int seek(int n, int whence) { return 0; }
985 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
988 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
989 if(path.equals("null")) return devNullFD;
990 if(path.equals("zero")) return devZeroFD;
991 if(path.startsWith("fd/")) {
994 n = Integer.parseInt(path.substring(4));
995 } catch(NumberFormatException e) {
998 if(n < 0 || n >= OPEN_MAX) return null;
999 if(r.fds[n] == null) return null;
1000 return r.fds[n].dup();
1002 if(path.equals("fd")) {
1004 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1005 final int[] files = new int[count];
1007 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1008 return new DevDirFD() {
1009 public int myInode() { return FD_INODE; }
1010 public int parentInode() { return ROOT_INODE; }
1011 public int inode(int n) { return FD_INODES + n; }
1012 public String name(int n) { return Integer.toString(files[n]); }
1013 public int size() { return files.length; }
1016 if(path.equals("")) {
1017 return new DevDirFD() {
1018 public int myInode() { return ROOT_INODE; }
1019 // FEATURE: Get the real parent inode somehow
1020 public int parentInode() { return -1; }
1021 public int inode(int n) {
1023 case 0: return NULL_INODE;
1024 case 1: return ZERO_INODE;
1025 case 2: return FD_INODE;
1030 public String name(int n) {
1032 case 0: return "null";
1033 case 1: return "zero";
1034 case 2: return "fd";
1035 default: return null;
1038 public int size() { return 3; }
1044 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1045 if(path.equals("null")) return devNullFD.fstat();
1046 if(path.equals("zero")) return devZeroFD.fstat();
1047 if(path.startsWith("fd/")) {
1050 n = Integer.parseInt(path.substring(4));
1051 } catch(NumberFormatException e) {
1054 if(n < 0 || n >= OPEN_MAX) return null;
1055 if(r.fds[n] == null) return null;
1056 return r.fds[n].fstat();
1058 // FEATURE: inode stuff
1059 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1060 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1064 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1065 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }