1 package org.ibex.nestedvm;
3 import org.ibex.nestedvm.util.*;
9 public abstract class UnixRuntime extends Runtime implements Cloneable {
10 /** The pid of this "process" */
12 private UnixRuntime parent;
13 public final int getPid() { return pid; }
15 private static final GlobalState defaultGS = new GlobalState();
16 private GlobalState gs = defaultGS;
17 public void setGlobalState(GlobalState gs) {
18 if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running");
22 /** proceses' current working directory - absolute path WITHOUT leading slash
23 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
26 /** The runtime that should be run next when in state == EXECED */
27 private UnixRuntime execedRuntime;
29 private Object children; // used only for synchronizatin
30 private Vector activeChildren;
31 private Vector exitedChildren;
33 protected UnixRuntime(int pageSize, int totalPages) {
34 super(pageSize,totalPages);
36 // FEATURE: Do the proper mangling for non-unix hosts
37 String userdir = getSystemProperty("user.dir");
39 userdir != null && userdir.startsWith("/") && File.separatorChar == '/' && getSystemProperty("nestedvm.root") == null
40 ? userdir.substring(1) : "";
43 // NOTE: getDisplayName() is a Java2 function
44 private static String posixTZ() {
45 StringBuffer sb = new StringBuffer();
46 TimeZone zone = TimeZone.getDefault();
47 int off = zone.getRawOffset() / 1000;
48 sb.append(zone.getDisplayName(false,TimeZone.SHORT));
49 if(off > 0) sb.append("-");
51 sb.append(off/3600); off = off%3600;
52 if(off > 0) sb.append(":").append(off/60); off=off%60;
53 if(off > 0) sb.append(":").append(off);
54 if(zone.useDaylightTime())
55 sb.append(zone.getDisplayName(true,TimeZone.SHORT));
59 private static boolean envHas(String key,String[] environ) {
60 for(int i=0;i<environ.length;i++)
61 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
65 String[] createEnv(String[] extra) {
66 String[] defaults = new String[6];
68 if(extra == null) extra = new String[0];
69 if(!envHas("USER",extra) && getSystemProperty("user.name") != null)
70 defaults[n++] = "USER=" + getSystemProperty("user.name");
71 if(!envHas("HOME",extra) && getSystemProperty("user.home") != null)
72 defaults[n++] = "HOME=" + getSystemProperty("user.home");
73 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
74 if(!envHas("TERM",extra)) defaults[n++] = "TERM=vt100";
75 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
76 if(!envHas("PATH",extra)) defaults[n++] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin";
77 String[] env = new String[extra.length+n];
78 for(int i=0;i<n;i++) env[i] = defaults[i];
79 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
83 private static class ProcessTableFullExn extends RuntimeException { }
86 UnixRuntime[] tasks = gs.tasks;
89 UnixRuntime prev = tasks[pid];
90 if(prev == null || prev == this || prev.pid != pid || prev.parent != parent)
91 throw new Error("should never happen");
92 synchronized(parent.children) {
93 int i = parent.activeChildren.indexOf(prev);
94 if(i == -1) throw new Error("should never happen");
95 parent.activeChildren.set(i,this);
99 int nextPID = gs.nextPID;
100 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
101 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
102 if(newpid == -1) throw new ProcessTableFullExn();
104 gs.nextPID = newpid + 1;
110 int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
112 case SYS_kill: return sys_kill(a,b);
113 case SYS_fork: return sys_fork();
114 case SYS_pipe: return sys_pipe(a);
115 case SYS_dup2: return sys_dup2(a,b);
116 case SYS_dup: return sys_dup(a);
117 case SYS_waitpid: return sys_waitpid(a,b,c);
118 case SYS_stat: return sys_stat(a,b);
119 case SYS_lstat: return sys_lstat(a,b);
120 case SYS_mkdir: return sys_mkdir(a,b);
121 case SYS_getcwd: return sys_getcwd(a,b);
122 case SYS_chdir: return sys_chdir(a);
123 case SYS_exec: return sys_exec(a,b,c);
124 case SYS_getdents: return sys_getdents(a,b,c,d);
125 case SYS_unlink: return sys_unlink(a);
126 case SYS_getppid: return sys_getppid();
128 default: return super._syscall(syscall,a,b,c,d);
132 FD _open(String path, int flags, int mode) throws ErrnoException {
133 return gs.open(this,normalizePath(path),flags,mode);
136 private int sys_getppid() {
137 return parent == null ? 1 : parent.pid;
140 /** The kill syscall.
141 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
142 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
143 Anything else terminates the process. */
144 private int sys_kill(int pid, int signal) {
145 // This will only be called by raise() in newlib to invoke the default handler
146 // We don't have to worry about actually delivering the signal
147 if(pid != pid) return -ESRCH;
148 if(signal < 0 || signal >= 32) return -EINVAL;
163 return syscall(SYS_exit,128+signal,0,0,0);
168 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
169 final int WNOHANG = 1;
170 if((options & ~(WNOHANG)) != 0) return -EINVAL;
171 if(pid == 0 || pid < -1) {
172 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
175 boolean blocking = (options&WNOHANG)==0;
177 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
178 if(children == null) return blocking ? -ECHILD : 0;
180 UnixRuntime done = null;
182 synchronized(children) {
185 if(exitedChildren.size() > 0) done = (UnixRuntime)exitedChildren.remove(exitedChildren.size() - 1);
187 UnixRuntime t = gs.tasks[pid];
188 if(t.parent != this) return -ECHILD;
189 if(t.state == EXITED) {
190 if(!exitedChildren.remove(t)) throw new Error("should never happen");
194 // process group stuff, EINVAL returned above
195 throw new Error("should never happen");
198 if(!blocking) return 0;
199 try { children.wait(); } catch(InterruptedException e) {}
200 //System.err.println("waitpid woke up: " + exitedChildren.size());
202 gs.tasks[done.pid] = null;
207 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
213 if(children != null) synchronized(children) {
214 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
215 UnixRuntime child = (UnixRuntime) e.nextElement();
216 gs.tasks[child.pid] = null;
218 exitedChildren.clear();
219 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
220 UnixRuntime child = (UnixRuntime) e.nextElement();
223 activeChildren.clear();
226 UnixRuntime _parent = parent;
227 if(_parent == null) {
228 gs.tasks[pid] = null;
230 synchronized(_parent.children) {
232 gs.tasks[pid] = null;
234 if(!parent.activeChildren.remove(this)) throw new Error("should never happen _exited: pid: " + pid);
235 parent.exitedChildren.add(this);
236 parent.children.notify();
242 protected Object clone() throws CloneNotSupportedException {
243 UnixRuntime r = (UnixRuntime) super.clone();
247 r.activeChildren = r.exitedChildren = null;
251 private int sys_fork() {
252 CPUState state = new CPUState();
254 int sp = state.r[SP];
258 r = (UnixRuntime) clone();
259 } catch(Exception e) {
268 } catch(ProcessTableFullExn e) {
272 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
273 if(children == null) {
274 children = new Object();
275 activeChildren = new Vector();
276 exitedChildren = new Vector();
278 activeChildren.add(r);
280 state.r[V0] = 0; // return 0 to child
281 state.pc += 4; // skip over syscall instruction
282 r.setCPUState(state);
285 new ForkedProcess(r);
290 public static final class ForkedProcess extends Thread {
291 private final UnixRuntime initial;
292 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
293 public void run() { UnixRuntime.executeAndExec(initial); }
296 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
297 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
299 public static int executeAndExec(UnixRuntime r) {
302 if(r.execute()) break;
303 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
305 if(r.state != EXECED) return r.exitStatus();
310 private String[] readStringArray(int addr) throws ReadFaultException {
312 for(int p=addr;memRead(p) != 0;p+=4) count++;
313 String[] a = new String[count];
314 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
318 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
319 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
322 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
323 if(argv.length == 0) argv = new String[]{""};
325 // NOTE: For this little hack to work nestedvm.root MUST be "."
327 System.err.println("Execing normalized path: " + normalizedPath);
328 if(true) return exec(new Interpreter(normalizedPath),argv,envp);
329 } catch(IOException e) { throw new Error(e); }*/
331 Object o = gs.exec(this,normalizedPath);
332 if(o == null) return -ENOENT;
334 if(o instanceof Class) {
337 return exec((UnixRuntime) c.newInstance(),argv,envp);
338 } catch(Exception e) {
343 String[] command = (String[]) o;
344 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
345 int p = command[0].lastIndexOf('/');
346 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
348 if(command[1] != null) newArgv[p++] = command[1];
349 newArgv[p++] = "/" + normalizedPath;
350 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
351 return exec(command[0],newArgv,envp);
355 private int exec(UnixRuntime r, String[] argv, String[] envp) {
357 //System.err.println("Execing " + r);
358 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
360 r.closeOnExec = closeOnExec;
361 // make sure this doesn't get messed with these since we didn't copy them
378 // FEATURE: Make sure fstat info is correct
379 // FEATURE: This could be faster if we did direct copies from each process' memory
380 // FEATURE: Check this logic one more time
381 public static class Pipe {
382 private final byte[] pipebuf = new byte[PIPE_BUF*4];
384 private int writePos;
386 public final FD reader = new Reader();
387 public final FD writer = new Writer();
389 public class Reader extends FD {
390 protected FStat _fstat() { return new FStat(); }
391 public int read(byte[] buf, int off, int len) throws ErrnoException {
392 if(len == 0) return 0;
393 synchronized(Pipe.this) {
394 while(writePos != -1 && readPos == writePos) {
395 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
397 if(writePos == -1) return 0; // eof
398 len = Math.min(len,writePos-readPos);
399 System.arraycopy(pipebuf,readPos,buf,off,len);
401 if(readPos == writePos) Pipe.this.notify();
405 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
408 public class Writer extends FD {
409 protected FStat _fstat() { return new FStat(); }
410 public int write(byte[] buf, int off, int len) throws ErrnoException {
411 if(len == 0) return 0;
412 synchronized(Pipe.this) {
413 if(readPos == -1) throw new ErrnoException(EPIPE);
414 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
415 // not enough space to atomicly write the data
416 while(readPos != -1 && readPos != writePos) {
417 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
419 if(readPos == -1) throw new ErrnoException(EPIPE);
420 readPos = writePos = 0;
422 len = Math.min(len,pipebuf.length - writePos);
423 System.arraycopy(buf,off,pipebuf,writePos,len);
424 if(readPos == writePos) Pipe.this.notify();
429 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
433 private int sys_pipe(int addr) {
434 Pipe pipe = new Pipe();
436 int fd1 = addFD(pipe.reader);
437 if(fd1 < 0) return -ENFILE;
438 int fd2 = addFD(pipe.writer);
439 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
443 memWrite(addr+4,fd2);
444 } catch(FaultException e) {
452 private int sys_dup2(int oldd, int newd) {
453 if(oldd == newd) return 0;
454 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
455 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
456 if(fds[oldd] == null) return -EBADFD;
457 if(fds[newd] != null) fds[newd].close();
458 fds[newd] = fds[oldd].dup();
462 private int sys_dup(int oldd) {
463 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
464 if(fds[oldd] == null) return -EBADFD;
465 FD fd = fds[oldd].dup();
466 int newd = addFD(fd);
467 if(newd < 0) { fd.close(); return -ENFILE; }
471 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
472 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
473 if(s == null) return -ENOENT;
477 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
478 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
479 if(s == null) return -ENOENT;
483 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
484 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
488 private int sys_unlink(int cstring) throws FaultException, ErrnoException {
489 gs.unlink(this,normalizePath(cstring(cstring)));
493 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
494 byte[] b = getBytes(cwd);
495 if(size == 0) return -EINVAL;
496 if(size < b.length+2) return -ERANGE;
498 copyout(b,addr+1,b.length);
499 memset(addr+b.length+1,0,1);
503 private int sys_chdir(int addr) throws ErrnoException, FaultException {
504 String path = normalizePath(cstring(addr));
505 //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
506 if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
508 //System.err.println("Now: [" + cwd + "]");
512 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
513 count = Math.min(count,MAX_CHUNK);
514 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
515 if(fds[fdn] == null) return -EBADFD;
516 byte[] buf = byteBuf(count);
517 int n = fds[fdn].getdents(buf,0,count);
522 // FEATURE: Run through the fork/wait stuff one more time
523 public static class GlobalState {
524 protected static final int OPEN = 1;
525 protected static final int STAT = 2;
526 protected static final int LSTAT = 3;
527 protected static final int MKDIR = 4;
528 protected static final int UNLINK = 5;
530 final UnixRuntime[] tasks;
533 private MP[] mps = new MP[0];
536 public GlobalState() { this(255); }
537 public GlobalState(int maxProcs) { this(maxProcs,true); }
538 public GlobalState(int maxProcs, boolean defaultMounts) {
539 tasks = new UnixRuntime[maxProcs+1];
541 addMount("/",new HostFS());
542 addMount("/dev",new DevFS());
546 private static class MP {
547 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
550 public int compareTo(Object o) {
551 if(!(o instanceof MP)) return 1;
552 return -path.compareTo(((MP)o).path);
556 public synchronized FS getMount(String path) {
557 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
558 if(path.equals("/")) return root;
559 path = path.substring(1);
560 for(int i=0;i<mps.length;i++)
561 if(mps[i].path.equals(path)) return mps[i].fs;
565 public synchronized void addMount(String path, FS fs) {
566 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
567 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
569 if(fs.owner != null) fs.owner.removeMount(fs);
572 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
573 path = path.substring(1);
574 int oldLength = mps.length;
575 MP[] newMPS = new MP[oldLength + 1];
576 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
577 newMPS[oldLength] = new MP(path,fs);
581 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
582 fs.devno = highdevno + 2;
585 public synchronized void removeMount(FS fs) {
586 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
587 throw new IllegalArgumentException("mount point doesn't exist");
590 public synchronized void removeMount(String path) {
591 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
592 if(path.equals("/")) {
595 path = path.substring(1);
597 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
598 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
603 private void removeMount(int index) {
604 if(index == -1) { root.owner = null; root = null; return; }
605 MP[] newMPS = new MP[mps.length - 1];
606 System.arraycopy(mps,0,newMPS,0,index);
607 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
611 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
612 int pl = normalizedPath.length();
615 synchronized(this) { list = mps; }
616 for(int i=0;i<list.length;i++) {
618 int mpl = mp.path.length();
619 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
620 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
623 return dispatch(root,op,r,normalizedPath,arg1,arg2);
626 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
628 case OPEN: return fs.open(r,path,arg1,arg2);
629 case STAT: return fs.stat(r,path);
630 case LSTAT: return fs.lstat(r,path);
631 case MKDIR: fs.mkdir(r,path,arg1); return null;
632 case UNLINK: fs.unlink(r,path); return null;
633 default: throw new Error("should never happen");
637 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
638 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
639 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
640 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
641 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
643 private Hashtable execCache = new Hashtable();
644 private static class CacheEnt {
645 public final long time;
646 public final long size;
647 public final Object o;
648 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
651 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
652 // FIXME: Hideous hack to make a standalone busybox possible
653 if(path.equals("bin/busybox") && r.getClass().getName().endsWith("BusyBox"))
655 FStat fstat = stat(r,path);
656 if(fstat == null) return null;
657 long mtime = fstat.mtime();
658 long size = fstat.size();
659 CacheEnt ent = (CacheEnt) execCache.get(path);
661 //System.err.println("Found cached entry for " + path);
662 if(ent.time == mtime && ent.size == size) return ent.o;
663 //System.err.println("Cache was out of date");
664 execCache.remove(path);
666 FD fd = open(r,path,RD_ONLY,0);
667 if(fd == null) return null;
668 Seekable s = fd.seekable();
670 String[] command = null;
672 if(s == null) throw new ErrnoException(EACCES);
673 byte[] buf = new byte[4096];
676 int n = s.read(buf,0,buf.length);
677 if(n == -1) throw new ErrnoException(ENOEXEC);
680 case '\177': // possible ELF
681 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
682 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
686 int n2 = s.read(buf,1,buf.length-1);
687 if(n2 == -1) throw new ErrnoException(ENOEXEC);
690 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
694 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
696 if(p == buf.length) break OUTER;
697 n = s.read(buf,p,buf.length-p);
699 command = new String[2];
701 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
704 while(arg < p && buf[arg] == ' ') arg++;
705 command[0] = new String(buf,2,cmdEnd);
706 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
708 command[0] = new String(buf,2,p-2);
710 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
713 throw new ErrnoException(ENOEXEC);
715 } catch(IOException e) {
717 throw new ErrnoException(EIO);
720 if(command == null) {
724 Class c = RuntimeCompiler.compile(s);
725 //System.err.println("Compile succeeded: " + c);
726 ent = new CacheEnt(mtime,size,c);
727 } catch(Compiler.Exn e) {
728 if(STDERR_DIAG) e.printStackTrace();
729 throw new ErrnoException(ENOEXEC);
730 } catch(IOException e) {
731 if(STDERR_DIAG) e.printStackTrace();
732 throw new ErrnoException(EIO);
735 ent = new CacheEnt(mtime,size,command);
740 execCache.put(path,ent);
745 public abstract static class FS {
749 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
751 // If this returns null it'll be truned into an ENOENT
752 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
753 // If this returns null it'll be turned into an ENOENT
754 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
755 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
756 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
759 // FEATURE: chroot support in here
760 private String normalizePath(String path) {
761 boolean absolute = path.startsWith("/");
762 int cwdl = cwd.length();
763 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
764 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
765 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
767 char[] in = new char[path.length()+1];
768 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
772 do { inp++; } while(in[inp] == '/');
773 } else if(cwdl != 0) {
774 cwd.getChars(0,cwdl,out,0);
778 path.getChars(0,path.length(),in,0);
779 while(in[inp] != 0) {
780 if(inp != 0 || cwdl==0) {
781 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
782 while(in[inp] == '/') inp++;
784 if(in[inp] == '\0') continue;
785 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
786 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
787 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
790 while(outp > 0 && out[outp] != '/') outp--;
791 //System.err.println("After ..: " + new String(out,0,outp));
798 if(outp > 0 && out[outp-1] == '/') outp--;
799 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
800 return new String(out,0,outp);
803 FStat hostFStat(final File f, Object data) {
806 FileInputStream fis = new FileInputStream(f);
808 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
809 case '#': e = fis.read() == '!';
812 } catch(IOException e2) { }
813 HostFS fs = (HostFS) data;
814 final int inode = fs.inodes.get(f.getAbsolutePath());
815 final int devno = fs.devno;
816 return new HostFStat(f,e) {
817 public int inode() { return inode; }
818 public int dev() { return devno; }
822 FD hostFSDirFD(File f, Object _fs) {
823 HostFS fs = (HostFS) _fs;
824 return fs.new HostDirFD(f);
827 public static class HostFS extends FS {
828 InodeCache inodes = new InodeCache(4000);
830 public File getRoot() { return root; }
832 private static File hostRootDir() {
833 if(getSystemProperty("nestedvm.root") != null) {
834 File f = new File(getSystemProperty("nestedvm.root"));
835 if(f.isDirectory()) return f;
836 // fall through to case below
838 String cwd = getSystemProperty("user.dir");
839 File f = new File(cwd != null ? cwd : ".");
840 if(!f.exists()) throw new Error("Couldn't get File for cwd");
841 f = new File(f.getAbsolutePath());
842 while(f.getParent() != null) f = new File(f.getParent());
846 private File hostFile(String path) {
847 char sep = File.separatorChar;
849 char buf[] = path.toCharArray();
850 for(int i=0;i<buf.length;i++) {
852 if(c == '/') buf[i] = sep;
853 else if(c == sep) buf[i] = '/';
855 path = new String(buf);
857 return new File(root,path);
860 public HostFS() { this(hostRootDir()); }
861 public HostFS(String root) { this(new File(root)); }
862 public HostFS(File root) { this.root = root; }
865 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
866 final File f = hostFile(path);
867 return r.hostFSOpen(f,flags,mode,this);
870 public void unlink(UnixRuntime r, String path) throws ErrnoException {
871 File f = hostFile(path);
872 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
873 if(!f.exists()) throw new ErrnoException(ENOENT);
874 if(!f.delete()) throw new ErrnoException(EPERM);
877 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
878 File f = hostFile(path);
879 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
880 if(!f.exists()) return null;
881 return r.hostFStat(f,this);
884 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
885 File f = hostFile(path);
886 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
887 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
888 if(f.exists()) throw new ErrnoException(ENOTDIR);
889 File parent = f.getParentFile();
890 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
891 if(!f.mkdir()) throw new ErrnoException(EIO);
894 public class HostDirFD extends DirFD {
895 private final File f;
896 private final File[] children;
897 public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
898 public int size() { return children.length; }
899 public String name(int n) { return children[n].getName(); }
900 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
901 public int parentInode() {
902 File parent = f.getParentFile();
903 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
905 public int myInode() { return inodes.get(f.getAbsolutePath()); }
906 public int myDev() { return devno; }
910 private static void putInt(byte[] buf, int off, int n) {
911 buf[off+0] = (byte)((n>>>24)&0xff);
912 buf[off+1] = (byte)((n>>>16)&0xff);
913 buf[off+2] = (byte)((n>>> 8)&0xff);
914 buf[off+3] = (byte)((n>>> 0)&0xff);
917 public static abstract class DirFD extends FD {
918 private int pos = -2;
920 protected abstract int size();
921 protected abstract String name(int n);
922 protected abstract int inode(int n);
923 protected abstract int myDev();
924 protected int parentInode() { return -1; }
925 protected int myInode() { return -1; }
927 public int getdents(byte[] buf, int off, int len) {
931 OUTER: for(;len > 0 && pos < size();pos++){
935 ino = pos == -1 ? parentInode() : myInode();
936 if(ino == -1) continue;
937 reclen = 9 + (pos == -1 ? 2 : 1);
938 if(reclen > len) break OUTER;
940 if(pos == -1) buf[off+9] = '.';
943 String f = name(pos);
944 byte[] fb = getBytes(f);
945 reclen = fb.length + 9;
946 if(reclen > len) break OUTER;
948 System.arraycopy(fb,0,buf,off+8,fb.length);
951 buf[off+reclen-1] = 0; // null terminate
952 reclen = (reclen + 3) & ~3; // add padding
953 putInt(buf,off,reclen);
954 putInt(buf,off+4,ino);
961 protected FStat _fstat() {
963 public int type() { return S_IFDIR; }
964 public int inode() { return myInode(); }
965 public int dev() { return myDev(); }
970 public static class DevFS extends FS {
971 private static final int ROOT_INODE = 1;
972 private static final int NULL_INODE = 2;
973 private static final int ZERO_INODE = 3;
974 private static final int FD_INODE = 4;
975 private static final int FD_INODES = 32;
977 private class DevFStat extends FStat {
978 public int dev() { return devno; }
979 public int mode() { return 0666; }
980 public int type() { return S_IFCHR; }
981 public int nlink() { return 1; }
984 private abstract class DevDirFD extends DirFD {
985 public int myDev() { return devno; }
988 private FD devZeroFD = new FD() {
989 public boolean readable() { return true; }
990 public boolean writable() { return true; }
991 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
992 public int write(byte[] a, int off, int length) { return length; }
993 public int seek(int n, int whence) { return 0; }
994 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
996 private FD devNullFD = new FD() {
997 public boolean readable() { return true; }
998 public boolean writable() { return true; }
999 public int read(byte[] a, int off, int length) { return 0; }
1000 public int write(byte[] a, int off, int length) { return length; }
1001 public int seek(int n, int whence) { return 0; }
1002 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1005 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1006 if(path.equals("null")) return devNullFD;
1007 if(path.equals("zero")) return devZeroFD;
1008 if(path.startsWith("fd/")) {
1011 n = Integer.parseInt(path.substring(4));
1012 } catch(NumberFormatException e) {
1015 if(n < 0 || n >= OPEN_MAX) return null;
1016 if(r.fds[n] == null) return null;
1017 return r.fds[n].dup();
1019 if(path.equals("fd")) {
1021 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1022 final int[] files = new int[count];
1024 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1025 return new DevDirFD() {
1026 public int myInode() { return FD_INODE; }
1027 public int parentInode() { return ROOT_INODE; }
1028 public int inode(int n) { return FD_INODES + n; }
1029 public String name(int n) { return Integer.toString(files[n]); }
1030 public int size() { return files.length; }
1033 if(path.equals("")) {
1034 return new DevDirFD() {
1035 public int myInode() { return ROOT_INODE; }
1036 // FEATURE: Get the real parent inode somehow
1037 public int parentInode() { return -1; }
1038 public int inode(int n) {
1040 case 0: return NULL_INODE;
1041 case 1: return ZERO_INODE;
1042 case 2: return FD_INODE;
1047 public String name(int n) {
1049 case 0: return "null";
1050 case 1: return "zero";
1051 case 2: return "fd";
1052 default: return null;
1055 public int size() { return 3; }
1061 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1062 if(path.equals("null")) return devNullFD.fstat();
1063 if(path.equals("zero")) return devZeroFD.fstat();
1064 if(path.startsWith("fd/")) {
1067 n = Integer.parseInt(path.substring(4));
1068 } catch(NumberFormatException e) {
1071 if(n < 0 || n >= OPEN_MAX) return null;
1072 if(r.fds[n] == null) return null;
1073 return r.fds[n].fstat();
1075 // FEATURE: inode stuff
1076 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1077 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1081 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1082 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }