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 if(tasks[pid] == null || tasks[pid].pid != pid) throw new Error("should never happen");
92 int nextPID = gs.nextPID;
93 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
94 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
95 if(newpid == -1) throw new ProcessTableFullExn();
97 gs.nextPID = newpid + 1;
103 int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
105 case SYS_kill: return sys_kill(a,b);
106 case SYS_fork: return sys_fork();
107 case SYS_pipe: return sys_pipe(a);
108 case SYS_dup2: return sys_dup2(a,b);
109 case SYS_dup: return sys_dup(a);
110 case SYS_waitpid: return sys_waitpid(a,b,c);
111 case SYS_stat: return sys_stat(a,b);
112 case SYS_lstat: return sys_lstat(a,b);
113 case SYS_mkdir: return sys_mkdir(a,b);
114 case SYS_getcwd: return sys_getcwd(a,b);
115 case SYS_chdir: return sys_chdir(a);
116 case SYS_exec: return sys_exec(a,b,c);
117 case SYS_getdents: return sys_getdents(a,b,c,d);
118 case SYS_unlink: return sys_unlink(a);
119 case SYS_getppid: return sys_getppid();
121 default: return super._syscall(syscall,a,b,c,d);
125 FD _open(String path, int flags, int mode) throws ErrnoException {
126 return gs.open(this,normalizePath(path),flags,mode);
129 private int sys_getppid() {
130 return parent == null ? 1 : parent.pid;
133 /** The kill syscall.
134 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
135 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
136 Anything else terminates the process. */
137 private int sys_kill(int pid, int signal) {
138 // This will only be called by raise() in newlib to invoke the default handler
139 // We don't have to worry about actually delivering the signal
140 if(pid != pid) return -ESRCH;
141 if(signal < 0 || signal >= 32) return -EINVAL;
156 return syscall(SYS_exit,128+signal,0,0,0);
161 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
162 final int WNOHANG = 1;
163 if((options & ~(WNOHANG)) != 0) return -EINVAL;
164 if(pid == 0 || pid < -1) {
165 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
168 boolean blocking = (options&WNOHANG)==0;
170 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
171 if(children == null) return blocking ? -ECHILD : 0;
173 UnixRuntime done = null;
175 synchronized(children) {
178 if(exitedChildren.size() > 0) done = (UnixRuntime)exitedChildren.remove(exitedChildren.size() - 1);
180 UnixRuntime t = gs.tasks[pid];
181 if(t.parent != this) return -ECHILD;
182 if(t.state == EXITED) {
183 if(!exitedChildren.remove(t)) throw new Error("should never happen");
187 // process group stuff, EINVAL returned above
188 throw new Error("should never happen");
191 if(!blocking) return 0;
192 try { children.wait(); } catch(InterruptedException e) {}
193 //System.err.println("waitpid woke up: " + exitedChildren.size());
195 gs.tasks[done.pid] = null;
200 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
206 if(children != null) synchronized(children) {
207 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
208 UnixRuntime child = (UnixRuntime) e.nextElement();
209 gs.tasks[child.pid] = null;
211 exitedChildren.clear();
212 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
213 UnixRuntime child = (UnixRuntime) e.nextElement();
216 activeChildren.clear();
219 UnixRuntime _parent = parent;
220 if(_parent == null) {
221 gs.tasks[pid] = null;
223 synchronized(_parent.children) {
225 gs.tasks[pid] = null;
227 parent.activeChildren.remove(this);
228 parent.exitedChildren.add(this);
229 parent.children.notify();
235 protected Object clone() throws CloneNotSupportedException {
236 UnixRuntime r = (UnixRuntime) super.clone();
240 r.activeChildren = r.exitedChildren = null;
244 private int sys_fork() {
245 CPUState state = new CPUState();
247 int sp = state.r[SP];
251 r = (UnixRuntime) clone();
252 } catch(Exception e) {
261 } catch(ProcessTableFullExn e) {
265 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
266 if(children == null) {
267 children = new Object();
268 activeChildren = new Vector();
269 exitedChildren = new Vector();
271 activeChildren.add(r);
273 state.r[V0] = 0; // return 0 to child
274 state.pc += 4; // skip over syscall instruction
275 r.setCPUState(state);
278 new ForkedProcess(r);
283 public static final class ForkedProcess extends Thread {
284 private final UnixRuntime initial;
285 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
286 public void run() { UnixRuntime.executeAndExec(initial); }
289 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
290 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
292 public static int executeAndExec(UnixRuntime r) {
295 if(r.execute()) break;
296 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
298 if(r.state != EXECED) return r.exitStatus();
303 private String[] readStringArray(int addr) throws ReadFaultException {
305 for(int p=addr;memRead(p) != 0;p+=4) count++;
306 String[] a = new String[count];
307 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
311 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
312 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
315 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
316 if(argv.length == 0) argv = new String[]{""};
318 // NOTE: For this little hack to work nestedvm.root MUST be "."
320 System.err.println("Execing normalized path: " + normalizedPath);
321 if(true) return exec(new Interpreter(normalizedPath),argv,envp);
322 } catch(IOException e) { throw new Error(e); }*/
324 Object o = gs.exec(this,normalizedPath);
325 if(o == null) return -ENOENT;
327 if(o instanceof Class) {
330 return exec((UnixRuntime) c.newInstance(),argv,envp);
331 } catch(Exception e) {
336 String[] command = (String[]) o;
337 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
338 int p = command[0].lastIndexOf('/');
339 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
341 if(command[1] != null) newArgv[p++] = command[1];
342 newArgv[p++] = "/" + normalizedPath;
343 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
344 return exec(command[0],newArgv,envp);
348 private int exec(UnixRuntime r, String[] argv, String[] envp) {
350 //System.err.println("Execing " + r);
351 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
353 r.closeOnExec = closeOnExec;
354 // make sure this doesn't get messed with these since we didn't copy them
371 // FEATURE: Make sure fstat info is correct
372 // FEATURE: This could be faster if we did direct copies from each process' memory
373 // FEATURE: Check this logic one more time
374 public static class Pipe {
375 private final byte[] pipebuf = new byte[PIPE_BUF*4];
377 private int writePos;
379 public final FD reader = new Reader();
380 public final FD writer = new Writer();
382 public class Reader extends FD {
383 protected FStat _fstat() { return new FStat(); }
384 public int read(byte[] buf, int off, int len) throws ErrnoException {
385 if(len == 0) return 0;
386 synchronized(Pipe.this) {
387 while(writePos != -1 && readPos == writePos) {
388 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
390 if(writePos == -1) return 0; // eof
391 len = Math.min(len,writePos-readPos);
392 System.arraycopy(pipebuf,readPos,buf,off,len);
394 if(readPos == writePos) Pipe.this.notify();
398 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
401 public class Writer extends FD {
402 protected FStat _fstat() { return new FStat(); }
403 public int write(byte[] buf, int off, int len) throws ErrnoException {
404 if(len == 0) return 0;
405 synchronized(Pipe.this) {
406 if(readPos == -1) throw new ErrnoException(EPIPE);
407 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
408 // not enough space to atomicly write the data
409 while(readPos != -1 && readPos != writePos) {
410 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
412 if(readPos == -1) throw new ErrnoException(EPIPE);
413 readPos = writePos = 0;
415 len = Math.min(len,pipebuf.length - writePos);
416 System.arraycopy(buf,off,pipebuf,writePos,len);
417 if(readPos == writePos) Pipe.this.notify();
422 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
426 private int sys_pipe(int addr) {
427 Pipe pipe = new Pipe();
429 int fd1 = addFD(pipe.reader);
430 if(fd1 < 0) return -ENFILE;
431 int fd2 = addFD(pipe.writer);
432 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
436 memWrite(addr+4,fd2);
437 } catch(FaultException e) {
445 private int sys_dup2(int oldd, int newd) {
446 if(oldd == newd) return 0;
447 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
448 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
449 if(fds[oldd] == null) return -EBADFD;
450 if(fds[newd] != null) fds[newd].close();
451 fds[newd] = fds[oldd].dup();
455 private int sys_dup(int oldd) {
456 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
457 if(fds[oldd] == null) return -EBADFD;
458 FD fd = fds[oldd].dup();
459 int newd = addFD(fd);
460 if(newd < 0) { fd.close(); return -ENFILE; }
464 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
465 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
466 if(s == null) return -ENOENT;
470 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
471 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
472 if(s == null) return -ENOENT;
476 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
477 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
481 private int sys_unlink(int cstring) throws FaultException, ErrnoException {
482 gs.unlink(this,normalizePath(cstring(cstring)));
486 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
487 byte[] b = getBytes(cwd);
488 if(size == 0) return -EINVAL;
489 if(size < b.length+2) return -ERANGE;
491 copyout(b,addr+1,b.length);
492 memset(addr+b.length+1,0,1);
496 private int sys_chdir(int addr) throws ErrnoException, FaultException {
497 String path = normalizePath(cstring(addr));
498 //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
499 if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
501 //System.err.println("Now: [" + cwd + "]");
505 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
506 count = Math.min(count,MAX_CHUNK);
507 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
508 if(fds[fdn] == null) return -EBADFD;
509 byte[] buf = byteBuf(count);
510 int n = fds[fdn].getdents(buf,0,count);
515 // FEATURE: Run through the fork/wait stuff one more time
516 public static class GlobalState {
517 protected static final int OPEN = 1;
518 protected static final int STAT = 2;
519 protected static final int LSTAT = 3;
520 protected static final int MKDIR = 4;
521 protected static final int UNLINK = 5;
523 final UnixRuntime[] tasks;
526 private MP[] mps = new MP[0];
529 public GlobalState() { this(255); }
530 public GlobalState(int maxProcs) { this(maxProcs,true); }
531 public GlobalState(int maxProcs, boolean defaultMounts) {
532 tasks = new UnixRuntime[maxProcs+1];
534 addMount("/",new HostFS());
535 addMount("/dev",new DevFS());
539 private static class MP {
540 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
543 public int compareTo(Object o) {
544 if(!(o instanceof MP)) return 1;
545 return -path.compareTo(((MP)o).path);
549 public synchronized FS getMount(String path) {
550 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
551 if(path.equals("/")) return root;
552 path = path.substring(1);
553 for(int i=0;i<mps.length;i++)
554 if(mps[i].path.equals(path)) return mps[i].fs;
558 public synchronized void addMount(String path, FS fs) {
559 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
560 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
562 if(fs.owner != null) fs.owner.removeMount(fs);
565 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
566 path = path.substring(1);
567 int oldLength = mps.length;
568 MP[] newMPS = new MP[oldLength + 1];
569 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
570 newMPS[oldLength] = new MP(path,fs);
574 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
575 fs.devno = highdevno + 2;
578 public synchronized void removeMount(FS fs) {
579 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
580 throw new IllegalArgumentException("mount point doesn't exist");
583 public synchronized void removeMount(String path) {
584 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
585 if(path.equals("/")) {
588 path = path.substring(1);
590 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
591 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
596 private void removeMount(int index) {
597 if(index == -1) { root.owner = null; root = null; return; }
598 MP[] newMPS = new MP[mps.length - 1];
599 System.arraycopy(mps,0,newMPS,0,index);
600 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
604 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
605 int pl = normalizedPath.length();
608 synchronized(this) { list = mps; }
609 for(int i=0;i<list.length;i++) {
611 int mpl = mp.path.length();
612 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
613 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
616 return dispatch(root,op,r,normalizedPath,arg1,arg2);
619 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
621 case OPEN: return fs.open(r,path,arg1,arg2);
622 case STAT: return fs.stat(r,path);
623 case LSTAT: return fs.lstat(r,path);
624 case MKDIR: fs.mkdir(r,path,arg1); return null;
625 case UNLINK: fs.unlink(r,path); return null;
626 default: throw new Error("should never happen");
630 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
631 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
632 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
633 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
634 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(UNLINK,r,path,0,0); }
636 private Hashtable execCache = new Hashtable();
637 private static class CacheEnt {
638 public final long time;
639 public final long size;
640 public final Object o;
641 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
644 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
645 FStat fstat = stat(r,path);
646 if(fstat == null) return null;
647 long mtime = fstat.mtime();
648 long size = fstat.size();
649 CacheEnt ent = (CacheEnt) execCache.get(path);
651 //System.err.println("Found cached entry for " + path);
652 if(ent.time == mtime && ent.size == size) return ent.o;
653 //System.err.println("Cache was out of date");
654 execCache.remove(path);
656 FD fd = open(r,path,RD_ONLY,0);
657 if(fd == null) return null;
658 Seekable s = fd.seekable();
660 String[] command = null;
662 if(s == null) throw new ErrnoException(EACCES);
663 byte[] buf = new byte[4096];
666 int n = s.read(buf,0,buf.length);
667 if(n == -1) throw new ErrnoException(ENOEXEC);
670 case '\177': // possible ELF
671 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
672 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
676 int n2 = s.read(buf,1,buf.length-1);
677 if(n2 == -1) throw new ErrnoException(ENOEXEC);
680 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
684 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
686 if(p == buf.length) break OUTER;
687 n = s.read(buf,p,buf.length-p);
689 command = new String[2];
691 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
694 while(arg < p && buf[arg] == ' ') arg++;
695 command[0] = new String(buf,2,cmdEnd);
696 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
698 command[0] = new String(buf,2,p-2);
700 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
703 throw new ErrnoException(ENOEXEC);
705 } catch(IOException e) {
707 throw new ErrnoException(EIO);
710 if(command == null) {
714 Class c = RuntimeCompiler.compile(s);
715 //System.err.println("Compile succeeded: " + c);
716 ent = new CacheEnt(mtime,size,c);
717 } catch(Compiler.Exn e) {
718 if(STDERR_DIAG) e.printStackTrace();
719 throw new ErrnoException(ENOEXEC);
720 } catch(IOException e) {
721 if(STDERR_DIAG) e.printStackTrace();
722 throw new ErrnoException(EIO);
725 ent = new CacheEnt(mtime,size,command);
730 execCache.put(path,ent);
735 public abstract static class FS {
739 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
741 // If this returns null it'll be truned into an ENOENT
742 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
743 // If this returns null it'll be turned into an ENOENT
744 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
745 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
746 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
749 // FEATURE: chroot support in here
750 private String normalizePath(String path) {
751 boolean absolute = path.startsWith("/");
752 int cwdl = cwd.length();
753 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
754 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
755 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
757 char[] in = new char[path.length()+1];
758 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
762 do { inp++; } while(in[inp] == '/');
763 } else if(cwdl != 0) {
764 cwd.getChars(0,cwdl,out,0);
768 path.getChars(0,path.length(),in,0);
769 while(in[inp] != 0) {
770 if(inp != 0 || cwdl==0) {
771 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
772 while(in[inp] == '/') inp++;
774 if(in[inp] == '\0') continue;
775 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
776 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
777 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
780 while(outp > 0 && out[outp] != '/') outp--;
781 //System.err.println("After ..: " + new String(out,0,outp));
788 if(outp > 0 && out[outp-1] == '/') outp--;
789 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
790 return new String(out,0,outp);
793 FStat hostFStat(final File f, Object data) {
796 FileInputStream fis = new FileInputStream(f);
798 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
799 case '#': e = fis.read() == '!';
802 } catch(IOException e2) { }
803 HostFS fs = (HostFS) data;
804 final int inode = fs.inodes.get(f.getAbsolutePath());
805 final int devno = fs.devno;
806 return new HostFStat(f,e) {
807 public int inode() { return inode; }
808 public int dev() { return devno; }
812 FD hostFSDirFD(File f, Object _fs) {
813 HostFS fs = (HostFS) _fs;
814 return fs.new HostDirFD(f);
817 public static class HostFS extends FS {
818 InodeCache inodes = new InodeCache(4000);
820 public File getRoot() { return root; }
822 private static File hostRootDir() {
823 if(getSystemProperty("nestedvm.root") != null) {
824 File f = new File(getSystemProperty("nestedvm.root"));
825 if(f.isDirectory()) return f;
826 // fall through to case below
828 String cwd = getSystemProperty("user.dir");
829 File f = new File(cwd != null ? cwd : ".");
830 if(!f.exists()) throw new Error("Couldn't get File for cwd");
831 f = new File(f.getAbsolutePath());
832 while(f.getParent() != null) f = new File(f.getParent());
836 private File hostFile(String path) {
837 char sep = File.separatorChar;
839 char buf[] = path.toCharArray();
840 for(int i=0;i<buf.length;i++) {
842 if(c == '/') buf[i] = sep;
843 else if(c == sep) buf[i] = '/';
845 path = new String(buf);
847 return new File(root,path);
850 public HostFS() { this(hostRootDir()); }
851 public HostFS(String root) { this(new File(root)); }
852 public HostFS(File root) { this.root = root; }
855 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
856 final File f = hostFile(path);
857 return r.hostFSOpen(f,flags,mode,this);
860 public void unlink(UnixRuntime r, String path) throws ErrnoException {
861 File f = hostFile(path);
862 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
863 if(!f.exists()) throw new ErrnoException(ENOENT);
864 if(!f.delete()) throw new ErrnoException(EPERM);
867 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
868 File f = hostFile(path);
869 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
870 if(!f.exists()) return null;
871 return r.hostFStat(f,this);
874 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
875 File f = hostFile(path);
876 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
877 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
878 if(f.exists()) throw new ErrnoException(ENOTDIR);
879 File parent = f.getParentFile();
880 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
881 if(!f.mkdir()) throw new ErrnoException(EIO);
884 public class HostDirFD extends DirFD {
885 private final File f;
886 private final File[] children;
887 public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
888 public int size() { return children.length; }
889 public String name(int n) { return children[n].getName(); }
890 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
891 public int parentInode() {
892 File parent = f.getParentFile();
893 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
895 public int myInode() { return inodes.get(f.getAbsolutePath()); }
896 public int myDev() { return devno; }
900 private static void putInt(byte[] buf, int off, int n) {
901 buf[off+0] = (byte)((n>>>24)&0xff);
902 buf[off+1] = (byte)((n>>>16)&0xff);
903 buf[off+2] = (byte)((n>>> 8)&0xff);
904 buf[off+3] = (byte)((n>>> 0)&0xff);
907 public static abstract class DirFD extends FD {
908 private int pos = -2;
910 protected abstract int size();
911 protected abstract String name(int n);
912 protected abstract int inode(int n);
913 protected abstract int myDev();
914 protected int parentInode() { return -1; }
915 protected int myInode() { return -1; }
917 public int getdents(byte[] buf, int off, int len) {
921 OUTER: for(;len > 0 && pos < size();pos++){
925 ino = pos == -1 ? parentInode() : myInode();
926 if(ino == -1) continue;
927 reclen = 9 + (pos == -1 ? 2 : 1);
928 if(reclen > len) break OUTER;
930 if(pos == -1) buf[off+9] = '.';
933 String f = name(pos);
934 byte[] fb = getBytes(f);
935 reclen = fb.length + 9;
936 if(reclen > len) break OUTER;
938 System.arraycopy(fb,0,buf,off+8,fb.length);
941 buf[off+reclen-1] = 0; // null terminate
942 reclen = (reclen + 3) & ~3; // add padding
943 putInt(buf,off,reclen);
944 putInt(buf,off+4,ino);
951 protected FStat _fstat() {
953 public int type() { return S_IFDIR; }
954 public int inode() { return myInode(); }
955 public int dev() { return myDev(); }
960 public static class DevFS extends FS {
961 private static final int ROOT_INODE = 1;
962 private static final int NULL_INODE = 2;
963 private static final int ZERO_INODE = 3;
964 private static final int FD_INODE = 4;
965 private static final int FD_INODES = 32;
967 private class DevFStat extends FStat {
968 public int dev() { return devno; }
969 public int mode() { return 0666; }
970 public int type() { return S_IFCHR; }
971 public int nlink() { return 1; }
974 private abstract class DevDirFD extends DirFD {
975 public int myDev() { return devno; }
978 private FD devZeroFD = new FD() {
979 public boolean readable() { return true; }
980 public boolean writable() { return true; }
981 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
982 public int write(byte[] a, int off, int length) { return length; }
983 public int seek(int n, int whence) { return 0; }
984 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
986 private FD devNullFD = new FD() {
987 public boolean readable() { return true; }
988 public boolean writable() { return true; }
989 public int read(byte[] a, int off, int length) { return 0; }
990 public int write(byte[] a, int off, int length) { return length; }
991 public int seek(int n, int whence) { return 0; }
992 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
995 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
996 if(path.equals("null")) return devNullFD;
997 if(path.equals("zero")) return devZeroFD;
998 if(path.startsWith("fd/")) {
1001 n = Integer.parseInt(path.substring(4));
1002 } catch(NumberFormatException e) {
1005 if(n < 0 || n >= OPEN_MAX) return null;
1006 if(r.fds[n] == null) return null;
1007 return r.fds[n].dup();
1009 if(path.equals("fd")) {
1011 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1012 final int[] files = new int[count];
1014 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1015 return new DevDirFD() {
1016 public int myInode() { return FD_INODE; }
1017 public int parentInode() { return ROOT_INODE; }
1018 public int inode(int n) { return FD_INODES + n; }
1019 public String name(int n) { return Integer.toString(files[n]); }
1020 public int size() { return files.length; }
1023 if(path.equals("")) {
1024 return new DevDirFD() {
1025 public int myInode() { return ROOT_INODE; }
1026 // FEATURE: Get the real parent inode somehow
1027 public int parentInode() { return -1; }
1028 public int inode(int n) {
1030 case 0: return NULL_INODE;
1031 case 1: return ZERO_INODE;
1032 case 2: return FD_INODE;
1037 public String name(int n) {
1039 case 0: return "null";
1040 case 1: return "zero";
1041 case 2: return "fd";
1042 default: return null;
1045 public int size() { return 3; }
1051 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1052 if(path.equals("null")) return devNullFD.fstat();
1053 if(path.equals("zero")) return devZeroFD.fstat();
1054 if(path.startsWith("fd/")) {
1057 n = Integer.parseInt(path.substring(4));
1058 } catch(NumberFormatException e) {
1061 if(n < 0 || n >= OPEN_MAX) return null;
1062 if(r.fds[n] == null) return null;
1063 return r.fds[n].fstat();
1065 // FEATURE: inode stuff
1066 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1067 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1071 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1072 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }