more preliminary exec() stuff
[nestedvm.git] / src / org / ibex / nestedvm / UnixRuntime.java
index 3befb91..5b47219 100644 (file)
@@ -4,7 +4,13 @@ import org.ibex.nestedvm.util.*;
 import java.io.*;
 import java.util.*;
 
-public abstract class UnixRuntime extends Runtime {
+// FEATURE: BusyBox's ASH doesn't like \r\n at the end of lines
+// is ash just broken or are many apps like this? if so workaround in nestedvm
+
+// FEATURE: Throw ErrnoException and catch in syscall whereever possible 
+// (only in cases where we've already paid the price for a throw)
+
+public abstract class UnixRuntime extends Runtime implements Cloneable {
     /** The pid of this "process" */
     private int pid;
     private int ppid;
@@ -14,13 +20,17 @@ public abstract class UnixRuntime extends Runtime {
     private FS fs;
     public FS getFS() { return fs; }
     public void setFS(FS fs) {
-        if(state >= RUNNING) throw new IllegalStateException("Can't change fs while process is running");
+        if(state != STOPPED) throw new IllegalStateException("Can't change fs while process is running");
         this.fs = fs;
     }
     
-    /** proceses current working directory */
+    /** proceses' current working directory - absolute path WITHOUT leading slash
+        "" = root, "bin" = /bin "usr/bin" = /usr/bin */
     private String cwd;
     
+    /** The runtime that should be run next when in state == EXECED */
+    private UnixRuntime execedRuntime;
+    
     /* Static stuff */
     // FEATURE: Most of this is O(n) or worse - fix it
     private final Object waitNotification = new Object();
@@ -45,19 +55,18 @@ public abstract class UnixRuntime extends Runtime {
         }
     }
     
-    public UnixRuntime(int pageSize, int totalPages, boolean allowEmptyPages) {
-        super(pageSize,totalPages,allowEmptyPages);
+    public UnixRuntime(int pageSize, int totalPages) {
+        super(pageSize,totalPages);
         
-        HostFS root = new HostFS();
-        fs = new UnixOverlayFS(root);
+        FS root = new HostFS();
+        FS dev = new DevFS();
+        MountPointFS mounts = new MountPointFS(root);
+        mounts.add("/dev",dev);
+        fs = mounts;
         
-        String dir = root.hostCWD();
-        try {
-            chdir(dir == null ? "/" : dir);
-        } catch(FileNotFoundException e) {
-            e.printStackTrace();
-            cwd = "/";
-        }
+        // FEATURE: Do the proper mangling for non-unix hosts
+        String userdir = getSystemProperty("user.dir");
+        cwd = userdir != null && userdir.startsWith("/") && File.separatorChar == '/'  ? userdir.substring(1) : "";
     }
     
     // NOTE: getDisplayName() is a Java2 function
@@ -108,11 +117,11 @@ public abstract class UnixRuntime extends Runtime {
             if(ppid == 0) removeTask(this);
             for(int i=0;i<MAX_TASKS;i++) {
                 if(tasks[i] != null && tasks[i].ppid == pid) {
-                    if(tasks[i].state == DONE) removeTask(tasks[i]);
+                    if(tasks[i].state == EXITED) removeTask(tasks[i]);
                     else tasks[i].ppid = 0;
                 }
             }
-            state = DONE;
+            state = EXITED;
             if(ppid != 0) synchronized(tasks[ppid].waitNotification) { tasks[ppid].waitNotification.notify(); }
         }
     }
@@ -128,12 +137,15 @@ public abstract class UnixRuntime extends Runtime {
             case SYS_mkdir: return sys_mkdir(a,b);
             case SYS_getcwd: return sys_getcwd(a,b);
             case SYS_chdir: return sys_chdir(a);
+            case SYS_execve: return sys_execve(a,b,c);
 
             default: return super.syscall(syscall,a,b,c,d);
         }
     }
     
-    protected FD open(String path, int flags, int mode) throws IOException { return fs.open(cleanupPath(path),flags,mode); }
+    protected FD open(String path, int flags, int mode) throws IOException {
+        return fs.open(normalizePath(path),flags,mode);
+    }
 
     // FEATURE: Allow simple, broken signal delivery to other processes 
     // (check if a signal was delivered before and after syscalls)
@@ -160,20 +172,8 @@ public abstract class UnixRuntime extends Runtime {
             case 23: // SIGIO
             case 28: // SIGWINCH
                 break;
-            default: {
-                String msg = "Terminating on signal: " + signal + "\n";
-                exitStatus = 1;
-                state = DONE;
-                if(fds[2]==null) {
-                    System.out.print(msg);
-                } else {
-                    try {
-                        byte[] b = getBytes(msg); 
-                        fds[2].write(b,0,b.length);
-                    }
-                    catch(IOException e) { /* ignore */ }
-                }
-            }
+            default:
+                return syscall(SYS_exit,128+signal,0,0,0);
         }
         return 0;
     }
