Exec support and cleanup
[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         final UnixRuntime r;
293         
294         throw new Error("FIXME exec() not finished");
295         //Class klass = fs.getClass(path);
296         //if(klass != null) return exec(klass,argv,envp);
297         
298         /*try {
299              Seekable s = fs.getSeekable(path);
300              boolean elf = false;
301              boolean script = false;
302              switch(s.read()) {
303                 case '\177': elf = s.read() == 'E' && s.read() == 'L' && s.read() == 'F'; break;
304                 case '#': script = s.read() == '!';
305             }
306             s.close();
307             if(script) {
308                 // FIXME #! support
309                 throw new Error("FIXME can't exec scripts yet");
310                 // append args, etc
311                 // return exec(...)
312             } else if(elf) {
313                 klass = fs.(path);
314                 if(klass == null) return -ENOEXEC;
315                 return exec(klass,argv,envp);
316             } else {
317                     return -ENOEXEC;
318             }
319         }*/
320         // FEATURE: Way too much overlap in the handling of ioexeptions everhwere
321         /*catch(ErrnoException e) { return -e.errno; }
322         catch(FileNotFoundException e) {
323             if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
324             return -ENOENT;
325         }
326         catch(IOException e) { return -EIO; }
327         catch(FaultException e) { return -EFAULT; }*/
328     }
329     
330     private int exec(Class c, String[] argv, String[] envp) {
331         UnixRuntime r;
332         
333         try {
334                     r = (UnixRuntime) c.newInstance();
335         } catch(Exception e) {
336                     return -ENOMEM;
337         }
338         
339         for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
340         r.fds = fds;
341         r.closeOnExec = closeOnExec;
342         // make sure this doesn't get messed with these since we didn't copy them
343         fds = null;
344         closeOnExec = null;
345         
346         r.cwd = cwd;
347         r.fs = fs;
348         r.pid = pid;
349         r.ppid = ppid;
350         r.start(argv,envp);
351         
352         state = EXECED;
353         execedRuntime = r;
354         
355         return 0;   
356     }
357     
358     // FEATURE: Use custom PipeFD - be sure to support PIPE_BUF of data
359     private int sys_pipe(int addr) {
360         PipedOutputStream writerStream = new PipedOutputStream();
361         PipedInputStream readerStream;
362         try {
363              readerStream = new PipedInputStream(writerStream);
364         } catch(IOException e) {
365             return -EIO;
366         }
367         FD reader = new InputStreamFD(readerStream);
368         FD writer = new OutputStreamFD(writerStream);
369         int fd1 = addFD(reader);
370         if(fd1 < 0) return -ENFILE;
371         int fd2 = addFD(writer);
372         if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
373         try {
374             memWrite(addr,fd1);
375             memWrite(addr+4,fd2);
376         } catch(FaultException e) {
377             closeFD(fd1);
378             closeFD(fd2);
379             return -EFAULT;
380         }
381         return 0;
382     }
383     
384     private int sys_dup2(int oldd, int newd) {
385         if(oldd == newd) return 0;
386         if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
387         if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
388         if(fds[oldd] == null) return -EBADFD;
389         if(fds[newd] != null) fds[newd].close();
390         fds[newd] = fds[oldd].dup();
391         return 0;
392     }
393     
394     private int sys_stat(int cstring, int addr) {
395         try {
396             String path = normalizePath(cstring(cstring));
397             return stat(fs.stat(path),addr);
398         }
399         catch(ErrnoException e) { return -e.errno; }
400         catch(FileNotFoundException e) {
401             if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
402             return -ENOENT;
403         }
404         catch(IOException e) { return -EIO; }
405         catch(FaultException e) { return -EFAULT; }
406     }
407     
408     
409     private int sys_mkdir(int cstring, int mode) {
410         try {
411             fs.mkdir(normalizePath(cstring(cstring)));
412             return 0;
413         }
414         catch(ErrnoException e) { return -e.errno; }
415         catch(FileNotFoundException e) { return -ENOENT; }
416         catch(IOException e) { return -EIO; }
417         catch(FaultException e) { return -EFAULT; }
418     }
419    
420     
421     private int sys_getcwd(int addr, int size) {
422         byte[] b = getBytes(cwd);
423         if(size == 0) return -EINVAL;
424         if(size < b.length+2) return -ERANGE;
425         try {
426             memset(addr,'/',1);
427             copyout(b,addr+1,b.length);
428             memset(addr+b.length+1,0,1);
429             return addr;
430         } catch(FaultException e) {
431             return -EFAULT;
432         }
433     }
434     
435     private int sys_chdir(int addr) {
436         try {
437             String path = normalizePath(cstring(addr));
438             System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
439             if(fs.stat(path).type() != FStat.S_IFDIR) return -ENOTDIR;
440             cwd = path;
441             System.err.println("Now: [" + cwd + "]");
442             return 0;
443         }
444         catch(ErrnoException e) { return -e.errno; }
445         catch(FileNotFoundException e) { return -ENOENT; }
446         catch(IOException e) { return -EIO; }
447         catch(FaultException e) { return -EFAULT; }
448     }
449
450     public void chdir(String dir) throws FileNotFoundException {
451         if(state != STOPPED) throw new IllegalStateException("Can't chdir while process is running");
452         try {
453             dir = normalizePath(dir);
454             if(fs.stat(dir).type() != FStat.S_IFDIR) throw new FileNotFoundException();
455         } catch(IOException e) {
456             throw new FileNotFoundException();
457         }
458         cwd = dir;
459     }
460         
461     public abstract static class FS {
462         protected FD _open(String path, int flags, int mode) throws IOException { return null; }
463         protected FStat _stat(String path) throws IOException { return null; }
464         protected void _mkdir(String path) throws IOException { throw new ErrnoException(EROFS); }
465         
466         protected static final int OPEN = 1;
467         protected static final int STAT = 2;
468         protected static final int MKDIR = 3;
469         
470         protected Object op(int op, String path, int arg1, int arg2) throws IOException {
471                         switch(op) {
472                                 case OPEN: return _open(path,arg1,arg2);
473                                 case STAT: return _stat(path);
474                                 case MKDIR: _mkdir(path); return null;
475                                 default: throw new IllegalArgumentException("Unknown FS OP");
476                         }
477         }
478         
479         public final FD open(String path, int flags, int mode) throws IOException { return (FD) op(OPEN,path,flags,mode); }
480         public final FStat stat(String path) throws IOException { return (FStat) op(STAT,path,0,0); }
481         public final void mkdir(String path) throws IOException { op(MKDIR,path,0,0); }
482         
483                 
484                 // FEATURE: inode stuff
485         // FEATURE: Implement whatever is needed to get newlib's opendir and friends to work - that patch is a pain
486         protected static FD directoryFD(String[] files, int hashCode) throws IOException {
487             ByteArrayOutputStream bos = new ByteArrayOutputStream();
488             DataOutputStream dos = new DataOutputStream(bos);
489             for(int i=0;i<files.length;i++) {
490                 byte[] b = getBytes(files[i]);
491                 int inode = (files[i].hashCode() ^ hashCode) & 0xfffff;
492                 dos.writeInt(inode);
493                 dos.writeInt(b.length);
494                 dos.write(b,0,b.length);
495             }
496             final byte[] data = bos.toByteArray();
497             return new SeekableFD(new Seekable.ByteArray(data,false),RD_ONLY) {
498                 protected FStat _fstat() { return  new FStat() {
499                     public int length() { return data.length; }
500                     public int type() { return S_IFDIR; }
501                 }; }
502             };
503         }
504     }
505         
506     private String normalizePath(String path) {
507         boolean absolute = path.startsWith("/");
508         int cwdl = cwd.length();
509         // NOTE: This isn't just a fast path, it handles cases the code below doesn't
510         if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
511             return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
512         
513         char[] in = new char[path.length()+1];
514         char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
515         int inp=0, outp=0;
516         
517         if(absolute) {
518             do { inp++; } while(in[inp] == '/');
519         } else if(cwdl != 0) {
520                 cwd.getChars(0,cwdl,out,0);
521                 outp = cwdl;
522         }
523             
524         path.getChars(0,path.length(),in,0);
525         while(in[inp] != 0) {
526             if(inp != 0) {
527                     if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
528                     while(in[inp] == '/') inp++;
529             }
530             if(in[inp] == '\0') continue;
531             if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
532             if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
533             if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
534                 inp += 2;
535                 if(outp > 0) outp--;
536                 while(outp > 0 && out[outp] != '/') outp--;
537                 System.err.println("After ..: " + new String(out,0,outp));
538                 continue;
539             }
540             inp++;
541             out[outp++] = '/';
542             out[outp++] = '.';
543         }
544         if(outp > 0 && out[outp-1] == '/') outp--;
545         //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
546         return new String(out,0,outp);
547     }
548     
549     public static class MountPointFS extends FS {
550         private static class MP {
551             public MP(String path, FS fs) { this.path = path; this.fs = fs; }
552             public String path;
553             public FS fs;
554             public int compareTo(Object o) {
555                 if(!(o instanceof MP)) return 1;
556                 return -path.compareTo(((MP)o).path);
557             }
558         }
559         private final MP[][] mps = new MP[128][];
560         private final FS root;
561         public MountPointFS(FS root) { this.root = root; }
562         
563         private static String fixup(String path) {
564             if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
565             path = path.substring(1);
566             if(path.length() == 0) throw new IllegalArgumentException("Zero length mount point path");
567             return path;
568         }
569         public synchronized FS get(String path) {
570             path = fixup(path);
571             int f = path.charAt(0) & 0x7f;
572             for(int i=0;mps[f] != null && i < mps[f].length;i++)
573                 if(mps[f][i].path.equals(path)) return mps[f][i].fs;
574             return null;
575         }
576         
577         public synchronized void add(String path, FS fs) {
578             if(get(path) != null) throw new IllegalArgumentException("mount point already exists");
579             path = fixup(path);
580             int f = path.charAt(0) & 0x7f;
581             int oldLength = mps[f] == null ? 0 : mps[f].length;
582             MP[] newList = new MP[oldLength + 1];
583             if(oldLength != 0) System.arraycopy(mps[f],0,newList,0,oldLength);
584             newList[oldLength] = new MP(path,fs);
585             Arrays.sort(newList);
586             mps[f] = newList;
587         }
588         
589         public synchronized void remove(String path) {
590             path = fixup(path);
591             if(get(path) == null) throw new IllegalArgumentException("mount point doesn't exist");
592             int f = path.charAt(0) & 0x7f;
593             MP[] oldList = mps[f];
594             MP[] newList = new MP[oldList.length - 1];
595             int p = 0;
596             for(p=0;p<oldList.length;p++) if(oldList[p].path.equals(path)) break;
597             if(p == oldList.length) throw new Error("should never happen");
598             System.arraycopy(oldList,0,newList,0,p);
599             System.arraycopy(oldList,0,newList,p,oldList.length-p-1);
600             mps[f] = newList;
601         }
602         
603         protected Object op(int op, String path, int arg1, int arg2) throws IOException {
604             int pl = path.length();
605             if(pl != 0) {
606                     MP[] list = mps[path.charAt(0) & 0x7f];
607                     if(list != null) for(int i=0;i<list.length;i++) {
608                                 MP mp = list[i];
609                                 int mpl = mp.path.length();
610                                 if(pl == mpl || (pl < mpl && path.charAt(mpl) == '/'))
611                                 return mp.fs.op(op,pl == mpl ? "" : path.substring(mpl+1),arg1,arg2);
612                  }
613             }
614             return root.op(op,path,arg1,arg2);
615         }
616     }
617         
618     public static class HostFS extends FS {
619         protected File root;
620         public File getRoot() { return root; }
621         
622         private static File hostRootDir() {
623             String cwd = getSystemProperty("user.dir");
624             File f = new File(cwd != null ? cwd : ".");
625             f = new File(f.getAbsolutePath());
626             while(f.getParent() != null) f = new File(f.getParent());
627             return f;
628         }
629         
630         File hostFile(String path) {
631             char sep = File.separatorChar;
632             if(sep != '/') {
633                 char buf[] = path.toCharArray();
634                 for(int i=0;i<buf.length;i++) {
635                             char c = buf[i];
636                     if(c == '/') buf[i] = sep;
637                     else if(c == sep) buf[i] = '/';
638                 }
639                 path = new String(buf);
640             }
641             return new File(root,path);
642         }
643         
644         public HostFS() { this(hostRootDir()); }
645         public HostFS(String root) { this(new File(root)); }
646         public HostFS(File root) { this.root = root; }
647         
648         
649         // FEATURE: This shares a lot with Runtime.open
650         // NOTE: createNewFile is a Java2 function
651         public FD _open(String path, int flags, int mode) throws IOException {
652             final File f = hostFile(path);
653             if(f.isDirectory()) {
654                 if((flags&3)!=RD_ONLY) throw new ErrnoException(EACCES);
655                 return directoryFD(f.list(),path.hashCode());
656             }
657             if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT))
658                 if(!f.createNewFile()) throw new ErrnoException(EEXIST);
659             if((flags&O_CREAT) == 0 && !f.exists())
660                 return null;
661             final Seekable.File sf = new Seekable.File(f,(flags&3)!=RD_ONLY);
662             if((flags&O_TRUNC)!=0) sf.setLength(0);
663             return new SeekableFD(sf,mode) {
664                 protected FStat _fstat() { return new HostFStat(f) {
665                     public int size() {
666                         try { return sf.length(); } catch(IOException e) { return 0; }
667                     }
668                 };}
669             };
670         }
671         
672         public FStat _stat(String path) throws FileNotFoundException {
673             File f = hostFile(path);
674             if(!f.exists()) throw new FileNotFoundException();
675             return new HostFStat(f);
676         }
677         
678         public void _mkdir(String path) throws IOException {
679             File f = hostFile(path);
680             if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
681             if(f.exists()) throw new ErrnoException(ENOTDIR);
682             File parent = f.getParentFile();
683             if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
684             if(!f.mkdir()) throw new ErrnoException(EIO);            
685         }
686     }
687         
688     private static class DevFStat extends FStat {
689         public int dev() { return 1; }
690         public int mode() { return 0666; }
691         public int type() { return S_IFCHR; }
692         public int nlink() { return 1; }
693     }
694     private static FD devZeroFD = new FD() {
695         public boolean readable() { return true; }
696         public boolean writable() { return true; }
697         public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
698         public int write(byte[] a, int off, int length) { return length; }
699         public int seek(int n, int whence) { return 0; }
700         public FStat _fstat() { return new DevFStat(); }
701     };
702     private static FD devNullFD = new FD() {
703         public boolean readable() { return true; }
704         public boolean writable() { return true; }
705         public int read(byte[] a, int off, int length) { return 0; }
706         public int write(byte[] a, int off, int length) { return length; }
707         public int seek(int n, int whence) { return 0; }
708         public FStat _fstat() { return new DevFStat(); }
709     };    
710     
711     // FIXME: Support /dev/fd (need to have syscalls pass along Runtime instance)
712     public static class DevFS extends FS {
713         public FD _open(String path, int mode, int flags) throws IOException {
714             if(path.equals("null")) return devNullFD;
715             if(path.equals("zero")) return devZeroFD;
716             /*if(path.startsWith("fd/")) {
717                 int n;
718                 try {
719                     n = Integer.parseInt(path.substring(4));
720                 } catch(NumberFormatException e) {
721                     throw new FileNotFoundException();
722                 }
723                 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
724                 if(fds[n] == null) throw new FileNotFoundException();
725                 return fds[n].dup();
726             }
727             if(path.equals("fd")) {
728                 int count=0;
729                 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) count++; 
730                 String[] files = new String[count];
731                 count = 0;
732                 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) files[count++] = Integer.toString(i);
733                 return directoryFD(files,hashCode());
734             }*/
735             if(path.equals("")) {
736                 String[] files = { "null", "zero", "fd" };
737                 return directoryFD(files,hashCode());
738             }
739             throw new FileNotFoundException();
740         }
741         
742         public FStat _stat(String path) throws IOException {
743             if(path.equals("null")) return devNullFD.fstat();
744             if(path.equals("zero")) return devZeroFD.fstat();            
745             /*if(path.startsWith("fd/")) {
746                 int n;
747                 try {
748                     n = Integer.parseInt(path.substring(4));
749                 } catch(NumberFormatException e) {
750                     throw new FileNotFoundException();
751                 }
752                 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
753                 if(fds[n] == null) throw new FileNotFoundException();
754                 return fds[n].fstat();
755             }
756             if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
757             */
758             if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
759             throw new FileNotFoundException();
760         }
761         
762         public void _mkdir(String path) throws IOException { throw new ErrnoException(EACCES); }
763     }
764 }