5b47219b2f784b4b40299b7c21c23b687725bdde
[nestedvm.git] / src / org / ibex / nestedvm / UnixRuntime.java
1 package org.ibex.nestedvm;
2
3 import org.ibex.nestedvm.util.*;
4 import java.io.*;
5 import java.util.*;
6
7 // FEATURE: BusyBox's ASH doesn't like \r\n at the end of lines
8 // is ash just broken or are many apps like this? if so workaround in nestedvm
9
10 // FEATURE: Throw ErrnoException and catch in syscall whereever possible 
11 // (only in cases where we've already paid the price for a throw)
12
13 public abstract class UnixRuntime extends Runtime implements Cloneable {
14     /** The pid of this "process" */
15     private int pid;
16     private int ppid;
17     protected int getPid() { return pid; }
18     
19     /** processes filesystem */
20     private FS fs;
21     public FS getFS() { return fs; }
22     public void setFS(FS fs) {
23         if(state != STOPPED) throw new IllegalStateException("Can't change fs while process is running");
24         this.fs = fs;
25     }
26     
27     /** proceses' current working directory - absolute path WITHOUT leading slash
28         "" = root, "bin" = /bin "usr/bin" = /usr/bin */
29     private String cwd;
30     
31     /** The runtime that should be run next when in state == EXECED */
32     private UnixRuntime execedRuntime;
33     
34     /* Static stuff */
35     // FEATURE: Most of this is O(n) or worse - fix it
36     private final Object waitNotification = new Object();
37     private final static int MAX_TASKS = 256;
38     private final static UnixRuntime[] tasks = new UnixRuntime[MAX_TASKS];
39     private static int addTask(UnixRuntime rt) {
40         synchronized(tasks) {
41             for(int i=1;i<MAX_TASKS;i++) {
42                 if(tasks[i] == null) {
43                     tasks[i] = rt;
44                     rt.pid = i;
45                     return i;
46                 }
47             }
48             return -1;
49         }
50     }
51     private static void removeTask(UnixRuntime rt) {
52         synchronized(tasks) {
53             for(int i=1;i<MAX_TASKS;i++)
54                 if(tasks[i] == rt) { tasks[i] = null; break; }
55         }
56     }
57     
58     public UnixRuntime(int pageSize, int totalPages) {
59         super(pageSize,totalPages);
60         
61         FS root = new HostFS();
62         FS dev = new DevFS();
63         MountPointFS mounts = new MountPointFS(root);
64         mounts.add("/dev",dev);
65         fs = mounts;
66         
67         // FEATURE: Do the proper mangling for non-unix hosts
68         String userdir = getSystemProperty("user.dir");
69         cwd = userdir != null && userdir.startsWith("/") && File.separatorChar == '/'  ? userdir.substring(1) : "";
70     }
71     
72     // NOTE: getDisplayName() is a Java2 function
73     private static String posixTZ() {
74         StringBuffer sb = new StringBuffer();
75         TimeZone zone = TimeZone.getDefault();
76         int off = zone.getRawOffset() / 1000;
77         sb.append(zone.getDisplayName(false,TimeZone.SHORT));
78         if(off > 0) sb.append("-");
79         else off = -off;
80         sb.append(off/3600); off = off%3600;
81         if(off > 0) sb.append(":").append(off/60); off=off%60;
82         if(off > 0) sb.append(":").append(off);
83         if(zone.useDaylightTime())
84             sb.append(zone.getDisplayName(true,TimeZone.SHORT));
85         return sb.toString();
86     }
87     
88     private static boolean envHas(String key,String[] environ) {
89         for(int i=0;i<environ.length;i++)
90             if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
91         return false;
92     }
93     
94     protected String[] createEnv(String[] extra) {
95         String[] defaults = new String[5];
96         int n=0;
97         if(extra == null) extra = new String[0];
98         if(!envHas("USER",extra) && getSystemProperty("user.name") != null)
99             defaults[n++] = "USER=" + getSystemProperty("user.name");
100         if(!envHas("HOME",extra) && getSystemProperty("user.name") != null)
101             defaults[n++] = "HOME=" + getSystemProperty("user.home");
102         if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
103         if(!envHas("TERM",extra))  defaults[n++] = "TERM=vt100";
104         if(!envHas("TZ",extra))    defaults[n++] = "TZ=" + posixTZ();
105         String[] env = new String[extra.length+n];
106         for(int i=0;i<n;i++) env[i] = defaults[i];
107         for(int i=0;i<extra.length;i++) env[n++] = extra[i];
108         return env;
109     }
110     
111     protected void _start() {
112         if(addTask(this) < 0) throw new Error("Task list full");
113     }
114     
115     protected void _exit() {
116         synchronized(tasks) {
117             if(ppid == 0) removeTask(this);
118             for(int i=0;i<MAX_TASKS;i++) {
119                 if(tasks[i] != null && tasks[i].ppid == pid) {
120                     if(tasks[i].state == EXITED) removeTask(tasks[i]);
121                     else tasks[i].ppid = 0;
122                 }
123             }
124             state = EXITED;
125             if(ppid != 0) synchronized(tasks[ppid].waitNotification) { tasks[ppid].waitNotification.notify(); }
126         }
127     }
128
129     protected int syscall(int syscall, int a, int b, int c, int d) {
130         switch(syscall) {
131             case SYS_kill: return sys_kill(a,b);
132             case SYS_fork: return sys_fork();
133             case SYS_pipe: return sys_pipe(a);
134             case SYS_dup2: return sys_dup2(a,b);
135             case SYS_waitpid: return sys_waitpid(a,b,c);
136             case SYS_stat: return sys_stat(a,b);
137             case SYS_mkdir: return sys_mkdir(a,b);
138             case SYS_getcwd: return sys_getcwd(a,b);
139             case SYS_chdir: return sys_chdir(a);
140             case SYS_execve: return sys_execve(a,b,c);
141
142             default: return super.syscall(syscall,a,b,c,d);
143         }
144     }
145     
146     protected FD open(String path, int flags, int mode) throws IOException {
147         return fs.open(normalizePath(path),flags,mode);
148     }
149
150     // FEATURE: Allow simple, broken signal delivery to other processes 
151     // (check if a signal was delivered before and after syscalls)
152     // FEATURE: Implement raise() in terms of call("raise",...) - kinda cheap, but it keeps the complexity in newlib
153     /** The kill syscall.
154        SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
155        SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
156        Anything else terminates the process. */
157     private int sys_kill(int pid, int signal) {
158         // This will only be called by raise() in newlib to invoke the default handler
159         // We don't have to worry about actually delivering the signal
160         if(pid != pid) return -ESRCH;
161         if(signal < 0 || signal >= 32) return -EINVAL;
162         switch(signal) {
163             case 0: return 0;
164             case 17: // SIGSTOP
165             case 18: // SIGTSTP
166             case 21: // SIGTTIN
167             case 22: // SIGTTOU
168                 state = PAUSED;
169                 break;
170             case 19: // SIGCONT
171             case 20: // SIGCHLD
172             case 23: // SIGIO
173             case 28: // SIGWINCH
174                 break;
175             default:
176                 return syscall(SYS_exit,128+signal,0,0,0);
177         }
178         return 0;
179     }
180
181     private int sys_waitpid(int pid, int statusAddr, int options) {
182         final int WNOHANG = 1;
183         if((options & ~(WNOHANG)) != 0) return -EINVAL;
184         if(pid !=-1 && (pid <= 0 || pid >= MAX_TASKS)) return -ECHILD;
185         for(;;) {
186             synchronized(tasks) {
187                 UnixRuntime task = null;
188                 if(pid == -1) {
189                     for(int i=0;i<MAX_TASKS;i++) {
190                         if(tasks[i] != null && tasks[i].ppid == this.pid && tasks[i].state == EXITED) {
191                             task = tasks[i];
192                             break;
193                         }
194                     }
195                 } else if(tasks[pid] != null && tasks[pid].ppid == this.pid && tasks[pid].state == EXITED) {
196                     task = tasks[pid];
197                 }
198                 
199                 if(task != null) {
200                     removeTask(task);
201                     try {
202                         if(statusAddr!=0) memWrite(statusAddr,task.exitStatus()<<8);
203                     } catch(FaultException e) {
204                         return -EFAULT;
205                     }
206
207                     return task.pid;
208                 }
209             }
210             if((options&WNOHANG)!=0) return 0;
211             synchronized(waitNotification) {
212                 try { waitNotification.wait(); } catch(InterruptedException e) { /* ignore */ }
213             }
214         }
215     }
216     
217     protected Object clone() throws CloneNotSupportedException {
218             UnixRuntime r = (UnixRuntime) super.clone();
219         r.pid = r.ppid = 0;
220         return r;
221     }
222
223     private int sys_fork() {
224         CPUState state = new CPUState();
225         getCPUState(state);
226         int sp = state.r[SP];
227         final UnixRuntime r;
228         
229         try {
230             r = (UnixRuntime) clone();
231         } catch(Exception e) {
232             e.printStackTrace();
233             return -ENOMEM;
234         }
235         
236         int childPID = addTask(r);
237         if(childPID < 0) return -ENOMEM;
238         
239         r.ppid = pid;
240         
241         state.r[V0] = 0; // return 0 to child
242         state.pc += 4; // skip over syscall instruction
243         r.setCPUState(state);
244         r.state = PAUSED;
245         
246         new Thread() {
247             public void run() {
248                 try {
249                     while(!r.execute());
250                 } catch(Exception e) {
251                     System.err.println("Forked process threw exception: ");
252                     e.printStackTrace();
253                 }
254             }
255         }.start();
256         
257         return childPID;
258     }
259     
260     public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
261     public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
262     
263     public static int executeAndExec(UnixRuntime r) {
264             for(;;) {
265             for(;;) {
266                 if(r.execute()) break;
267                 System.err.println("WARNING: Pause requested while executing runAndExec()");
268             }
269             if(r.state != EXECED) return r.exitStatus();
270             r = r.execedRuntime;
271         }
272     }
273      
274     private String[] readStringArray(int addr) throws ReadFaultException {
275             int count = 0;
276         for(int p=addr;memRead(p) != 0;p+=4) count++;
277         String[] a = new String[count];
278         for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
279         return a;
280     }
281     
282     // FEATURE: call the syscall just "exec"
283     private int sys_execve(int cpath, int cargv, int cenvp) {
284         try {
285                     return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
286         } catch(FaultException e) {
287             return -EFAULT;
288         }
289     }
290     
291     private int exec(String path, String[] argv, String[] envp) {
292         if(argv.length == 0) argv = new String[]{""};
293         Seekable s;
294         FD fd;
295         
296         try {
297             fd = fs.open(path,RD_ONLY,0);
298             System.err.println(fd + "  " + path);
299             if(fd == null) return -ENOENT;
300             s = fd.seekable();
301             if(s == null) return -ENOEXEC;
302         }
303         catch(ErrnoException e) { return -e.errno; }
304         catch(FileNotFoundException e) {
305             if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
306             return -ENOENT;
307         }
308         catch(IOException e) { return -EIO; }
309         
310         try {
311             int p = 0;
312             byte[] buf = new byte[4096];
313             OUTER: for(;;) {
314                     int n = s.read(buf,p,buf.length-p);
315                 if(n == -1) break;
316                 for(;n > 0; n--) if(buf[p++] == '\n' || p == 4096) break OUTER;
317             }
318             if(buf[0] == '!' && buf[1] == '#') {
319                     String cmd = new String(buf,2,p-2);
320                 String argv1 = null;
321                 if((p = cmd.indexOf(' ')) != -1) {
322                     do { p++; } while(cmd.charAt(p)==' ');
323                             argv1 = cmd.substring(p);
324                     cmd = cmd.substring(0,p-1);
325                 }
326                 String[] newArgv = new String[argv.length + argv1 != null ? 2 : 1];
327                 p = 0;
328                 newArgv[p++] = argv[0];
329                 if(argv1 != null) newArgv[p++] = argv1;
330                 newArgv[p++] = path;
331                 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
332                 fd.close();
333                 return exec(cmd,newArgv,envp);
334             } else if(buf[0] == '\177' && buf[1] == 'E' && buf[2] == 'L' && buf[3] == 'F') {
335                 s.seek(0);
336                     UnixRuntime r = new Interpreter(s);
337                 fd.close();
338                 return exec(r,argv,envp);
339             } else {
340                     return -ENOEXEC;
341             }
342         } catch(IOException e) {
343                     e.printStackTrace();
344             return -ENOEXEC;
345         }
346     }
347     
348     private int exec(UnixRuntime r, String[] argv, String[] envp) {        
349         for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
350         r.fds = fds;
351         r.closeOnExec = closeOnExec;
352         // make sure this doesn't get messed with these since we didn't copy them
353         fds = null;
354         closeOnExec = null;
355         
356         r.cwd = cwd;
357         r.fs = fs;
358         r.pid = pid;
359         r.ppid = ppid;
360         r.start(argv,envp);
361         
362         state = EXECED;
363         execedRuntime = r;
364         
365         return 0;   
366     }
367     
368     // FEATURE: Use custom PipeFD - be sure to support PIPE_BUF of data
369     private int sys_pipe(int addr) {
370         PipedOutputStream writerStream = new PipedOutputStream();
371         PipedInputStream readerStream;
372         try {
373              readerStream = new PipedInputStream(writerStream);
374         } catch(IOException e) {
375             return -EIO;
376         }
377         FD reader = new InputStreamFD(readerStream);
378         FD writer = new OutputStreamFD(writerStream);
379         int fd1 = addFD(reader);
380         if(fd1 < 0) return -ENFILE;
381         int fd2 = addFD(writer);
382         if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
383         try {
384             memWrite(addr,fd1);
385             memWrite(addr+4,fd2);
386         } catch(FaultException e) {
387             closeFD(fd1);
388             closeFD(fd2);
389             return -EFAULT;
390         }
391         return 0;
392     }
393     
394     private int sys_dup2(int oldd, int newd) {
395         if(oldd == newd) return 0;
396         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
397         if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
398         if(fds[oldd] == null) return -EBADFD;
399         if(fds[newd] != null) fds[newd].close();
400         fds[newd] = fds[oldd].dup();
401         return 0;
402     }
403     
404     private int sys_stat(int cstring, int addr) {
405         try {
406             String path = normalizePath(cstring(cstring));
407             return stat(fs.stat(path),addr);
408         }
409         catch(ErrnoException e) { return -e.errno; }
410         catch(FileNotFoundException e) {
411             if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
412             return -ENOENT;
413         }
414         catch(IOException e) { return -EIO; }
415         catch(FaultException e) { return -EFAULT; }
416     }
417     
418     
419     private int sys_mkdir(int cstring, int mode) {
420         try {
421             fs.mkdir(normalizePath(cstring(cstring)));
422             return 0;
423         }
424         catch(ErrnoException e) { return -e.errno; }
425         catch(FileNotFoundException e) { return -ENOENT; }
426         catch(IOException e) { return -EIO; }
427         catch(FaultException e) { return -EFAULT; }
428     }
429    
430     
431     private int sys_getcwd(int addr, int size) {
432         byte[] b = getBytes(cwd);
433         if(size == 0) return -EINVAL;
434         if(size < b.length+2) return -ERANGE;
435         try {
436             memset(addr,'/',1);
437             copyout(b,addr+1,b.length);
438             memset(addr+b.length+1,0,1);
439             return addr;
440         } catch(FaultException e) {
441             return -EFAULT;
442         }
443     }
444     
445     private int sys_chdir(int addr) {
446         try {
447             String path = normalizePath(cstring(addr));
448             System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
449             if(fs.stat(path).type() != FStat.S_IFDIR) return -ENOTDIR;
450             cwd = path;
451             System.err.println("Now: [" + cwd + "]");
452             return 0;
453         }
454         catch(ErrnoException e) { return -e.errno; }
455         catch(FileNotFoundException e) { return -ENOENT; }
456         catch(IOException e) { return -EIO; }
457         catch(FaultException e) { return -EFAULT; }
458     }
459
460     public void chdir(String dir) throws FileNotFoundException {
461         if(state != STOPPED) throw new IllegalStateException("Can't chdir while process is running");
462         try {
463             dir = normalizePath(dir);
464             if(fs.stat(dir).type() != FStat.S_IFDIR) throw new FileNotFoundException();
465         } catch(IOException e) {
466             throw new FileNotFoundException();
467         }
468         cwd = dir;
469     }
470         
471     public abstract static class FS {
472         protected FD _open(String path, int flags, int mode) throws IOException { return null; }
473         protected FStat _stat(String path) throws IOException { return null; }
474         protected void _mkdir(String path) throws IOException { throw new ErrnoException(EROFS); }
475         
476         protected static final int OPEN = 1;
477         protected static final int STAT = 2;
478         protected static final int MKDIR = 3;
479         
480         protected Object op(int op, String path, int arg1, int arg2) throws IOException {
481                         switch(op) {
482                                 case OPEN: return _open(path,arg1,arg2);
483                                 case STAT: return _stat(path);
484                                 case MKDIR: _mkdir(path); return null;
485                                 default: throw new IllegalArgumentException("Unknown FS OP");
486                         }
487         }
488         
489         public final FD open(String path, int flags, int mode) throws IOException { return (FD) op(OPEN,path,flags,mode); }
490         public final FStat stat(String path) throws IOException { return (FStat) op(STAT,path,0,0); }
491         public final void mkdir(String path) throws IOException { op(MKDIR,path,0,0); }
492         
493                 
494                 // FEATURE: inode stuff
495         // FEATURE: Implement whatever is needed to get newlib's opendir and friends to work - that patch is a pain
496         protected static FD directoryFD(String[] files, int hashCode) throws IOException {
497             ByteArrayOutputStream bos = new ByteArrayOutputStream();
498             DataOutputStream dos = new DataOutputStream(bos);
499             for(int i=0;i<files.length;i++) {
500                 byte[] b = getBytes(files[i]);
501                 int inode = (files[i].hashCode() ^ hashCode) & 0xfffff;
502                 dos.writeInt(inode);
503                 dos.writeInt(b.length);
504                 dos.write(b,0,b.length);
505             }
506             final byte[] data = bos.toByteArray();
507             return new SeekableFD(new Seekable.ByteArray(data,false),RD_ONLY) {
508                 protected FStat _fstat() { return  new FStat() {
509                     public int length() { return data.length; }
510                     public int type() { return S_IFDIR; }
511                 }; }
512             };
513         }
514     }
515         
516     private String normalizePath(String path) {
517         boolean absolute = path.startsWith("/");
518         int cwdl = cwd.length();
519         // NOTE: This isn't just a fast path, it handles cases the code below doesn't
520         if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
521             return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
522         
523         char[] in = new char[path.length()+1];
524         char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
525         int inp=0, outp=0;
526         
527         if(absolute) {
528             do { inp++; } while(in[inp] == '/');
529         } else if(cwdl != 0) {
530                 cwd.getChars(0,cwdl,out,0);
531                 outp = cwdl;
532         }
533             
534         path.getChars(0,path.length(),in,0);
535         while(in[inp] != 0) {
536             if(inp != 0) {
537                     if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
538                     while(in[inp] == '/') inp++;
539             }
540             if(in[inp] == '\0') continue;
541             if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
542             if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
543             if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
544                 inp += 2;
545                 if(outp > 0) outp--;
546                 while(outp > 0 && out[outp] != '/') outp--;
547                 System.err.println("After ..: " + new String(out,0,outp));
548                 continue;
549             }
550             inp++;
551             out[outp++] = '/';
552             out[outp++] = '.';
553         }
554         if(outp > 0 && out[outp-1] == '/') outp--;
555         //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
556         return new String(out,0,outp);
557     }
558     
559     public static class MountPointFS extends FS {
560         private static class MP {
561             public MP(String path, FS fs) { this.path = path; this.fs = fs; }
562             public String path;
563             public FS fs;
564             public int compareTo(Object o) {
565                 if(!(o instanceof MP)) return 1;
566                 return -path.compareTo(((MP)o).path);
567             }
568         }
569         private final MP[][] mps = new MP[128][];
570         private final FS root;
571         public MountPointFS(FS root) { this.root = root; }
572         
573         private static String fixup(String path) {
574             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
575             path = path.substring(1);
576             if(path.length() == 0) throw new IllegalArgumentException("Zero length mount point path");
577             return path;
578         }
579         public synchronized FS get(String path) {
580             path = fixup(path);
581             int f = path.charAt(0) & 0x7f;
582             for(int i=0;mps[f] != null && i < mps[f].length;i++)
583                 if(mps[f][i].path.equals(path)) return mps[f][i].fs;
584             return null;
585         }
586         
587         public synchronized void add(String path, FS fs) {
588             if(get(path) != null) throw new IllegalArgumentException("mount point already exists");
589             path = fixup(path);
590             int f = path.charAt(0) & 0x7f;
591             int oldLength = mps[f] == null ? 0 : mps[f].length;
592             MP[] newList = new MP[oldLength + 1];
593             if(oldLength != 0) System.arraycopy(mps[f],0,newList,0,oldLength);
594             newList[oldLength] = new MP(path,fs);
595             Arrays.sort(newList);
596             mps[f] = newList;
597         }
598         
599         public synchronized void remove(String path) {
600             path = fixup(path);
601             if(get(path) == null) throw new IllegalArgumentException("mount point doesn't exist");
602             int f = path.charAt(0) & 0x7f;
603             MP[] oldList = mps[f];
604             MP[] newList = new MP[oldList.length - 1];
605             int p = 0;
606             for(p=0;p<oldList.length;p++) if(oldList[p].path.equals(path)) break;
607             if(p == oldList.length) throw new Error("should never happen");
608             System.arraycopy(oldList,0,newList,0,p);
609             System.arraycopy(oldList,0,newList,p,oldList.length-p-1);
610             mps[f] = newList;
611         }
612         
613         protected Object op(int op, String path, int arg1, int arg2) throws IOException {
614             int pl = path.length();
615             if(pl != 0) {
616                     MP[] list = mps[path.charAt(0) & 0x7f];
617                     if(list != null) for(int i=0;i<list.length;i++) {
618                                 MP mp = list[i];
619                                 int mpl = mp.path.length();
620                                 if(pl == mpl || (pl < mpl && path.charAt(mpl) == '/'))
621                                 return mp.fs.op(op,pl == mpl ? "" : path.substring(mpl+1),arg1,arg2);
622                  }
623             }
624             return root.op(op,path,arg1,arg2);
625         }
626     }
627         
628     public static class HostFS extends FS {
629         protected File root;
630         public File getRoot() { return root; }
631         
632         private static File hostRootDir() {
633             String cwd = getSystemProperty("user.dir");
634             File f = new File(cwd != null ? cwd : ".");
635             f = new File(f.getAbsolutePath());
636             while(f.getParent() != null) f = new File(f.getParent());
637             return f;
638         }
639         
640         File hostFile(String path) {
641             char sep = File.separatorChar;
642             if(sep != '/') {
643                 char buf[] = path.toCharArray();
644                 for(int i=0;i<buf.length;i++) {
645                             char c = buf[i];
646                     if(c == '/') buf[i] = sep;
647                     else if(c == sep) buf[i] = '/';
648                 }
649                 path = new String(buf);
650             }
651             return new File(root,path);
652         }
653         
654         public HostFS() { this(hostRootDir()); }
655         public HostFS(String root) { this(new File(root)); }
656         public HostFS(File root) { this.root = root; }
657         
658         
659         // FEATURE: This shares a lot with Runtime.open
660         // NOTE: createNewFile is a Java2 function
661         public FD _open(String path, int flags, int mode) throws IOException {
662             final File f = hostFile(path);
663             System.err.println(path + " -> " + f + " " + f.exists());
664             if(f.isDirectory()) {
665                 if((flags&3)!=RD_ONLY) throw new ErrnoException(EACCES);
666                 return directoryFD(f.list(),path.hashCode());
667             }
668             if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT))
669                 if(!f.createNewFile()) throw new ErrnoException(EEXIST);
670             if((flags&O_CREAT) == 0 && !f.exists())
671                 return null;
672             final Seekable.File sf = new Seekable.File(f,(flags&3)!=RD_ONLY);
673             if((flags&O_TRUNC)!=0) sf.setLength(0);
674             return new SeekableFD(sf,mode) {
675                 protected FStat _fstat() { return new HostFStat(f) {
676                     public int size() {
677                         try { return sf.length(); } catch(IOException e) { return 0; }
678                     }
679                 };}
680             };
681         }
682         
683         public FStat _stat(String path) throws FileNotFoundException {
684             File f = hostFile(path);
685             if(!f.exists()) throw new FileNotFoundException();
686             return new HostFStat(f);
687         }
688         
689         public void _mkdir(String path) throws IOException {
690             File f = hostFile(path);
691             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
692             if(f.exists()) throw new ErrnoException(ENOTDIR);
693             File parent = f.getParentFile();
694             if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
695             if(!f.mkdir()) throw new ErrnoException(EIO);            
696         }
697     }
698         
699     private static class DevFStat extends FStat {
700         public int dev() { return 1; }
701         public int mode() { return 0666; }
702         public int type() { return S_IFCHR; }
703         public int nlink() { return 1; }
704     }
705     private static FD devZeroFD = new FD() {
706         public boolean readable() { return true; }
707         public boolean writable() { return true; }
708         public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
709         public int write(byte[] a, int off, int length) { return length; }
710         public int seek(int n, int whence) { return 0; }
711         public FStat _fstat() { return new DevFStat(); }
712     };
713     private static FD devNullFD = new FD() {
714         public boolean readable() { return true; }
715         public boolean writable() { return true; }
716         public int read(byte[] a, int off, int length) { return 0; }
717         public int write(byte[] a, int off, int length) { return length; }
718         public int seek(int n, int whence) { return 0; }
719         public FStat _fstat() { return new DevFStat(); }
720     };    
721     
722     // FIXME: Support /dev/fd (need to have syscalls pass along Runtime instance)
723     public static class DevFS extends FS {
724         public FD _open(String path, int mode, int flags) throws IOException {
725             if(path.equals("null")) return devNullFD;
726             if(path.equals("zero")) return devZeroFD;
727             /*if(path.startsWith("fd/")) {
728                 int n;
729                 try {
730                     n = Integer.parseInt(path.substring(4));
731                 } catch(NumberFormatException e) {
732                     throw new FileNotFoundException();
733                 }
734                 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
735                 if(fds[n] == null) throw new FileNotFoundException();
736                 return fds[n].dup();
737             }
738             if(path.equals("fd")) {
739                 int count=0;
740                 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) count++; 
741                 String[] files = new String[count];
742                 count = 0;
743                 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) files[count++] = Integer.toString(i);
744                 return directoryFD(files,hashCode());
745             }*/
746             if(path.equals("")) {
747                 String[] files = { "null", "zero", "fd" };
748                 return directoryFD(files,hashCode());
749             }
750             throw new FileNotFoundException();
751         }
752         
753         public FStat _stat(String path) throws IOException {
754             if(path.equals("null")) return devNullFD.fstat();
755             if(path.equals("zero")) return devZeroFD.fstat();            
756             /*if(path.startsWith("fd/")) {
757                 int n;
758                 try {
759                     n = Integer.parseInt(path.substring(4));
760                 } catch(NumberFormatException e) {
761                     throw new FileNotFoundException();
762                 }
763                 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
764                 if(fds[n] == null) throw new FileNotFoundException();
765                 return fds[n].fstat();
766             }
767             if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
768             */
769             if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
770             throw new FileNotFoundException();
771         }
772         
773         public void _mkdir(String path) throws IOException { throw new ErrnoException(EACCES); }
774     }
775 }