@@ -187,12 +187,12 @@ public abstract class UnixRuntime extends Runtime {
                 UnixRuntime task = null;
                 if(pid == -1) {
                     for(int i=0;i<MAX_TASKS;i++) {
-                        if(tasks[i] != null && tasks[i].ppid == this.pid && tasks[i].state == DONE) {
+                        if(tasks[i] != null && tasks[i].ppid == this.pid && tasks[i].state == EXITED) {
                             task = tasks[i];
                             break;
                         }
                     }
-                } else if(tasks[pid] != null && tasks[pid].ppid == this.pid && tasks[pid].state == DONE) {
+                } else if(tasks[pid] != null && tasks[pid].ppid == this.pid && tasks[pid].state == EXITED) {
                     task = tasks[pid];
                 }
                 
@@ -214,40 +214,32 @@ public abstract class UnixRuntime extends Runtime {
         }
     }
     
-    // Great ugliness lies within.....
+    protected Object clone() throws CloneNotSupportedException {
+           UnixRuntime r = (UnixRuntime) super.clone();
+        r.pid = r.ppid = 0;
+        return r;
+    }
+
     private int sys_fork() {
-        CPUState state = getCPUState();
+        CPUState state = new CPUState();
+        getCPUState(state);
         int sp = state.r[SP];
         final UnixRuntime r;
+        
         try {
-            r = (UnixRuntime) getClass().newInstance();
+            r = (UnixRuntime) clone();
         } catch(Exception e) {
-            System.err.println(e);
+            e.printStackTrace();
             return -ENOMEM;
         }
-        int child_pid = addTask(r);
-        if(child_pid < 0) return -ENOMEM;
+        
+        int childPID = addTask(r);
+        if(childPID < 0) return -ENOMEM;
         
         r.ppid = pid;
-        r.brkAddr = brkAddr;
-        r.fds = new FD[OPEN_MAX];
-        for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) r.fds[i] = fds[i].dup();
-        r.cwd = cwd;
-        r.fs = fs;
-        for(int i=0;i<TOTAL_PAGES;i++) {
-            if(readPages[i] == null) continue;
-            if(isEmptyPage(writePages[i])) {
-                r.readPages[i] = r.writePages[i] = writePages[i];
-            } else if(writePages[i] != null) {
-                r.readPages[i] = r.writePages[i] = new int[PAGE_WORDS];
-                if(STACK_BOTTOM == 0 || i*PAGE_SIZE < STACK_BOTTOM || i*PAGE_SIZE >= sp-PAGE_SIZE*2)
-                    System.arraycopy(writePages[i],0,r.writePages[i],0,PAGE_WORDS);
-            } else {
-                r.readPages[i] = r.readPages[i];
-            }
-        }
-        state.r[V0] = 0;
-        state.pc += 4;
+        
+        state.r[V0] = 0; // return 0 to child
+        state.pc += 4; // skip over syscall instruction
         r.setCPUState(state);
         r.state = PAUSED;
         
@@ -262,9 +254,118 @@ public abstract class UnixRuntime extends Runtime {
             }
         }.start();
         
-        return child_pid;        
+        return childPID;
     }
