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 == '/' && HostFS.hostRootDir().getParent() == 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[5];
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 String[] env = new String[extra.length+n];
75 for(int i=0;i<n;i++) env[i] = defaults[i];
76 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
80 private static class ProcessTableFullExn extends RuntimeException { }
83 UnixRuntime[] tasks = gs.tasks;
86 if(tasks[pid] == null || tasks[pid].pid != pid) throw new Error("should never happen");
89 int nextPID = gs.nextPID;
90 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
91 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
92 if(newpid == -1) throw new ProcessTableFullExn();
94 gs.nextPID = newpid + 1;
100 int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
102 case SYS_kill: return sys_kill(a,b);
103 case SYS_fork: return sys_fork();
104 case SYS_pipe: return sys_pipe(a);
105 case SYS_dup2: return sys_dup2(a,b);
106 case SYS_dup: return sys_dup(a);
107 case SYS_waitpid: return sys_waitpid(a,b,c);
108 case SYS_stat: return sys_stat(a,b);
109 case SYS_lstat: return sys_lstat(a,b);
110 case SYS_mkdir: return sys_mkdir(a,b);
111 case SYS_getcwd: return sys_getcwd(a,b);
112 case SYS_chdir: return sys_chdir(a);
113 case SYS_exec: return sys_exec(a,b,c);
114 case SYS_getdents: return sys_getdents(a,b,c,d);
116 default: return super._syscall(syscall,a,b,c,d);
120 FD _open(String path, int flags, int mode) throws ErrnoException {
121 return gs.open(this,normalizePath(path),flags,mode);
124 /** The kill syscall.
125 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
126 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
127 Anything else terminates the process. */
128 private int sys_kill(int pid, int signal) {
129 // This will only be called by raise() in newlib to invoke the default handler
130 // We don't have to worry about actually delivering the signal
131 if(pid != pid) return -ESRCH;
132 if(signal < 0 || signal >= 32) return -EINVAL;
147 return syscall(SYS_exit,128+signal,0,0,0);
152 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
153 final int WNOHANG = 1;
154 if((options & ~(WNOHANG)) != 0) return -EINVAL;
155 if(pid == 0 || pid < -1) {
156 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
159 boolean blocking = (options&WNOHANG)==0;
161 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
162 if(children == null) return blocking ? -ECHILD : 0;
164 UnixRuntime done = null;
166 synchronized(children) {
169 if(exitedChildren.size() > 0) done = (UnixRuntime)exitedChildren.remove(exitedChildren.size() - 1);
171 UnixRuntime t = gs.tasks[pid];
172 if(t.parent != this) return -ECHILD;
173 if(t.state == EXITED) {
174 if(!exitedChildren.remove(t)) throw new Error("should never happen");
178 // process group stuff, EINVAL returned above
179 throw new Error("should never happen");
182 if(!blocking) return 0;
183 try { children.wait(); } catch(InterruptedException e) {}
184 //System.err.println("waitpid woke up: " + exitedChildren.size());
186 gs.tasks[done.pid] = null;
191 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
197 if(children != null) synchronized(children) {
198 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
199 UnixRuntime child = (UnixRuntime) e.nextElement();
200 gs.tasks[child.pid] = null;
202 exitedChildren.clear();
203 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
204 UnixRuntime child = (UnixRuntime) e.nextElement();
207 activeChildren.clear();
210 UnixRuntime _parent = parent;
211 if(_parent == null) {
212 gs.tasks[pid] = null;
214 synchronized(_parent.children) {
216 gs.tasks[pid] = null;
218 parent.activeChildren.remove(this);
219 parent.exitedChildren.add(this);
220 parent.children.notify();
226 protected Object clone() throws CloneNotSupportedException {
227 UnixRuntime r = (UnixRuntime) super.clone();
231 r.activeChildren = r.exitedChildren = null;
235 private int sys_fork() {
236 CPUState state = new CPUState();
238 int sp = state.r[SP];
242 r = (UnixRuntime) clone();
243 } catch(Exception e) {
252 } catch(ProcessTableFullExn e) {
256 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
257 if(children == null) {
258 children = new Object();
259 activeChildren = new Vector();
260 exitedChildren = new Vector();
262 activeChildren.add(r);
264 state.r[V0] = 0; // return 0 to child
265 state.pc += 4; // skip over syscall instruction
266 r.setCPUState(state);
269 new ForkedProcess(r);
274 public static final class ForkedProcess extends Thread {
275 private final UnixRuntime initial;
276 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
277 public void run() { UnixRuntime.executeAndExec(initial); }
280 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
281 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
283 public static int executeAndExec(UnixRuntime r) {
286 if(r.execute()) break;
287 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
289 if(r.state != EXECED) return r.exitStatus();
294 private String[] readStringArray(int addr) throws ReadFaultException {
296 for(int p=addr;memRead(p) != 0;p+=4) count++;
297 String[] a = new String[count];
298 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
302 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
303 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
306 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
307 if(argv.length == 0) argv = new String[]{""};
309 // NOTE: For this little hack to work nestedvm.root MUST be "."
311 System.err.println("Execing normalized path: " + normalizedPath);
312 if(true) return exec(new Interpreter(normalizedPath),argv,envp);
313 } catch(IOException e) { throw new Error(e); }*/
315 Object o = gs.exec(this,normalizedPath);
316 if(o == null) return -ENOENT;
318 if(o instanceof Class) {
321 return exec((UnixRuntime) c.newInstance(),argv,envp);
322 } catch(Exception e) {
327 String[] command = (String[]) o;
328 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
329 int p = command[0].lastIndexOf('/');
330 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
332 if(command[1] != null) newArgv[p++] = command[1];
333 newArgv[p++] = "/" + normalizedPath;
334 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
335 return exec(command[0],newArgv,envp);
339 private int exec(UnixRuntime r, String[] argv, String[] envp) {
341 //System.err.println("Execing " + r);
342 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
344 r.closeOnExec = closeOnExec;
345 // make sure this doesn't get messed with these since we didn't copy them
362 // FEATURE: Make sure fstat info is correct
363 // FEATURE: This could be faster if we did direct copies from each process' memory
364 // FEATURE: Check this logic one more time
365 public static class Pipe {
366 private final byte[] pipebuf = new byte[PIPE_BUF*4];
368 private int writePos;
370 public final FD reader = new Reader();
371 public final FD writer = new Writer();
373 public class Reader extends FD {
374 protected FStat _fstat() { return new FStat(); }
375 public int read(byte[] buf, int off, int len) throws ErrnoException {
376 if(len == 0) return 0;
377 synchronized(Pipe.this) {
378 while(writePos != -1 && readPos == writePos) {
379 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
381 if(writePos == -1) return 0; // eof
382 len = Math.min(len,writePos-readPos);
383 System.arraycopy(pipebuf,readPos,buf,off,len);
385 if(readPos == writePos) Pipe.this.notify();
389 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
392 public class Writer extends FD {
393 protected FStat _fstat() { return new FStat(); }
394 public int write(byte[] buf, int off, int len) throws ErrnoException {
395 if(len == 0) return 0;
396 synchronized(Pipe.this) {
397 if(readPos == -1) throw new ErrnoException(EPIPE);
398 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
399 // not enough space to atomicly write the data
400 while(readPos != -1 && readPos != writePos) {
401 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
403 if(readPos == -1) throw new ErrnoException(EPIPE);
404 readPos = writePos = 0;
406 len = Math.min(len,pipebuf.length - writePos);
407 System.arraycopy(buf,off,pipebuf,writePos,len);
408 if(readPos == writePos) Pipe.this.notify();
413 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
417 private int sys_pipe(int addr) {
418 Pipe pipe = new Pipe();
420 int fd1 = addFD(pipe.reader);
421 if(fd1 < 0) return -ENFILE;
422 int fd2 = addFD(pipe.writer);
423 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
427 memWrite(addr+4,fd2);
428 } catch(FaultException e) {
436 private int sys_dup2(int oldd, int newd) {
437 if(oldd == newd) return 0;
438 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
439 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
440 if(fds[oldd] == null) return -EBADFD;
441 if(fds[newd] != null) fds[newd].close();
442 fds[newd] = fds[oldd].dup();
446 private int sys_dup(int oldd) {
447 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
448 if(fds[oldd] == null) return -EBADFD;
449 FD fd = fds[oldd].dup();
450 int newd = addFD(fd);
451 if(newd < 0) { fd.close(); return -ENFILE; }
455 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
456 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
457 if(s == null) return -ENOENT;
461 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
462 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
463 if(s == null) return -ENOENT;
467 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
468 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
472 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
473 byte[] b = getBytes(cwd);
474 if(size == 0) return -EINVAL;
475 if(size < b.length+2) return -ERANGE;
477 copyout(b,addr+1,b.length);
478 memset(addr+b.length+1,0,1);
482 private int sys_chdir(int addr) throws ErrnoException, FaultException {
483 String path = normalizePath(cstring(addr));
484 //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
485 if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
487 //System.err.println("Now: [" + cwd + "]");
491 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
492 count = Math.min(count,MAX_CHUNK);
493 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
494 if(fds[fdn] == null) return -EBADFD;
495 byte[] buf = byteBuf(count);
496 int n = fds[fdn].getdents(buf,0,count);
501 // FEATURE: Run through the fork/wait stuff one more time
502 public static class GlobalState {
503 protected static final int OPEN = 1;
504 protected static final int STAT = 2;
505 protected static final int LSTAT = 3;
506 protected static final int MKDIR = 4;
508 final UnixRuntime[] tasks;
511 private MP[] mps = new MP[0];
514 public GlobalState() { this(255); }
515 public GlobalState(int maxProcs) { this(maxProcs,true); }
516 public GlobalState(int maxProcs, boolean defaultMounts) {
517 tasks = new UnixRuntime[maxProcs+1];
519 addMount("/",new HostFS());
520 addMount("/dev",new DevFS());
524 private static class MP {
525 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
528 public int compareTo(Object o) {
529 if(!(o instanceof MP)) return 1;
530 return -path.compareTo(((MP)o).path);
534 public synchronized FS getMount(String path) {
535 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
536 if(path.equals("/")) return root;
537 path = path.substring(1);
538 for(int i=0;i<mps.length;i++)
539 if(mps[i].path.equals(path)) return mps[i].fs;
543 public synchronized void addMount(String path, FS fs) {
544 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
545 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
547 if(fs.owner != null) fs.owner.removeMount(fs);
550 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
551 path = path.substring(1);
552 int oldLength = mps.length;
553 MP[] newMPS = new MP[oldLength + 1];
554 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
555 newMPS[oldLength] = new MP(path,fs);
559 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
560 fs.devno = highdevno + 2;
563 public synchronized void removeMount(FS fs) {
564 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
565 throw new IllegalArgumentException("mount point doesn't exist");
568 public synchronized void removeMount(String path) {
569 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
570 if(path.equals("/")) {
573 path = path.substring(1);
575 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
576 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
581 private void removeMount(int index) {
582 if(index == -1) { root.owner = null; root = null; return; }
583 MP[] newMPS = new MP[mps.length - 1];
584 System.arraycopy(mps,0,newMPS,0,index);
585 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
589 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
590 int pl = normalizedPath.length();
593 synchronized(this) { list = mps; }
594 for(int i=0;i<list.length;i++) {
596 int mpl = mp.path.length();
597 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
598 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
601 return dispatch(root,op,r,normalizedPath,arg1,arg2);
604 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
606 case OPEN: return fs.open(r,path,arg1,arg2);
607 case STAT: return fs.stat(r,path);
608 case LSTAT: return fs.lstat(r,path);
609 case MKDIR: fs.mkdir(r,path,arg1); return null;
610 default: throw new Error("should never happen");
614 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
615 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
616 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
617 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
619 private Hashtable execCache = new Hashtable();
620 private static class CacheEnt {
621 public final long time;
622 public final long size;
623 public final Object o;
624 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
627 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
628 FStat fstat = stat(r,path);
629 if(fstat == null) return null;
630 long mtime = fstat.mtime();
631 long size = fstat.size();
632 CacheEnt ent = (CacheEnt) execCache.get(path);
634 //System.err.println("Found cached entry for " + path);
635 if(ent.time == mtime && ent.size == size) return ent.o;
636 //System.err.println("Cache was out of date");
637 execCache.remove(path);
639 FD fd = open(r,path,RD_ONLY,0);
640 if(fd == null) return null;
641 Seekable s = fd.seekable();
643 String[] command = null;
645 if(s == null) throw new ErrnoException(EACCES);
646 byte[] buf = new byte[4096];
649 int n = s.read(buf,0,buf.length);
650 if(n == -1) throw new ErrnoException(ENOEXEC);
653 case '\177': // possible ELF
654 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
655 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
659 int n2 = s.read(buf,1,buf.length-1);
660 if(n2 == -1) throw new ErrnoException(ENOEXEC);
663 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
667 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
669 if(p == buf.length) break OUTER;
670 n = s.read(buf,p,buf.length-p);
672 command = new String[2];
674 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
677 while(arg < p && buf[arg] == ' ') arg++;
678 command[0] = new String(buf,2,cmdEnd);
679 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
681 command[0] = new String(buf,2,p-2);
683 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
686 throw new ErrnoException(ENOEXEC);
688 } catch(IOException e) {
690 throw new ErrnoException(EIO);
693 if(command == null) {
697 Class c = RuntimeCompiler.compile(s);
698 //System.err.println("Compile succeeded: " + c);
699 ent = new CacheEnt(mtime,size,c);
700 } catch(Compiler.Exn e) {
701 if(STDERR_DIAG) e.printStackTrace();
702 throw new ErrnoException(ENOEXEC);
703 } catch(IOException e) {
704 if(STDERR_DIAG) e.printStackTrace();
705 throw new ErrnoException(EIO);
708 ent = new CacheEnt(mtime,size,command);
713 execCache.put(path,ent);
718 public abstract static class FS {
722 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
724 // If this returns null it'll be truned into an ENOENT
725 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
726 // If this returns null it'll be turned into an ENOENT
727 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
728 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
731 // FEATURE: chroot support in here
732 private String normalizePath(String path) {
733 boolean absolute = path.startsWith("/");
734 int cwdl = cwd.length();
735 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
736 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
737 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
739 char[] in = new char[path.length()+1];
740 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
744 do { inp++; } while(in[inp] == '/');
745 } else if(cwdl != 0) {
746 cwd.getChars(0,cwdl,out,0);
750 path.getChars(0,path.length(),in,0);
751 while(in[inp] != 0) {
753 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
754 while(in[inp] == '/') inp++;
756 if(in[inp] == '\0') continue;
757 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
758 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
759 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
762 while(outp > 0 && out[outp] != '/') outp--;
763 //System.err.println("After ..: " + new String(out,0,outp));
770 if(outp > 0 && out[outp-1] == '/') outp--;
771 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
772 return new String(out,0,outp);
775 FStat hostFStat(final File f, Object data) {
778 FileInputStream fis = new FileInputStream(f);
780 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
781 case '#': e = fis.read() == '!';
784 } catch(IOException e2) { }
785 HostFS fs = (HostFS) data;
786 final int inode = fs.inodes.get(f.getAbsolutePath());
787 final int devno = fs.devno;
788 return new HostFStat(f,e) {
789 public int inode() { return inode; }
790 public int dev() { return devno; }
794 FD hostFSDirFD(File f, Object _fs) {
795 HostFS fs = (HostFS) _fs;
796 return fs.new HostDirFD(f);
799 public static class HostFS extends FS {
800 InodeCache inodes = new InodeCache(4000);
802 public File getRoot() { return root; }
804 private static File hostRootDir() {
805 if(getSystemProperty("nestedvm.root") != null) {
806 File f = new File(getSystemProperty("nestedvm.root"));
807 if(f.isDirectory()) return f;
808 // fall through to case below
810 String cwd = getSystemProperty("user.dir");
811 File f = new File(cwd != null ? cwd : ".");
812 if(!f.exists()) throw new Error("Couldn't get File for cwd");
813 f = new File(f.getAbsolutePath());
814 while(f.getParent() != null) f = new File(f.getParent());
818 private File hostFile(String path) {
819 char sep = File.separatorChar;
821 char buf[] = path.toCharArray();
822 for(int i=0;i<buf.length;i++) {
824 if(c == '/') buf[i] = sep;
825 else if(c == sep) buf[i] = '/';
827 path = new String(buf);
829 return new File(root,path);
832 public HostFS() { this(hostRootDir()); }
833 public HostFS(String root) { this(new File(root)); }
834 public HostFS(File root) { this.root = root; }
837 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
838 final File f = hostFile(path);
839 return r.hostFSOpen(f,flags,mode,this);
842 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
843 File f = hostFile(path);
844 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
845 if(!f.exists()) return null;
846 return r.hostFStat(f,this);
849 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
850 File f = hostFile(path);
851 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
852 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
853 if(f.exists()) throw new ErrnoException(ENOTDIR);
854 File parent = f.getParentFile();
855 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
856 if(!f.mkdir()) throw new ErrnoException(EIO);
859 public class HostDirFD extends DirFD {
860 private final File f;
861 private final File[] children;
862 public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
863 public int size() { return children.length; }
864 public String name(int n) { return children[n].getName(); }
865 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
866 public int parentInode() {
867 File parent = f.getParentFile();
868 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
870 public int myInode() { return inodes.get(f.getAbsolutePath()); }
871 public int myDev() { return devno; }
875 private static void putInt(byte[] buf, int off, int n) {
876 buf[off+0] = (byte)((n>>>24)&0xff);
877 buf[off+1] = (byte)((n>>>16)&0xff);
878 buf[off+2] = (byte)((n>>> 8)&0xff);
879 buf[off+3] = (byte)((n>>> 0)&0xff);
882 public static abstract class DirFD extends FD {
883 private int pos = -2;
885 protected abstract int size();
886 protected abstract String name(int n);
887 protected abstract int inode(int n);
888 protected abstract int myDev();
889 protected int parentInode() { return -1; }
890 protected int myInode() { return -1; }
892 public int getdents(byte[] buf, int off, int len) {
896 OUTER: for(;len > 0 && pos < size();pos++){
900 ino = pos == -1 ? parentInode() : myInode();
901 if(ino == -1) continue;
902 reclen = 9 + (pos == -1 ? 2 : 1);
903 if(reclen > len) break OUTER;
905 if(pos == -1) buf[off+9] = '.';
908 String f = name(pos);
909 byte[] fb = getBytes(f);
910 reclen = fb.length + 9;
911 if(reclen > len) break OUTER;
913 System.arraycopy(fb,0,buf,off+8,fb.length);
916 buf[off+reclen-1] = 0; // null terminate
917 reclen = (reclen + 3) & ~3; // add padding
918 putInt(buf,off,reclen);
919 putInt(buf,off+4,ino);
926 protected FStat _fstat() {
928 public int type() { return S_IFDIR; }
929 public int inode() { return myInode(); }
930 public int dev() { return myDev(); }
935 public static class DevFS extends FS {
936 private static final int ROOT_INODE = 1;
937 private static final int NULL_INODE = 2;
938 private static final int ZERO_INODE = 3;
939 private static final int FD_INODE = 4;
940 private static final int FD_INODES = 32;
942 private class DevFStat extends FStat {
943 public int dev() { return devno; }
944 public int mode() { return 0666; }
945 public int type() { return S_IFCHR; }
946 public int nlink() { return 1; }
949 private abstract class DevDirFD extends DirFD {
950 public int myDev() { return devno; }
953 private FD devZeroFD = new FD() {
954 public boolean readable() { return true; }
955 public boolean writable() { return true; }
956 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
957 public int write(byte[] a, int off, int length) { return length; }
958 public int seek(int n, int whence) { return 0; }
959 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
961 private FD devNullFD = new FD() {
962 public boolean readable() { return true; }
963 public boolean writable() { return true; }
964 public int read(byte[] a, int off, int length) { return 0; }
965 public int write(byte[] a, int off, int length) { return length; }
966 public int seek(int n, int whence) { return 0; }
967 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
970 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
971 if(path.equals("null")) return devNullFD;
972 if(path.equals("zero")) return devZeroFD;
973 if(path.startsWith("fd/")) {
976 n = Integer.parseInt(path.substring(4));
977 } catch(NumberFormatException e) {
980 if(n < 0 || n >= OPEN_MAX) return null;
981 if(r.fds[n] == null) return null;
982 return r.fds[n].dup();
984 if(path.equals("fd")) {
986 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
987 final int[] files = new int[count];
989 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
990 return new DevDirFD() {
991 public int myInode() { return FD_INODE; }
992 public int parentInode() { return ROOT_INODE; }
993 public int inode(int n) { return FD_INODES + n; }
994 public String name(int n) { return Integer.toString(files[n]); }
995 public int size() { return files.length; }
998 if(path.equals("")) {
999 return new DevDirFD() {
1000 public int myInode() { return ROOT_INODE; }
1001 // FEATURE: Get the real parent inode somehow
1002 public int parentInode() { return -1; }
1003 public int inode(int n) {
1005 case 0: return NULL_INODE;
1006 case 1: return ZERO_INODE;
1007 case 2: return FD_INODE;
1012 public String name(int n) {
1014 case 0: return "null";
1015 case 1: return "zero";
1016 case 2: return "fd";
1017 default: return null;
1020 public int size() { return 3; }
1026 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1027 if(path.equals("null")) return devNullFD.fstat();
1028 if(path.equals("zero")) return devZeroFD.fstat();
1029 if(path.startsWith("fd/")) {
1032 n = Integer.parseInt(path.substring(4));
1033 } catch(NumberFormatException e) {
1036 if(n < 0 || n >= OPEN_MAX) return null;
1037 if(r.fds[n] == null) return null;
1038 return r.fds[n].fstat();
1040 // FEATURE: inode stuff
1041 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1042 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1046 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EACCES); }