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