-            
+    
+    public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
+    public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
+    
+    public static int executeAndExec(UnixRuntime r) {
+           for(;;) {
+            for(;;) {
+                if(r.execute()) break;
+                System.err.println("WARNING: Pause requested while executing runAndExec()");
+            }
+            if(r.state != EXECED) return r.exitStatus();
+            r = r.execedRuntime;
+        }
+    }
+     
+    private String[] readStringArray(int addr) throws ReadFaultException {
+           int count = 0;
+        for(int p=addr;memRead(p) != 0;p+=4) count++;
+        String[] a = new String[count];
+        for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
+        return a;
+    }
+    
+    // FEATURE: call the syscall just "exec"
+    private int sys_execve(int cpath, int cargv, int cenvp) {
+        try {
+                   return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
+        } catch(FaultException e) {
+            return -EFAULT;
+        }
+    }
+    
+    private int exec(String path, String[] argv, String[] envp) {
+        if(argv.length == 0) argv = new String[]{""};
+        Seekable s;
+        FD fd;
+        
+        try {
+            fd = fs.open(path,RD_ONLY,0);
+            System.err.println(fd + "  " + path);
+            if(fd == null) return -ENOENT;
+            s = fd.seekable();
+            if(s == null) return -ENOEXEC;
+        }
+        catch(ErrnoException e) { return -e.errno; }
+        catch(FileNotFoundException e) {
+            if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
+            return -ENOENT;
+        }
+        catch(IOException e) { return -EIO; }
+        
+        try {
+            int p = 0;
+            byte[] buf = new byte[4096];
+            OUTER: for(;;) {
+                   int n = s.read(buf,p,buf.length-p);
+                if(n == -1) break;
+                for(;n > 0; n--) if(buf[p++] == '\n' || p == 4096) break OUTER;
+            }
+            if(buf[0] == '!' && buf[1] == '#') {
+                   String cmd = new String(buf,2,p-2);
+                String argv1 = null;
+                if((p = cmd.indexOf(' ')) != -1) {
+                    do { p++; } while(cmd.charAt(p)==' ');
+                           argv1 = cmd.substring(p);
+                    cmd = cmd.substring(0,p-1);
+                }
+                String[] newArgv = new String[argv.length + argv1 != null ? 2 : 1];
+                p = 0;
+                newArgv[p++] = argv[0];
+                if(argv1 != null) newArgv[p++] = argv1;
+                newArgv[p++] = path;
+                for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
+                fd.close();
+                return exec(cmd,newArgv,envp);
+            } else if(buf[0] == '\177' && buf[1] == 'E' && buf[2] == 'L' && buf[3] == 'F') {
+                s.seek(0);
+                   UnixRuntime r = new Interpreter(s);
+                fd.close();
+                return exec(r,argv,envp);
+            } else {
+                   return -ENOEXEC;
+            }
+        } catch(IOException e) {
+                   e.printStackTrace();
+            return -ENOEXEC;
+        }
+    }
+    
+    private int exec(UnixRuntime r, String[] argv, String[] envp) {        
+        for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
+        r.fds = fds;
+        r.closeOnExec = closeOnExec;
+        // make sure this doesn't get messed with these since we didn't copy them
+        fds = null;
+        closeOnExec = null;
+        
+        r.cwd = cwd;
+        r.fs = fs;
+        r.pid = pid;
+        r.ppid = ppid;
+        r.start(argv,envp);
+        
+        state = EXECED;
+        execedRuntime = r;
+        
+        return 0;   
+    }
+    
+    // FEATURE: Use custom PipeFD - be sure to support PIPE_BUF of data
     private int sys_pipe(int addr) {
         PipedOutputStream writerStream = new PipedOutputStream();
         PipedInputStream readerStream;
@@ -302,7 +403,7 @@ public abstract class UnixRuntime extends Runtime {
     
     private int sys_stat(int cstring, int addr) {
         try {
-            String path = cleanupPath(cstring(cstring));
+            String path = normalizePath(cstring(cstring));
             return stat(fs.stat(path),addr);
         }
         catch(ErrnoException e) { return -e.errno; }
@@ -317,7 +418,7 @@ public abstract class UnixRuntime extends Runtime {
     
     private int sys_mkdir(int cstring, int mode) {
         try {
-            fs.mkdir(cleanupPath(cstring(cstring)));
+            fs.mkdir(normalizePath(cstring(cstring)));
             return 0;
         }
         catch(ErrnoException e) { return -e.errno; }
@@ -330,10 +431,10 @@ public abstract class UnixRuntime extends Runtime {
     private int sys_getcwd(int addr, int size) {
         byte[] b = getBytes(cwd);
         if(size == 0) return -EINVAL;
-        if(size < b.length+1) return -ERANGE;
-        if(!new File(cwd).exists()) return -ENOENT;
+        if(size < b.length+2) return -ERANGE;
         try {
-            copyout(b,addr,b.length);
+            memset(addr,'/',1);
+            copyout(b,addr+1,b.length);
             memset(addr+b.length+1,0,1);
             return addr;
         } catch(FaultException e) {
@@ -343,11 +444,11 @@ public abstract class UnixRuntime extends Runtime {
     
     private int sys_chdir(int addr) {
         try {
-            String path = cleanupPath(cstring(addr));
+            String path = normalizePath(cstring(addr));
             System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
             if(fs.stat(path).type() != FStat.S_IFDIR) return -ENOTDIR;
             cwd = path;
-            System.err.println("Now: " + cwd);
+            System.err.println("Now: [" + cwd + "]");
             return 0;
         }
         catch(ErrnoException e) { return -e.errno; }
@@ -357,9 +458,9 @@ public abstract class UnixRuntime extends Runtime {
     }
 
     public void chdir(String dir) throws FileNotFoundException {
-        if(state >= RUNNING) throw new IllegalStateException("Can't chdir while process is running");
+        if(state != STOPPED) throw new IllegalStateException("Can't chdir while process is running");
         try {
-            dir = cleanupPath(dir);
+            dir = normalizePath(dir);
             if(fs.stat(dir).type() != FStat.S_IFDIR) throw new FileNotFoundException();
         } catch(IOException e) {
             throw new FileNotFoundException();
@@ -368,11 +469,31 @@ public abstract class UnixRuntime extends Runtime {
     }
         
     public abstract static class FS {
-        public FD open(String path, int flags, int mode) throws IOException { throw new FileNotFoundException(); }
-        public FStat stat(String path) throws IOException { throw new FileNotFoundException(); }
-        public void mkdir(String path) throws IOException { throw new ErrnoException(ENOTDIR); }
+        protected FD _open(String path, int flags, int mode) throws IOException { return null; }
+        protected FStat _stat(String path) throws IOException { return null; }
+        protected void _mkdir(String path) throws IOException { throw new ErrnoException(EROFS); }
+        
+        protected static final int OPEN = 1;
+        protected static final int STAT = 2;
+        protected static final int MKDIR = 3;
         
-        public static FD directoryFD(String[] files, int hashCode) throws IOException {
+        protected Object op(int op, String path, int arg1, int arg2) throws IOException {
+                       switch(op) {
+                               case OPEN: return _open(path,arg1,arg2);
+                               case STAT: return _stat(path);
+                               case MKDIR: _mkdir(path); return null;
+                               default: throw new IllegalArgumentException("Unknown FS OP");
+                       }
+        }
+        
+        public final FD open(String path, int flags, int mode) throws IOException { return (FD) op(OPEN,path,flags,mode); }
+        public final FStat stat(String path) throws IOException { return (FStat) op(STAT,path,0,0); }
+        public final void mkdir(String path) throws IOException { op(MKDIR,path,0,0); }
+        
+               
+               // FEATURE: inode stuff
+        // FEATURE: Implement whatever is needed to get newlib's opendir and friends to work - that patch is a pain
+        protected static FD directoryFD(String[] files, int hashCode) throws IOException {
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
             DataOutputStream dos = new DataOutputStream(bos);
             for(int i=0;i<files.length;i++) {
@@ -392,121 +513,163 @@ public abstract class UnixRuntime extends Runtime {
         }
     }
         
-    private static boolean needsCleanup(String path) {
-        if(path.indexOf("//") != -1) return true;
-        if(path.indexOf('.') != -1) {
-            if(path.length() == 1) return true;
-            if(path.equals("..")) return true;
-            if(path.startsWith("./")  || path.indexOf("/./")  != -1 || path.endsWith("/."))  return true;
-            if(path.startsWith("../") || path.indexOf("/../") != -1 || path.endsWith("/..")) return true;
+    private String normalizePath(String path) {
+        boolean absolute = path.startsWith("/");
+        int cwdl = cwd.length();
+        // NOTE: This isn't just a fast path, it handles cases the code below doesn't
+        if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
+            return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
+        
+        char[] in = new char[path.length()+1];
+        char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
+        int inp=0, outp=0;
+        
+        if(absolute) {
+            do { inp++; } while(in[inp] == '/');
+        } else if(cwdl != 0) {
+               cwd.getChars(0,cwdl,out,0);
+               outp = cwdl;
         }
-        return false;
-    }
-    
-    // FIXME: This is probably still buggy
-    // FEATURE: Remove some of the "should never happen checks"
-    protected String cleanupPath(String p) throws ErrnoException {
-        if(p.length() == 0) throw new ErrnoException(ENOENT);
-        if(needsCleanup(p)) {
-            char[] in = p.toCharArray();
-            char[] out;
-            int outp ;
-            if(in[0] == '/') {
-                out = new char[in.length];
-                outp = 0;
-            } else {
-                out = new char[cwd.length() + in.length + 1];
-                outp = cwd.length();
-                for(int i=0;i<outp;i++) out[i] = cwd.charAt(i);
-                if(outp == 0 || out[0] != '/') throw new Error("should never happen");
+            
+        path.getChars(0,path.length(),in,0);
+        while(in[inp] != 0) {
+            if(inp != 0) {
+                   if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
+                   while(in[inp] == '/') inp++;
             }
-            int inLength = in.length;
-            int inp = 0;
-            while(inp<inLength) {
-                if(inp == 0 || in[inp] == '/') {
-                    while(inp < inLength && in[inp] == '/') inp++;
-                    if(inp == inLength) break;
-                    if(in[inp] == '.') {
-                        if(inp+1 == inLength) break;
-                        if(in[inp+1] == '.' && (inp+2 == inLength || in[inp+2] == '/')) {
-                            inp+=2;
-                            if(outp == 0) continue;
-                            do { outp--; } while(outp > 0 && out[outp] != '/');
-                        } else if(in[inp+1] == '/') {
-                            inp++;
-                        } else {
-                            out[outp++] = '/';
-                        }
-                    } else {
-                        out[outp++] = '/';
-                        out[outp++] = in[inp++];
-                    }
-                } else {
-                    out[outp++] = in[inp++];
-                }
+            if(in[inp] == '\0') continue;
+            if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
+            if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
+            if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
+                inp += 2;
+                if(outp > 0) outp--;
+                while(outp > 0 && out[outp] != '/') outp--;
+                System.err.println("After ..: " + new String(out,0,outp));
+                continue;
             }
-            if(outp == 0) out[outp++] = '/';
-            return new String(out,0,outp);
-        } else {
-            if(p.startsWith("/")) return p;
-            StringBuffer sb = new StringBuffer(cwd);
-            if(!cwd.equals("/")) sb.append('/');
-            return sb.append(p).toString();
+            inp++;
+            out[outp++] = '/';
+            out[outp++] = '.';
         }
+        if(outp > 0 && out[outp-1] == '/') outp--;
+        //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
+        return new String(out,0,outp);
     }
     
-    // FEATURE: Probably should make this more general - support mountpoints, etc
-    public class UnixOverlayFS extends FS {
-        private final FS root;
-        private final FS dev = new DevFS();
-        public UnixOverlayFS(FS root) {
-            this.root = root;
-        }
-        private String devPath(String path) {
-            if(path.startsWith("/dev")) {
-                if(path.length() == 4) return "/";
-                if(path.charAt(4) == '/') return path.substring(4);
+    public static class MountPointFS extends FS {
+        private static class MP {
+            public MP(String path, FS fs) { this.path = path; this.fs = fs; }
+            public String path;
+            public FS fs;
+            public int compareTo(Object o) {
+                if(!(o instanceof MP)) return 1;
+                return -path.compareTo(((MP)o).path);
             }
+        }
+        private final MP[][] mps = new MP[128][];
+        private final FS root;
+        public MountPointFS(FS root) { this.root = root; }
+        
+        private static String fixup(String path) {
+            if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
+            path = path.substring(1);
+            if(path.length() == 0) throw new IllegalArgumentException("Zero length mount point path");
+            return path;
+        }
+        public synchronized FS get(String path) {
+            path = fixup(path);
+            int f = path.charAt(0) & 0x7f;
+            for(int i=0;mps[f] != null && i < mps[f].length;i++)
+                if(mps[f][i].path.equals(path)) return mps[f][i].fs;
             return null;
         }
-        public FD open(String path, int flags, int mode) throws IOException{
-            String dp = devPath(path);
-            return dp == null ? root.open(path,flags,mode) : dev.open(dp,flags,mode);
+        
+        public synchronized void add(String path, FS fs) {
+            if(get(path) != null) throw new IllegalArgumentException("mount point already exists");
+            path = fixup(path);
+            int f = path.charAt(0) & 0x7f;
+            int oldLength = mps[f] == null ? 0 : mps[f].length;
+            MP[] newList = new MP[oldLength + 1];
+            if(oldLength != 0) System.arraycopy(mps[f],0,newList,0,oldLength);
+            newList[oldLength] = new MP(path,fs);
+            Arrays.sort(newList);
+            mps[f] = newList;
         }
-        public FStat stat(String path) throws IOException {
-            String dp = devPath(path);
-            return dp == null ? root.stat(path) : dev.stat(dp);
+        
+        public synchronized void remove(String path) {
+            path = fixup(path);
+            if(get(path) == null) throw new IllegalArgumentException("mount point doesn't exist");
+            int f = path.charAt(0) & 0x7f;
+            MP[] oldList = mps[f];
+            MP[] newList = new MP[oldList.length - 1];
+            int p = 0;
+            for(p=0;p<oldList.length;p++) if(oldList[p].path.equals(path)) break;
+            if(p == oldList.length) throw new Error("should never happen");
+            System.arraycopy(oldList,0,newList,0,p);
+            System.arraycopy(oldList,0,newList,p,oldList.length-p-1);
+            mps[f] = newList;
         }
-        public void mkdir(String path) throws IOException {
-            String dp = devPath(path);
-            if(dp == null) root.mkdir(path);
-            else dev.mkdir(dp);
+        
+        protected Object op(int op, String path, int arg1, int arg2) throws IOException {
+            int pl = path.length();
+            if(pl != 0) {
+                   MP[] list = mps[path.charAt(0) & 0x7f];
+                   if(list != null) for(int i=0;i<list.length;i++) {
+                               MP mp = list[i];
+                               int mpl = mp.path.length();
+                               if(pl == mpl || (pl < mpl && path.charAt(mpl) == '/'))
+                               return mp.fs.op(op,pl == mpl ? "" : path.substring(mpl+1),arg1,arg2);
+                 }
+            }
+            return root.op(op,path,arg1,arg2);
         }
     }
-    
-    // FIXME: This is totally broken on non-unix hosts - need to do some kind of cygwin type mapping
+        
     public static class HostFS extends FS {
-        public static String fixPath(String path) throws FileNotFoundException {
-            return path;
+        protected File root;
+        public File getRoot() { return root; }
+        
+        private static File hostRootDir() {
+            String cwd = getSystemProperty("user.dir");
+            File f = new File(cwd != null ? cwd : ".");
+            f = new File(f.getAbsolutePath());
+            while(f.getParent() != null) f = new File(f.getParent());
+            return f;
         }
         
-        public String hostCWD() {
-            return getSystemProperty("user.dir");
+        File hostFile(String path) {
+            char sep = File.separatorChar;
+            if(sep != '/') {
+                char buf[] = path.toCharArray();
+                for(int i=0;i<buf.length;i++) {
+                           char c = buf[i];
+                    if(c == '/') buf[i] = sep;
+                    else if(c == sep) buf[i] = '/';
+                }
+                path = new String(buf);
+            }
+            return new File(root,path);
         }
         
+        public HostFS() { this(hostRootDir()); }
+        public HostFS(String root) { this(new File(root)); }
+        public HostFS(File root) { this.root = root; }
+        
+        
         // FEATURE: This shares a lot with Runtime.open
-        public FD open(String path, int flags, int mode) throws IOException {
-            path = fixPath(path);
-            final File f = new File(path);
-            // NOTE: createNewFile is a Java2 function
-            if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT))
-                if(!f.createNewFile()) throw new ErrnoException(EEXIST);
-            if(!f.exists() && (flags&O_CREAT) == 0) return null;
+        // NOTE: createNewFile is a Java2 function
+        public FD _open(String path, int flags, int mode) throws IOException {
+            final File f = hostFile(path);
+            System.err.println(path + " -> " + f + " " + f.exists());
             if(f.isDirectory()) {
                 if((flags&3)!=RD_ONLY) throw new ErrnoException(EACCES);
                 return directoryFD(f.list(),path.hashCode());
             }
-            final Seekable.File sf = new Seekable.File(path,(flags&3)!=RD_ONLY);
+            if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT))
+                if(!f.createNewFile()) throw new ErrnoException(EEXIST);
+            if((flags&O_CREAT) == 0 && !f.exists())
+                return null;
+            final Seekable.File sf = new Seekable.File(f,(flags&3)!=RD_ONLY);
             if((flags&O_TRUNC)!=0) sf.setLength(0);
             return new SeekableFD(sf,mode) {
                 protected FStat _fstat() { return new HostFStat(f) {
@@ -517,14 +680,14 @@ public abstract class UnixRuntime extends Runtime {
             };
         }
         
-        public FStat stat(String path) throws FileNotFoundException {
-            File f = new File(fixPath(path));
+        public FStat _stat(String path) throws FileNotFoundException {
+            File f = hostFile(path);
             if(!f.exists()) throw new FileNotFoundException();
             return new HostFStat(f);
         }
         
-        public void mkdir(String path) throws IOException {
-            File f = new File(fixPath(path));
+        public void _mkdir(String path) throws IOException {
+            File f = hostFile(path);
             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
             if(f.exists()) throw new ErrnoException(ENOTDIR);
             File parent = f.getParentFile();
@@ -532,7 +695,7 @@ public abstract class UnixRuntime extends Runtime {
             if(!f.mkdir()) throw new ErrnoException(EIO);            
         }
     }
-    
+        
     private static class DevFStat extends FStat {
         public int dev() { return 1; }
         public int mode() { return 0666; }
@@ -556,11 +719,12 @@ public abstract class UnixRuntime extends Runtime {
         public FStat _fstat() { return new DevFStat(); }
     };    
     
-    public class DevFS extends FS {
-        public FD open(String path, int mode, int flags) throws IOException {
-            if(path.equals("/null")) return devNullFD;
-            if(path.equals("/zero")) return devZeroFD;
-            if(path.startsWith("/fd/")) {
+    // FIXME: Support /dev/fd (need to have syscalls pass along Runtime instance)
+    public static class DevFS extends FS {
+        public FD _open(String path, int mode, int flags) throws IOException {
+            if(path.equals("null")) return devNullFD;
+            if(path.equals("zero")) return devZeroFD;
+            /*if(path.startsWith("fd/")) {
                 int n;
                 try {
                     n = Integer.parseInt(path.substring(4));
@@ -571,25 +735,25 @@ public abstract class UnixRuntime extends Runtime {
                 if(fds[n] == null) throw new FileNotFoundException();
                 return fds[n].dup();
             }
-            if(path.equals("/fd")) {
+            if(path.equals("fd")) {
                 int count=0;
                 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) count++; 
                 String[] files = new String[count];
                 count = 0;
                 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) files[count++] = Integer.toString(i);
                 return directoryFD(files,hashCode());
-            }
-            if(path.equals("/")) {
+            }*/
+            if(path.equals("")) {
                 String[] files = { "null", "zero", "fd" };
                 return directoryFD(files,hashCode());
             }
             throw new FileNotFoundException();
         }
         
-        public FStat stat(String path) throws IOException {
-            if(path.equals("/null")) return devNullFD.fstat();
-            if(path.equals("/zero")) return devZeroFD.fstat();            
-            if(path.startsWith("/fd/")) {
+        public FStat _stat(String path) throws IOException {
+            if(path.equals("null")) return devNullFD.fstat();
+            if(path.equals("zero")) return devZeroFD.fstat();            
+            /*if(path.startsWith("fd/")) {
                 int n;
                 try {
                     n = Integer.parseInt(path.substring(4));
@@ -600,11 +764,12 @@ public abstract class UnixRuntime extends Runtime {
                 if(fds[n] == null) throw new FileNotFoundException();
                 return fds[n].fstat();
             }
-            if(path.equals("/fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
-            if(path.equals("/")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
+            if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
+            */
+            if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
             throw new FileNotFoundException();
         }
         
-        public void mkdir(String path) throws IOException { throw new ErrnoException(EACCES); }
+        public void _mkdir(String path) throws IOException { throw new ErrnoException(EACCES); }
     }
 }