1 package org.ibex.nestedvm;
3 import org.ibex.nestedvm.util.*;
7 public abstract class UnixRuntime extends Runtime implements Cloneable {
8 /** The pid of this "process" */
10 private UnixRuntime parent;
11 public final int getPid() { return pid; }
13 private static final GlobalState defaultGS = new GlobalState();
14 private GlobalState gs = defaultGS;
15 public void setGlobalState(GlobalState gs) {
16 if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running");
20 /** proceses' current working directory - absolute path WITHOUT leading slash
21 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
24 /** The runtime that should be run next when in state == EXECED */
25 private UnixRuntime execedRuntime;
27 private Object children; // used only for synchronizatin
28 private Vector activeChildren;
29 private Vector exitedChildren;
31 protected UnixRuntime(int pageSize, int totalPages) {
32 super(pageSize,totalPages);
34 // FEATURE: Do the proper mangling for non-unix hosts
35 String userdir = getSystemProperty("user.dir");
36 cwd = userdir != null && userdir.startsWith("/") && File.separatorChar == '/' ? userdir.substring(1) : "";
39 // NOTE: getDisplayName() is a Java2 function
40 private static String posixTZ() {
41 StringBuffer sb = new StringBuffer();
42 TimeZone zone = TimeZone.getDefault();
43 int off = zone.getRawOffset() / 1000;
44 sb.append(zone.getDisplayName(false,TimeZone.SHORT));
45 if(off > 0) sb.append("-");
47 sb.append(off/3600); off = off%3600;
48 if(off > 0) sb.append(":").append(off/60); off=off%60;
49 if(off > 0) sb.append(":").append(off);
50 if(zone.useDaylightTime())
51 sb.append(zone.getDisplayName(true,TimeZone.SHORT));
55 private static boolean envHas(String key,String[] environ) {
56 for(int i=0;i<environ.length;i++)
57 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
61 String[] createEnv(String[] extra) {
62 String[] defaults = new String[5];
64 if(extra == null) extra = new String[0];
65 if(!envHas("USER",extra) && getSystemProperty("user.name") != null)
66 defaults[n++] = "USER=" + getSystemProperty("user.name");
67 if(!envHas("HOME",extra) && getSystemProperty("user.home") != null)
68 defaults[n++] = "HOME=" + getSystemProperty("user.home");
69 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
70 if(!envHas("TERM",extra)) defaults[n++] = "TERM=vt100";
71 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
72 String[] env = new String[extra.length+n];
73 for(int i=0;i<n;i++) env[i] = defaults[i];
74 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
78 private static class ProcessTableFullExn extends RuntimeException { }
81 UnixRuntime[] tasks = gs.tasks;
84 if(tasks[pid] == null || tasks[pid].pid != pid) throw new Error("should never happen");
87 int nextPID = gs.nextPID;
88 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
89 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
90 if(newpid == -1) throw new ProcessTableFullExn();
92 gs.nextPID = newpid + 1;
98 int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
100 case SYS_kill: return sys_kill(a,b);
101 case SYS_fork: return sys_fork();
102 case SYS_pipe: return sys_pipe(a);
103 case SYS_dup2: return sys_dup2(a,b);
104 case SYS_dup: return sys_dup(a);
105 case SYS_waitpid: return sys_waitpid(a,b,c);
106 case SYS_stat: return sys_stat(a,b);
107 case SYS_lstat: return sys_lstat(a,b);
108 case SYS_mkdir: return sys_mkdir(a,b);
109 case SYS_getcwd: return sys_getcwd(a,b);
110 case SYS_chdir: return sys_chdir(a);
111 case SYS_exec: return sys_exec(a,b,c);
112 case SYS_getdents: return sys_getdents(a,b,c,d);
114 default: return super._syscall(syscall,a,b,c,d);
118 FD _open(String path, int flags, int mode) throws ErrnoException {
119 return gs.open(this,normalizePath(path),flags,mode);
122 /** The kill syscall.
123 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
124 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
125 Anything else terminates the process. */
126 private int sys_kill(int pid, int signal) {
127 // This will only be called by raise() in newlib to invoke the default handler
128 // We don't have to worry about actually delivering the signal
129 if(pid != pid) return -ESRCH;
130 if(signal < 0 || signal >= 32) return -EINVAL;
145 return syscall(SYS_exit,128+signal,0,0,0);
150 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
151 final int WNOHANG = 1;
152 if((options & ~(WNOHANG)) != 0) return -EINVAL;
153 if(pid == 0 || pid < -1) {
154 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
157 boolean blocking = (options&WNOHANG)==0;
159 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
160 if(children == null) return blocking ? -ECHILD : 0;
162 UnixRuntime done = null;
164 synchronized(children) {
167 if(exitedChildren.size() > 0) done = (UnixRuntime)exitedChildren.remove(exitedChildren.size() - 1);
169 UnixRuntime t = gs.tasks[pid];
170 if(t.parent != this) return -ECHILD;
171 if(t.state == EXITED) {
172 if(!exitedChildren.remove(t)) throw new Error("should never happen");
176 // process group stuff, EINVAL returned above
177 throw new Error("should never happen");
180 if(!blocking) return 0;
181 try { children.wait(); } catch(InterruptedException e) {}
182 //System.err.println("waitpid woke up: " + exitedChildren.size());
184 gs.tasks[done.pid] = null;
189 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
195 if(children != null) synchronized(children) {
196 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
197 UnixRuntime child = (UnixRuntime) e.nextElement();
198 gs.tasks[child.pid] = null;
200 exitedChildren.clear();
201 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
202 UnixRuntime child = (UnixRuntime) e.nextElement();
205 activeChildren.clear();
208 UnixRuntime _parent = parent;
209 if(_parent == null) {
210 gs.tasks[pid] = null;
212 synchronized(_parent.children) {
214 gs.tasks[pid] = null;
216 parent.activeChildren.remove(this);
217 parent.exitedChildren.add(this);
218 parent.children.notify();
224 protected Object clone() throws CloneNotSupportedException {
225 UnixRuntime r = (UnixRuntime) super.clone();
229 r.activeChildren = r.exitedChildren = null;
233 private int sys_fork() {
234 CPUState state = new CPUState();
236 int sp = state.r[SP];
240 r = (UnixRuntime) clone();
241 } catch(Exception e) {
250 } catch(ProcessTableFullExn e) {
254 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
255 if(children == null) {
256 children = new Object();
257 activeChildren = new Vector();
258 exitedChildren = new Vector();
260 activeChildren.add(r);
262 state.r[V0] = 0; // return 0 to child
263 state.pc += 4; // skip over syscall instruction
264 r.setCPUState(state);
267 new ForkedProcess(r);
272 public static final class ForkedProcess extends Thread {
273 private final UnixRuntime initial;
274 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
275 public void run() { UnixRuntime.executeAndExec(initial); }
278 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
279 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
281 public static int executeAndExec(UnixRuntime r) {
284 if(r.execute()) break;
285 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
287 if(r.state != EXECED) return r.exitStatus();
292 private String[] readStringArray(int addr) throws ReadFaultException {
294 for(int p=addr;memRead(p) != 0;p+=4) count++;
295 String[] a = new String[count];
296 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
300 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
301 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
304 private int exec(String normalizedPath, String[] argv, String[] envp) throws ErrnoException {
305 if(argv.length == 0) argv = new String[]{""};
307 Object o = gs.exec(this,normalizedPath);
308 if(o == null) return -ENOENT;
310 if(o instanceof Class) {
313 return exec((UnixRuntime) c.newInstance(),argv,envp);
314 } catch(Exception e) {
319 String[] command = (String[]) o;
320 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
321 int p = command[0].lastIndexOf('/');
322 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
324 if(command[1] != null) newArgv[p++] = command[1];
325 newArgv[p++] = "/" + normalizedPath;
326 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
327 return exec(command[0],newArgv,envp);
331 private int exec(UnixRuntime r, String[] argv, String[] envp) {
333 //System.err.println("Execing " + r);
334 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
336 r.closeOnExec = closeOnExec;
337 // make sure this doesn't get messed with these since we didn't copy them
354 // FEATURE: Make sure fstat info is correct
355 // FEATURE: This could be faster if we did direct copies from each process' memory
356 // FEATURE: Check this logic one more time
357 public static class Pipe {
358 private final byte[] pipebuf = new byte[PIPE_BUF*4];
360 private int writePos;
362 public final FD reader = new Reader();
363 public final FD writer = new Writer();
365 public class Reader extends FD {
366 protected FStat _fstat() { return new FStat(); }
367 public int read(byte[] buf, int off, int len) throws ErrnoException {
368 if(len == 0) return 0;
369 synchronized(Pipe.this) {
370 while(writePos != -1 && readPos == writePos) {
371 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
373 if(writePos == -1) return 0; // eof
374 len = Math.min(len,writePos-readPos);
375 System.arraycopy(pipebuf,readPos,buf,off,len);
377 if(readPos == writePos) Pipe.this.notify();
381 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
384 public class Writer extends FD {
385 protected FStat _fstat() { return new FStat(); }
386 public int write(byte[] buf, int off, int len) throws ErrnoException {
387 if(len == 0) return 0;
388 synchronized(Pipe.this) {
389 if(readPos == -1) throw new ErrnoException(EPIPE);
390 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
391 // not enough space to atomicly write the data
392 while(readPos != -1 && readPos != writePos) {
393 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
395 if(readPos == -1) throw new ErrnoException(EPIPE);
396 readPos = writePos = 0;
398 len = Math.min(len,pipebuf.length - writePos);
399 System.arraycopy(buf,off,pipebuf,writePos,len);
400 if(readPos == writePos) Pipe.this.notify();
405 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
409 private int sys_pipe(int addr) {
410 Pipe pipe = new Pipe();
412 int fd1 = addFD(pipe.reader);
413 if(fd1 < 0) return -ENFILE;
414 int fd2 = addFD(pipe.writer);
415 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
419 memWrite(addr+4,fd2);
420 } catch(FaultException e) {
428 private int sys_dup2(int oldd, int newd) {
429 if(oldd == newd) return 0;
430 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
431 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
432 if(fds[oldd] == null) return -EBADFD;
433 if(fds[newd] != null) fds[newd].close();
434 fds[newd] = fds[oldd].dup();
438 private int sys_dup(int oldd) {
439 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
440 if(fds[oldd] == null) return -EBADFD;
441 FD fd = fds[oldd].dup();
442 int newd = addFD(fd);
443 if(newd < 0) { fd.close(); return -ENFILE; }
447 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
448 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
449 if(s == null) return -ENOENT;
453 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
454 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
455 if(s == null) return -ENOENT;
459 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
460 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
464 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
465 byte[] b = getBytes(cwd);
466 if(size == 0) return -EINVAL;
467 if(size < b.length+2) return -ERANGE;
469 copyout(b,addr+1,b.length);
470 memset(addr+b.length+1,0,1);
474 private int sys_chdir(int addr) throws ErrnoException, FaultException {
475 String path = normalizePath(cstring(addr));
476 //System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
477 if(gs.stat(this,path).type() != FStat.S_IFDIR) return -ENOTDIR;
479 //System.err.println("Now: [" + cwd + "]");
483 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
484 count = Math.min(count,MAX_CHUNK);
485 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
486 if(fds[fdn] == null) return -EBADFD;
487 byte[] buf = byteBuf(count);
488 int n = fds[fdn].getdents(buf,0,count);
493 // FEATURE: Run through the fork/wait stuff one more time
494 public static class GlobalState {
495 protected static final int OPEN = 1;
496 protected static final int STAT = 2;
497 protected static final int LSTAT = 3;
498 protected static final int MKDIR = 4;
500 final UnixRuntime[] tasks;
503 private MP[] mps = new MP[0];
506 public GlobalState() { this(255); }
507 public GlobalState(int maxProcs) { this(maxProcs,true); }
508 public GlobalState(int maxProcs, boolean defaultMounts) {
509 tasks = new UnixRuntime[maxProcs+1];
511 addMount("/",new HostFS());
512 addMount("/dev",new DevFS());
516 private static class MP {
517 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
520 public int compareTo(Object o) {
521 if(!(o instanceof MP)) return 1;
522 return -path.compareTo(((MP)o).path);
526 public synchronized FS getMount(String path) {
527 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
528 if(path.equals("/")) return root;
529 path = path.substring(1);
530 for(int i=0;i<mps.length;i++)
531 if(mps[i].path.equals(path)) return mps[i].fs;
535 public synchronized void addMount(String path, FS fs) {
536 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
537 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
539 if(fs.owner != null) fs.owner.removeMount(fs);
542 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
543 path = path.substring(1);
544 int oldLength = mps.length;
545 MP[] newMPS = new MP[oldLength + 1];
546 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
547 newMPS[oldLength] = new MP(path,fs);
551 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
552 fs.devno = highdevno + 2;
555 public synchronized void removeMount(FS fs) {
556 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
557 throw new IllegalArgumentException("mount point doesn't exist");
560 public synchronized void removeMount(String path) {
561 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
562 if(path.equals("/")) {
565 path = path.substring(1);
567 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
568 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
573 private void removeMount(int index) {
574 if(index == -1) { root.owner = null; root = null; return; }
575 MP[] newMPS = new MP[mps.length - 1];
576 System.arraycopy(mps,0,newMPS,0,index);
577 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
581 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
582 int pl = normalizedPath.length();
585 synchronized(this) { list = mps; }
586 for(int i=0;i<list.length;i++) {
588 int mpl = mp.path.length();
589 if(normalizedPath.startsWith(mp.path) && (pl == mpl || (pl < mpl && normalizedPath.charAt(mpl) == '/')))
590 return dispatch(mp.fs,op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
593 return dispatch(root,op,r,normalizedPath,arg1,arg2);
596 private static Object dispatch(FS fs, int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
598 case OPEN: return fs.open(r,path,arg1,arg2);
599 case STAT: return fs.stat(r,path);
600 case LSTAT: return fs.lstat(r,path);
601 case MKDIR: fs.mkdir(r,path,arg1); return null;
602 default: throw new Error("should never happen");
606 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(OPEN,r,path,flags,mode); }
607 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(STAT,r,path,0,0); }
608 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(LSTAT,r,path,0,0); }
609 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(MKDIR,r,path,mode,0); }
611 private Hashtable execCache = new Hashtable();
612 private static class CacheEnt {
613 public final long time;
614 public final long size;
615 public final Object o;
616 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
619 public synchronized Object exec(UnixRuntime r, String path) throws ErrnoException {
620 FStat fstat = stat(r,path);
621 if(fstat == null) return null;
622 long mtime = fstat.mtime();
623 long size = fstat.size();
624 CacheEnt ent = (CacheEnt) execCache.get(path);
626 //System.err.println("Found cached entry for " + path);
627 if(ent.time == mtime && ent.size == size) return ent.o;
628 //System.err.println("Cache was out of date");
629 execCache.remove(path);
631 FD fd = open(r,path,RD_ONLY,0);
632 if(fd == null) return null;
633 Seekable s = fd.seekable();
635 String[] command = null;
637 if(s == null) throw new ErrnoException(EACCES);
638 byte[] buf = new byte[4096];
641 int n = s.read(buf,0,buf.length);
642 if(n == -1) throw new ErrnoException(ENOEXEC);
645 case '\177': // possible ELF
646 if(n < 4 && s.tryReadFully(buf,n,4-n) != 4-n) throw new ErrnoException(ENOEXEC);
647 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') throw new ErrnoException(ENOEXEC);
651 int n2 = s.read(buf,1,buf.length-1);
652 if(n2 == -1) throw new ErrnoException(ENOEXEC);
655 if(buf[1] != '!') throw new ErrnoException(ENOEXEC);
659 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
661 if(p == buf.length) break OUTER;
662 n = s.read(buf,p,buf.length-p);
664 command = new String[2];
666 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
669 while(arg < p && buf[arg] == ' ') arg++;
670 command[0] = new String(buf,2,cmdEnd);
671 command[1] = arg < p ? new String(buf,arg,p-arg) : null;
673 command[0] = new String(buf,2,p-2);
675 //System.err.println("command[0]: " + command[0] + " command[1]: " + command[1]);
678 throw new ErrnoException(ENOEXEC);
680 } catch(IOException e) {
682 throw new ErrnoException(EIO);
685 if(command == null) {
689 Class c = RuntimeCompiler.compile(s);
690 //System.err.println("Compile succeeded: " + c);
691 ent = new CacheEnt(mtime,size,c);
692 } catch(Compiler.Exn e) {
693 if(STDERR_DIAG) e.printStackTrace();
694 throw new ErrnoException(ENOEXEC);
695 } catch(IOException e) {
696 if(STDERR_DIAG) e.printStackTrace();
697 throw new ErrnoException(EIO);
700 ent = new CacheEnt(mtime,size,command);
705 execCache.put(path,ent);
710 public abstract static class FS {
714 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
716 // If this returns null it'll be truned into an ENOENT
717 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
718 // If this returns null it'll be turned into an ENOENT
719 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
720 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
723 // FEATURE: chroot support in here
724 private String normalizePath(String path) {
725 boolean absolute = path.startsWith("/");
726 int cwdl = cwd.length();
727 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
728 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
729 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
731 char[] in = new char[path.length()+1];
732 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
736 do { inp++; } while(in[inp] == '/');
737 } else if(cwdl != 0) {
738 cwd.getChars(0,cwdl,out,0);
742 path.getChars(0,path.length(),in,0);
743 while(in[inp] != 0) {
745 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
746 while(in[inp] == '/') inp++;
748 if(in[inp] == '\0') continue;
749 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
750 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
751 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
754 while(outp > 0 && out[outp] != '/') outp--;
755 //System.err.println("After ..: " + new String(out,0,outp));
762 if(outp > 0 && out[outp-1] == '/') outp--;
763 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
764 return new String(out,0,outp);
767 FStat hostFStat(final File f, Object data) {
770 FileInputStream fis = new FileInputStream(f);
772 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
773 case '#': e = fis.read() == '!';
776 } catch(IOException e2) { }
777 HostFS fs = (HostFS) data;
778 final int inode = fs.inodes.get(f.getAbsolutePath());
779 final int devno = fs.devno;
780 return new HostFStat(f,e) {
781 public int inode() { return inode; }
782 public int dev() { return devno; }
786 FD hostFSDirFD(File f, Object _fs) {
787 HostFS fs = (HostFS) _fs;
788 return fs.new HostDirFD(f);
791 public static class HostFS extends FS {
792 InodeCache inodes = new InodeCache(4000);
794 public File getRoot() { return root; }
796 private static File hostRootDir() {
797 String cwd = getSystemProperty("user.dir");
798 File f = new File(cwd != null ? cwd : ".");
799 f = new File(f.getAbsolutePath());
800 while(f.getParent() != null) f = new File(f.getParent());
804 private File hostFile(String path) {
805 char sep = File.separatorChar;
807 char buf[] = path.toCharArray();
808 for(int i=0;i<buf.length;i++) {
810 if(c == '/') buf[i] = sep;
811 else if(c == sep) buf[i] = '/';
813 path = new String(buf);
815 return new File(root,path);
818 public HostFS() { this(hostRootDir()); }
819 public HostFS(String root) { this(new File(root)); }
820 public HostFS(File root) { this.root = root; }
823 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
824 final File f = hostFile(path);
825 return r.hostFSOpen(f,flags,mode,this);
828 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
829 File f = hostFile(path);
830 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
831 if(!f.exists()) return null;
832 return r.hostFStat(f,this);
835 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
836 File f = hostFile(path);
837 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
838 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
839 if(f.exists()) throw new ErrnoException(ENOTDIR);
840 File parent = f.getParentFile();
841 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
842 if(!f.mkdir()) throw new ErrnoException(EIO);
845 public class HostDirFD extends DirFD {
846 private final File f;
847 private final File[] children;
848 public HostDirFD(File f) { this.f = f; children = f.listFiles(); }
849 public int size() { return children.length; }
850 public String name(int n) { return children[n].getName(); }
851 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
852 public int parentInode() {
853 File parent = f.getParentFile();
854 return parent == null ? -1 : inodes.get(parent.getAbsolutePath());
856 public int myInode() { return inodes.get(f.getAbsolutePath()); }
857 public int myDev() { return devno; }
861 private static void putInt(byte[] buf, int off, int n) {
862 buf[off+0] = (byte)((n>>>24)&0xff);
863 buf[off+1] = (byte)((n>>>16)&0xff);
864 buf[off+2] = (byte)((n>>> 8)&0xff);
865 buf[off+3] = (byte)((n>>> 0)&0xff);
868 public static abstract class DirFD extends FD {
869 private int pos = -2;
871 protected abstract int size();
872 protected abstract String name(int n);
873 protected abstract int inode(int n);
874 protected abstract int myDev();
875 protected int parentInode() { return -1; }
876 protected int myInode() { return -1; }
878 public int getdents(byte[] buf, int off, int len) {
882 OUTER: for(;len > 0 && pos < size();pos++){
886 ino = pos == -1 ? parentInode() : myInode();
887 if(ino == -1) continue;
888 reclen = 9 + (pos == -1 ? 2 : 1);
889 if(reclen > len) break OUTER;
891 if(pos == -1) buf[off+9] = '.';
894 String f = name(pos);
895 byte[] fb = getBytes(f);
896 reclen = fb.length + 9;
897 if(reclen > len) break OUTER;
899 System.arraycopy(fb,0,buf,off+8,fb.length);
902 buf[off+reclen-1] = 0; // null terminate
903 reclen = (reclen + 3) & ~3; // add padding
904 putInt(buf,off,reclen);
905 putInt(buf,off+4,ino);
912 protected FStat _fstat() {
914 public int type() { return S_IFDIR; }
915 public int inode() { return myInode(); }
916 public int dev() { return myDev(); }
921 public static class DevFS extends FS {
922 private static final int ROOT_INODE = 1;
923 private static final int NULL_INODE = 2;
924 private static final int ZERO_INODE = 3;
925 private static final int FD_INODE = 4;
926 private static final int FD_INODES = 32;
928 private class DevFStat extends FStat {
929 public int dev() { return devno; }
930 public int mode() { return 0666; }
931 public int type() { return S_IFCHR; }
932 public int nlink() { return 1; }
935 private abstract class DevDirFD extends DirFD {
936 public int myDev() { return devno; }
939 private FD devZeroFD = new FD() {
940 public boolean readable() { return true; }
941 public boolean writable() { return true; }
942 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
943 public int write(byte[] a, int off, int length) { return length; }
944 public int seek(int n, int whence) { return 0; }
945 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
947 private FD devNullFD = new FD() {
948 public boolean readable() { return true; }
949 public boolean writable() { return true; }
950 public int read(byte[] a, int off, int length) { return 0; }
951 public int write(byte[] a, int off, int length) { return length; }
952 public int seek(int n, int whence) { return 0; }
953 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
956 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
957 if(path.equals("null")) return devNullFD;
958 if(path.equals("zero")) return devZeroFD;
959 if(path.startsWith("fd/")) {
962 n = Integer.parseInt(path.substring(4));
963 } catch(NumberFormatException e) {
966 if(n < 0 || n >= OPEN_MAX) return null;
967 if(r.fds[n] == null) return null;
968 return r.fds[n].dup();
970 if(path.equals("fd")) {
972 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
973 final int[] files = new int[count];
975 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
976 return new DevDirFD() {
977 public int myInode() { return FD_INODE; }
978 public int parentInode() { return ROOT_INODE; }
979 public int inode(int n) { return FD_INODES + n; }
980 public String name(int n) { return Integer.toString(files[n]); }
981 public int size() { return files.length; }
984 if(path.equals("")) {
985 return new DevDirFD() {
986 public int myInode() { return ROOT_INODE; }
987 // FEATURE: Get the real parent inode somehow
988 public int parentInode() { return -1; }
989 public int inode(int n) {
991 case 0: return NULL_INODE;
992 case 1: return ZERO_INODE;
993 case 2: return FD_INODE;
998 public String name(int n) {
1000 case 0: return "null";
1001 case 1: return "zero";
1002 case 2: return "fd";
1003 default: return null;
1006 public int size() { return 3; }
1012 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1013 if(path.equals("null")) return devNullFD.fstat();
1014 if(path.equals("zero")) return devZeroFD.fstat();
1015 if(path.startsWith("fd/")) {
1018 n = Integer.parseInt(path.substring(4));
1019 } catch(NumberFormatException e) {
1022 if(n < 0 || n >= OPEN_MAX) return null;
1023 if(r.fds[n] == null) return null;
1024 return r.fds[n].fstat();
1026 // FEATURE: inode stuff
1027 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1028 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1032 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EACCES); }