1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
5 package org.ibex.nestedvm;
7 import org.ibex.nestedvm.util.*;
8 // HACK: This is ugly, this stuff needs to be in org.ibex.util or something
9 import org.ibex.classgen.util.Sort;
13 import java.lang.reflect.*; // For lazily linked RuntimeCompiler
17 public abstract class UnixRuntime extends Runtime implements Cloneable {
18 /** The pid of this "process" */
20 private UnixRuntime parent;
21 public final int getPid() { return pid; }
23 private static final GlobalState defaultGS = new GlobalState();
24 private GlobalState gs;
25 public void setGlobalState(GlobalState gs) {
26 if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running");
27 if(gs == null) throw new NullPointerException("gs is null");
31 /** proceses' current working directory - absolute path WITHOUT leading slash
32 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
35 /** The runtime that should be run next when in state == EXECED */
36 private UnixRuntime execedRuntime;
38 private Object children; // used only for synchronizatin
39 private Vector activeChildren;
40 private Vector exitedChildren;
42 protected UnixRuntime(int pageSize, int totalPages) { this(pageSize,totalPages,false); }
43 protected UnixRuntime(int pageSize, int totalPages, boolean exec) {
44 super(pageSize,totalPages,exec);
48 String userdir = Platform.getProperty("user.dir");
49 String nvroot = Platform.getProperty("nestedvm.root");
51 if(userdir != null && nvroot == null) {
52 if(userdir.startsWith("/") && File.separatorChar == '/') {
53 cwd = userdir.substring(1);
55 Vector vec = new Vector();
56 File root = HostFS.hostRootDir();
57 String s = new File(userdir).getAbsolutePath();
59 System.err.println(s);
60 System.err.println(d);
61 while(!d.equals(root)) {
62 System.err.println("Got " + d.getName());
63 vec.addElement(d.getName());
64 if((s = d.getParent()) == null) break;
68 for(int i=vec.size()-1;i>=0;i--) cwd += (String) vec.elementAt(i) + (i==0?"":"/");
74 private static String posixTZ() {
75 StringBuffer sb = new StringBuffer();
76 TimeZone zone = TimeZone.getDefault();
77 int off = zone.getRawOffset() / 1000;
78 sb.append(Platform.timeZoneGetDisplayName(zone,false,false));
79 if(off > 0) sb.append("-");
81 sb.append(off/3600); off = off%3600;
82 if(off > 0) sb.append(":").append(off/60); off=off%60;
83 if(off > 0) sb.append(":").append(off);
84 if(zone.useDaylightTime())
85 sb.append(Platform.timeZoneGetDisplayName(zone,true,false));
89 private static boolean envHas(String key,String[] environ) {
90 for(int i=0;i<environ.length;i++)
91 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
95 String[] createEnv(String[] extra) {
96 String[] defaults = new String[6];
98 if(extra == null) extra = new String[0];
99 if(!envHas("USER",extra) && Platform.getProperty("user.name") != null)
100 defaults[n++] = "USER=" + Platform.getProperty("user.name");
101 if(!envHas("HOME",extra) && Platform.getProperty("user.home") != null)
102 defaults[n++] = "HOME=" + Platform.getProperty("user.home");
103 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
104 if(!envHas("TERM",extra) && !win32Hacks) defaults[n++] = "TERM=vt100";
105 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
106 if(!envHas("PATH",extra)) defaults[n++] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin";
107 String[] env = new String[extra.length+n];
108 for(int i=0;i<n;i++) env[i] = defaults[i];
109 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
113 private static class ProcessTableFullExn extends RuntimeException { }
116 UnixRuntime[] tasks = gs.tasks;
119 UnixRuntime prev = tasks[pid];
120 if(prev == null || prev == this || prev.pid != pid || prev.parent != parent)
121 throw new Error("should never happen");
122 synchronized(parent.children) {
123 int i = parent.activeChildren.indexOf(prev);
124 if(i == -1) throw new Error("should never happen");
125 parent.activeChildren.setElementAt(this,i);
129 int nextPID = gs.nextPID;
130 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
131 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
132 if(newpid == -1) throw new ProcessTableFullExn();
134 gs.nextPID = newpid + 1;
140 int _syscall(int syscall, int a, int b, int c, int d, int e, int f) throws ErrnoException, FaultException {
142 case SYS_kill: return sys_kill(a,b);
143 case SYS_fork: return sys_fork();
144 case SYS_pipe: return sys_pipe(a);
145 case SYS_dup2: return sys_dup2(a,b);
146 case SYS_dup: return sys_dup(a);
147 case SYS_waitpid: return sys_waitpid(a,b,c);
148 case SYS_stat: return sys_stat(a,b);
149 case SYS_lstat: return sys_lstat(a,b);
150 case SYS_mkdir: return sys_mkdir(a,b);
151 case SYS_getcwd: return sys_getcwd(a,b);
152 case SYS_chdir: return sys_chdir(a);
153 case SYS_exec: return sys_exec(a,b,c);
154 case SYS_getdents: return sys_getdents(a,b,c,d);
155 case SYS_unlink: return sys_unlink(a);
156 case SYS_getppid: return sys_getppid();
157 case SYS_socket: return sys_socket(a,b,c);
158 case SYS_connect: return sys_connect(a,b,c);
159 case SYS_resolve_hostname: return sys_resolve_hostname(a,b,c);
160 case SYS_setsockopt: return sys_setsockopt(a,b,c,d,e);
161 case SYS_getsockopt: return sys_getsockopt(a,b,c,d,e);
162 case SYS_bind: return sys_bind(a,b,c);
163 case SYS_listen: return sys_listen(a,b);
164 case SYS_accept: return sys_accept(a,b,c);
165 case SYS_shutdown: return sys_shutdown(a,b);
166 case SYS_sysctl: return sys_sysctl(a,b,c,d,e,f);
167 case SYS_sendto: return sys_sendto(a,b,c,d,e,f);
168 case SYS_recvfrom: return sys_recvfrom(a,b,c,d,e,f);
169 case SYS_select: return sys_select(a,b,c,d,e);
170 case SYS_access: return sys_access(a,b);
171 case SYS_realpath: return sys_realpath(a,b);
173 default: return super._syscall(syscall,a,b,c,d,e,f);
177 FD _open(String path, int flags, int mode) throws ErrnoException {
178 return gs.open(this,normalizePath(path),flags,mode);
181 private int sys_getppid() {
182 return parent == null ? 1 : parent.pid;
186 private int sys_access(int cstring, int mode) {
187 // FEATURE: sys_access
191 private int sys_realpath(int inAddr, int outAddr) throws FaultException {
192 String s = normalizePath(cstring(inAddr));
193 byte[] b = getNullTerminatedBytes(s);
194 if(b.length > PATH_MAX) return -ERANGE;
195 copyout(b,outAddr,b.length);
199 // FEATURE: Signal handling
200 // check flag only on backwards jumps to basic blocks without compulsatory checks
201 // (see A Portable Research Framework for the Execution of Java Bytecode - Etienne Gagnon, Chapter 2)
203 /** The kill syscall.
204 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
205 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
206 Anything else terminates the process. */
207 private int sys_kill(int pid, int signal) {
208 // This will only be called by raise() in newlib to invoke the default handler
209 // We don't have to worry about actually delivering the signal
210 if(pid != pid) return -ESRCH;
211 if(signal < 0 || signal >= 32) return -EINVAL;
224 exit(128+signal, true);
229 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
230 final int WNOHANG = 1;
231 if((options & ~(WNOHANG)) != 0) return -EINVAL;
232 if(pid == 0 || pid < -1) {
233 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
236 boolean blocking = (options&WNOHANG)==0;
238 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
239 if(children == null) return blocking ? -ECHILD : 0;
241 UnixRuntime done = null;
243 synchronized(children) {
246 if(exitedChildren.size() > 0) {
247 done = (UnixRuntime)exitedChildren.elementAt(exitedChildren.size() - 1);
248 exitedChildren.removeElementAt(exitedChildren.size() - 1);
251 if(pid >= gs.tasks.length) return -ECHILD;
252 UnixRuntime t = gs.tasks[pid];
253 if(t.parent != this) return -ECHILD;
254 if(t.state == EXITED) {
255 if(!exitedChildren.removeElement(t)) throw new Error("should never happen");
259 // process group stuff, EINVAL returned above
260 throw new Error("should never happen");
263 if(!blocking) return 0;
264 try { children.wait(); } catch(InterruptedException e) {}
265 //System.err.println("waitpid woke up: " + exitedChildren.size());
267 gs.tasks[done.pid] = null;
272 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
278 if(children != null) synchronized(children) {
279 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
280 UnixRuntime child = (UnixRuntime) e.nextElement();
281 gs.tasks[child.pid] = null;
283 exitedChildren.removeAllElements();
284 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
285 UnixRuntime child = (UnixRuntime) e.nextElement();
288 activeChildren.removeAllElements();
291 UnixRuntime _parent = parent;
292 if(_parent == null) {
293 gs.tasks[pid] = null;
295 synchronized(_parent.children) {
297 gs.tasks[pid] = null;
299 if(!parent.activeChildren.removeElement(this)) throw new Error("should never happen _exited: pid: " + pid);
300 parent.exitedChildren.addElement(this);
301 parent.children.notify();
307 protected Object clone() throws CloneNotSupportedException {
308 UnixRuntime r = (UnixRuntime) super.clone();
312 r.activeChildren = r.exitedChildren = null;
316 private int sys_fork() {
320 r = (UnixRuntime) clone();
321 } catch(Exception e) {
330 } catch(ProcessTableFullExn e) {
334 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
335 if(children == null) {
336 children = new Object();
337 activeChildren = new Vector();
338 exitedChildren = new Vector();
340 activeChildren.addElement(r);
342 CPUState state = new CPUState();
344 state.r[V0] = 0; // return 0 to child
345 state.pc += 4; // skip over syscall instruction
346 r.setCPUState(state);
349 new ForkedProcess(r);
354 public static final class ForkedProcess extends Thread {
355 private final UnixRuntime initial;
356 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
357 public void run() { UnixRuntime.executeAndExec(initial); }
360 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
361 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
363 public static int executeAndExec(UnixRuntime r) {
366 if(r.execute()) break;
367 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
369 if(r.state != EXECED) return r.exitStatus();
374 private String[] readStringArray(int addr) throws ReadFaultException {
376 for(int p=addr;memRead(p) != 0;p+=4) count++;
377 String[] a = new String[count];
378 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
382 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
383 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
386 private final static Method runtimeCompilerCompile;
390 m = Class.forName("org.ibex.nestedvm.RuntimeCompiler").getMethod("compile",new Class[]{Seekable.class,String.class});
391 } catch(NoSuchMethodException e) {
393 } catch(ClassNotFoundException e) {
396 runtimeCompilerCompile = m;
399 public Class runtimeCompile(Seekable s) throws IOException {
400 if(runtimeCompilerCompile == null) {
401 if(STDERR_DIAG) System.err.println("WARNING: Exec attempted but RuntimeCompiler not found!");
406 return (Class) runtimeCompilerCompile.invoke(null,new Object[]{s,"unixruntime"});
407 } catch(IllegalAccessException e) {
410 } catch(InvocationTargetException e) {
411 Throwable t = e.getTargetException();
412 if(t instanceof IOException) throw (IOException) t;
413 if(t instanceof RuntimeException) throw (RuntimeException) t;
414 if(t instanceof Error) throw (Error) t;
415 if(STDERR_DIAG) t.printStackTrace();
420 private int exec(String path, String[] argv, String[] envp) throws ErrnoException {
421 if(argv.length == 0) argv = new String[]{""};
422 // HACK: Hideous hack to make a standalone busybox possible
423 if(path.equals("bin/busybox") && getClass().getName().endsWith("BusyBox"))
424 return execClass(getClass(),argv,envp);
426 // NOTE: For this little hack to work nestedvm.root MUST be "."
428 System.err.println("Execing normalized path: " + normalizedPath);
429 if(true) return exec(new Interpreter(normalizedPath),argv,envp);
430 } catch(IOException e) { throw new Error(e); }*/
432 FStat fstat = gs.stat(this,path);
433 if(fstat == null) return -ENOENT;
434 GlobalState.CacheEnt ent = (GlobalState.CacheEnt) gs.execCache.get(path);
435 long mtime = fstat.mtime();
436 long size = fstat.size();
438 //System.err.println("Found cached entry for " + path);
439 if(ent.time ==mtime && ent.size == size) {
440 if(ent.o instanceof Class)
441 return execClass((Class) ent.o,argv,envp);
442 if(ent.o instanceof String[])
443 return execScript(path,(String[]) ent.o,argv,envp);
444 throw new Error("should never happen");
446 //System.err.println("Cache was out of date");
447 gs.execCache.remove(path);
450 FD fd = gs.open(this,path,RD_ONLY,0);
451 if(fd == null) throw new ErrnoException(ENOENT);
452 Seekable s = fd.seekable();
453 if(s == null) throw new ErrnoException(EACCES);
455 byte[] buf = new byte[4096];
458 int n = s.read(buf,0,buf.length);
459 if(n == -1) throw new ErrnoException(ENOEXEC);
462 case '\177': // possible ELF
463 if(n < 4) s.tryReadFully(buf,n,4-n);
464 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') return -ENOEXEC;
466 Class c = runtimeCompile(s);
467 if(c == null) throw new ErrnoException(ENOEXEC);
468 gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,c));
469 return execClass(c,argv,envp);
472 int n2 = s.read(buf,1,buf.length-1);
473 if(n2 == -1) return -ENOEXEC;
476 if(buf[1] != '!') return -ENOEXEC;
480 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
482 if(p == buf.length) break OUTER;
483 n = s.read(buf,p,buf.length-p);
486 for(arg=2;arg<p;arg++) if(buf[arg] == ' ') break;
488 while(arg < p && buf[arg] == ' ') arg++;
489 String[] command = new String[] {
490 new String(buf,2,cmdEnd),
491 arg < p ? new String(buf,arg,p-arg) : null
493 gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,command));
494 return execScript(path,command,argv,envp);
498 } catch(IOException e) {
505 public int execScript(String path, String[] command, String[] argv, String[] envp) throws ErrnoException {
506 String[] newArgv = new String[argv.length + command[1] != null ? 2 : 1];
507 int p = command[0].lastIndexOf('/');
508 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
510 if(command[1] != null) newArgv[p++] = command[1];
511 newArgv[p++] = "/" + path;
512 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
513 return exec(command[0],newArgv,envp);
516 public int execClass(Class c,String[] argv, String[] envp) {
518 UnixRuntime r = (UnixRuntime) c.getDeclaredConstructor(new Class[]{Boolean.TYPE}).newInstance(new Object[]{Boolean.TRUE});
519 return exec(r,argv,envp);
520 } catch(Exception e) {
526 private int exec(UnixRuntime r, String[] argv, String[] envp) {
527 //System.err.println("Execing " + r);
528 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
530 r.closeOnExec = closeOnExec;
531 // make sure this doesn't get messed with these since we didn't copy them
549 private final byte[] pipebuf = new byte[PIPE_BUF*4];
551 private int writePos;
553 public final FD reader = new Reader();
554 public final FD writer = new Writer();
556 public class Reader extends FD {
557 protected FStat _fstat() { return new SocketFStat(); }
558 public int read(byte[] buf, int off, int len) throws ErrnoException {
559 if(len == 0) return 0;
560 synchronized(Pipe.this) {
561 while(writePos != -1 && readPos == writePos) {
562 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
564 if(writePos == -1) return 0; // eof
565 len = Math.min(len,writePos-readPos);
566 System.arraycopy(pipebuf,readPos,buf,off,len);
568 if(readPos == writePos) Pipe.this.notify();
572 public int flags() { return O_RDONLY; }
573 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
576 public class Writer extends FD {
577 protected FStat _fstat() { return new SocketFStat(); }
578 public int write(byte[] buf, int off, int len) throws ErrnoException {
579 if(len == 0) return 0;
580 synchronized(Pipe.this) {
581 if(readPos == -1) throw new ErrnoException(EPIPE);
582 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
583 // not enough space to atomicly write the data
584 while(readPos != -1 && readPos != writePos) {
585 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
587 if(readPos == -1) throw new ErrnoException(EPIPE);
588 readPos = writePos = 0;
590 len = Math.min(len,pipebuf.length - writePos);
591 System.arraycopy(buf,off,pipebuf,writePos,len);
592 if(readPos == writePos) Pipe.this.notify();
597 public int flags() { return O_WRONLY; }
598 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
602 private int sys_pipe(int addr) {
603 Pipe pipe = new Pipe();
605 int fd1 = addFD(pipe.reader);
606 if(fd1 < 0) return -ENFILE;
607 int fd2 = addFD(pipe.writer);
608 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
612 memWrite(addr+4,fd2);
613 } catch(FaultException e) {
621 private int sys_dup2(int oldd, int newd) {
622 if(oldd == newd) return 0;
623 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
624 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
625 if(fds[oldd] == null) return -EBADFD;
626 if(fds[newd] != null) fds[newd].close();
627 fds[newd] = fds[oldd].dup();
631 private int sys_dup(int oldd) {
632 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
633 if(fds[oldd] == null) return -EBADFD;
634 FD fd = fds[oldd].dup();
635 int newd = addFD(fd);
636 if(newd < 0) { fd.close(); return -ENFILE; }
640 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
641 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
642 if(s == null) return -ENOENT;
646 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
647 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
648 if(s == null) return -ENOENT;
652 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
653 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
657 private int sys_unlink(int cstring) throws FaultException, ErrnoException {
658 gs.unlink(this,normalizePath(cstring(cstring)));
662 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
663 byte[] b = getBytes(cwd);
664 if(size == 0) return -EINVAL;
665 if(size < b.length+2) return -ERANGE;
667 copyout(b,addr+1,b.length);
668 memset(addr+b.length+1,0,1);
672 private int sys_chdir(int addr) throws ErrnoException, FaultException {
673 String path = normalizePath(cstring(addr));
674 FStat st = gs.stat(this,path);
675 if(st == null) return -ENOENT;
676 if(st.type() != FStat.S_IFDIR) return -ENOTDIR;
681 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
682 count = Math.min(count,MAX_CHUNK);
683 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
684 if(fds[fdn] == null) return -EBADFD;
685 byte[] buf = byteBuf(count);
686 int n = fds[fdn].getdents(buf,0,count);
691 static class SocketFD extends FD {
692 public static final int TYPE_STREAM = 0;
693 public static final int TYPE_DGRAM = 1;
694 public static final int LISTEN = 2;
695 public int type() { return flags & 1; }
696 public boolean listen() { return (flags & 2) != 0; }
705 InetAddress bindAddr;
707 InetAddress connectAddr;
708 int connectPort = -1;
714 private static final byte[] EMPTY = new byte[0];
715 public SocketFD(int type) {
717 if(type == TYPE_DGRAM)
718 dp = new DatagramPacket(EMPTY,0);
721 public void setOptions() {
723 if(s != null && type() == TYPE_STREAM && !listen()) {
724 Platform.socketSetKeepAlive(s,(options & SO_KEEPALIVE) != 0);
726 } catch(SocketException e) {
727 if(STDERR_DIAG) e.printStackTrace();
731 public void _close() {
733 if(s != null) s.close();
734 if(ss != null) ss.close();
735 if(ds != null) ds.close();
736 } catch(IOException e) {
741 public int read(byte[] a, int off, int length) throws ErrnoException {
742 if(type() == TYPE_DGRAM) return recvfrom(a,off,length,null,null);
743 if(is == null) throw new ErrnoException(EPIPE);
745 int n = is.read(a,off,length);
746 return n < 0 ? 0 : n;
747 } catch(IOException e) {
748 throw new ErrnoException(EIO);
752 public int recvfrom(byte[] a, int off, int length, InetAddress[] sockAddr, int[] port) throws ErrnoException {
753 if(type() == TYPE_STREAM) return read(a,off,length);
755 if(off != 0) throw new IllegalArgumentException("off must be 0");
757 dp.setLength(length);
759 if(ds == null) ds = new DatagramSocket();
761 } catch(IOException e) {
762 if(STDERR_DIAG) e.printStackTrace();
763 throw new ErrnoException(EIO);
765 if(sockAddr != null) {
766 sockAddr[0] = dp.getAddress();
767 port[0] = dp.getPort();
769 return dp.getLength();
772 public int write(byte[] a, int off, int length) throws ErrnoException {
773 if(type() == TYPE_DGRAM) return sendto(a,off,length,null,-1);
775 if(os == null) throw new ErrnoException(EPIPE);
777 os.write(a,off,length);
779 } catch(IOException e) {
780 throw new ErrnoException(EIO);
784 public int sendto(byte[] a, int off, int length, InetAddress destAddr, int destPort) throws ErrnoException {
785 if(off != 0) throw new IllegalArgumentException("off must be 0");
786 if(type() == TYPE_STREAM) return write(a,off,length);
788 if(destAddr == null) {
789 destAddr = connectAddr;
790 destPort = connectPort;
792 if(destAddr == null) throw new ErrnoException(ENOTCONN);
795 dp.setAddress(destAddr);
796 dp.setPort(destPort);
798 dp.setLength(length);
801 if(ds == null) ds = new DatagramSocket();
803 } catch(IOException e) {
804 if(STDERR_DIAG) e.printStackTrace();
805 if("Network is unreachable".equals(e.getMessage())) throw new ErrnoException(EHOSTUNREACH);
806 throw new ErrnoException(EIO);
808 return dp.getLength();
811 public int flags() { return O_RDWR; }
812 public FStat _fstat() { return new SocketFStat(); }
815 private int sys_socket(int domain, int type, int proto) {
816 if(domain != AF_INET || (type != SOCK_STREAM && type != SOCK_DGRAM)) return -EPROTONOSUPPORT;
817 return addFD(new SocketFD(type == SOCK_STREAM ? SocketFD.TYPE_STREAM : SocketFD.TYPE_DGRAM));
820 private SocketFD getSocketFD(int fdn) throws ErrnoException {
821 if(fdn < 0 || fdn >= OPEN_MAX) throw new ErrnoException(EBADFD);
822 if(fds[fdn] == null) throw new ErrnoException(EBADFD);
823 if(!(fds[fdn] instanceof SocketFD)) throw new ErrnoException(ENOTSOCK);
825 return (SocketFD) fds[fdn];
828 private int sys_connect(int fdn, int addr, int namelen) throws ErrnoException, FaultException {
829 SocketFD fd = getSocketFD(fdn);
831 if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
832 int word1 = memRead(addr);
833 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
834 int port = word1 & 0xffff;
835 byte[] ip = new byte[4];
838 InetAddress inetAddr;
840 inetAddr = Platform.inetAddressFromBytes(ip);
841 } catch(UnknownHostException e) {
842 return -EADDRNOTAVAIL;
845 fd.connectAddr = inetAddr;
846 fd.connectPort = port;
850 case SocketFD.TYPE_STREAM: {
851 Socket s = new Socket(inetAddr,port);
854 fd.is = s.getInputStream();
855 fd.os = s.getOutputStream();
858 case SocketFD.TYPE_DGRAM:
861 throw new Error("should never happen");
863 } catch(IOException e) {
864 return -ECONNREFUSED;
870 private int sys_resolve_hostname(int chostname, int addr, int sizeAddr) throws FaultException {
871 String hostname = cstring(chostname);
872 int size = memRead(sizeAddr);
873 InetAddress[] inetAddrs;
875 inetAddrs = InetAddress.getAllByName(hostname);
876 } catch(UnknownHostException e) {
877 return HOST_NOT_FOUND;
879 int count = min(size/4,inetAddrs.length);
880 for(int i=0;i<count;i++,addr+=4) {
881 byte[] b = inetAddrs[i].getAddress();
884 memWrite(sizeAddr,count*4);
888 private int sys_setsockopt(int fdn, int level, int name, int valaddr, int len) throws ReadFaultException, ErrnoException {
889 SocketFD fd = getSocketFD(fdn);
895 if(len != 4) return -EINVAL;
896 int val = memRead(valaddr);
897 if(val != 0) fd.options |= name;
898 else fd.options &= ~name;
903 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
907 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
912 private int sys_getsockopt(int fdn, int level, int name, int valaddr, int lenaddr) throws ErrnoException, FaultException {
913 SocketFD fd = getSocketFD(fdn);
919 int len = memRead(lenaddr);
920 if(len < 4) return -EINVAL;
921 int val = (fd.options & name) != 0 ? 1 : 0;
922 memWrite(valaddr,val);
927 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
931 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
936 private int sys_bind(int fdn, int addr, int namelen) throws FaultException, ErrnoException {
937 SocketFD fd = getSocketFD(fdn);
939 if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
940 int word1 = memRead(addr);
941 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
942 int port = word1 & 0xffff;
943 InetAddress inetAddr = null;
944 if(memRead(addr+4) != 0) {
945 byte[] ip = new byte[4];
949 inetAddr = Platform.inetAddressFromBytes(ip);
950 } catch(UnknownHostException e) {
951 return -EADDRNOTAVAIL;
956 case SocketFD.TYPE_STREAM: {
957 fd.bindAddr = inetAddr;
961 case SocketFD.TYPE_DGRAM: {
962 if(fd.ds != null) fd.ds.close();
964 fd.ds = inetAddr != null ? new DatagramSocket(port,inetAddr) : new DatagramSocket(port);
965 } catch(IOException e) {
971 throw new Error("should never happen");
975 private int sys_listen(int fdn, int backlog) throws ErrnoException {
976 SocketFD fd = getSocketFD(fdn);
977 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
978 if(fd.ss != null || fd.s != null) return -EISCONN;
979 if(fd.bindPort < 0) return -EOPNOTSUPP;
982 fd.ss = new ServerSocket(fd.bindPort,backlog,fd.bindAddr);
983 fd.flags |= SocketFD.LISTEN;
985 } catch(IOException e) {
991 private int sys_accept(int fdn, int addr, int lenaddr) throws ErrnoException, FaultException {
992 SocketFD fd = getSocketFD(fdn);
993 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
994 if(!fd.listen()) return -EOPNOTSUPP;
996 int size = memRead(lenaddr);
998 ServerSocket s = fd.ss;
1001 client = s.accept();
1002 } catch(IOException e) {
1007 memWrite(addr,(6 << 24) | (AF_INET << 16) | client.getPort());
1008 byte[] b = client.getInetAddress().getAddress();
1009 copyout(b,addr+4,4);
1010 memWrite(lenaddr,8);
1013 SocketFD clientFD = new SocketFD(SocketFD.TYPE_STREAM);
1014 clientFD.s = client;
1016 clientFD.is = client.getInputStream();
1017 clientFD.os = client.getOutputStream();
1018 } catch(IOException e) {
1021 int n = addFD(clientFD);
1022 if(n == -1) { clientFD.close(); return -ENFILE; }
1026 private int sys_shutdown(int fdn, int how) throws ErrnoException {
1027 SocketFD fd = getSocketFD(fdn);
1028 if(fd.type() != SocketFD.TYPE_STREAM || fd.listen()) return -EOPNOTSUPP;
1029 if(fd.s == null) return -ENOTCONN;
1034 if(how == SHUT_RD || how == SHUT_RDWR) Platform.socketHalfClose(s,false);
1035 if(how == SHUT_WR || how == SHUT_RDWR) Platform.socketHalfClose(s,true);
1036 } catch(IOException e) {
1043 private int sys_sendto(int fdn, int addr, int count, int flags, int destAddr, int socklen) throws ErrnoException,ReadFaultException {
1044 SocketFD fd = getSocketFD(fdn);
1045 if(flags != 0) throw new ErrnoException(EINVAL);
1047 int word1 = memRead(destAddr);
1048 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
1049 int port = word1 & 0xffff;
1050 InetAddress inetAddr;
1051 byte[] ip = new byte[4];
1052 copyin(destAddr+4,ip,4);
1054 inetAddr = Platform.inetAddressFromBytes(ip);
1055 } catch(UnknownHostException e) {
1056 return -EADDRNOTAVAIL;
1059 count = Math.min(count,MAX_CHUNK);
1060 byte[] buf = byteBuf(count);
1061 copyin(addr,buf,count);
1063 return fd.sendto(buf,0,count,inetAddr,port);
1064 } catch(ErrnoException e) {
1065 if(e.errno == EPIPE) exit(128+13,true);
1070 private int sys_recvfrom(int fdn, int addr, int count, int flags, int sourceAddr, int socklenAddr) throws ErrnoException, FaultException {
1071 SocketFD fd = getSocketFD(fdn);
1072 if(flags != 0) throw new ErrnoException(EINVAL);
1074 InetAddress[] inetAddr = sourceAddr == 0 ? null : new InetAddress[1];
1075 int[] port = sourceAddr == 0 ? null : new int[1];
1077 count = Math.min(count,MAX_CHUNK);
1078 byte[] buf = byteBuf(count);
1079 int n = fd.recvfrom(buf,0,count,inetAddr,port);
1080 copyout(buf,addr,n);
1082 if(sourceAddr != 0) {
1083 memWrite(sourceAddr,(AF_INET << 16) | port[0]);
1084 byte[] ip = inetAddr[0].getAddress();
1085 copyout(ip,sourceAddr+4,4);
1091 private int sys_select(int n, int readFDs, int writeFDs, int exceptFDs, int timevalAddr) throws ReadFaultException, ErrnoException {
1095 private static String hostName() {
1097 return InetAddress.getLocalHost().getHostName();
1098 } catch(UnknownHostException e) {
1103 private int sys_sysctl(int nameaddr, int namelen, int oldp, int oldlenaddr, int newp, int newlen) throws FaultException {
1104 if(newp != 0) return -EPERM;
1105 if(namelen == 0) return -ENOENT;
1106 if(oldp == 0) return 0;
1109 switch(memRead(nameaddr)) {
1111 if(namelen != 2) break;
1112 switch(memRead(nameaddr+4)) {
1113 case KERN_OSTYPE: o = "NestedVM"; break;
1114 case KERN_HOSTNAME: o = hostName(); break;
1115 case KERN_OSRELEASE: o = VERSION; break;
1116 case KERN_VERSION: o = "NestedVM Kernel Version " + VERSION; break;
1120 if(namelen != 2) break;
1121 switch(memRead(nameaddr+4)) {
1122 case HW_MACHINE: o = "NestedVM Virtual Machine"; break;
1126 if(o == null) return -ENOENT;
1127 int len = memRead(oldlenaddr);
1128 if(o instanceof String) {
1129 byte[] b = getNullTerminatedBytes((String)o);
1130 if(len < b.length) return -ENOMEM;
1132 copyout(b,oldp,len);
1133 memWrite(oldlenaddr,len);
1134 } else if(o instanceof Integer) {
1135 if(len < 4) return -ENOMEM;
1136 memWrite(oldp,((Integer)o).intValue());
1138 throw new Error("should never happen");
1143 public static final class GlobalState {
1144 Hashtable execCache = new Hashtable();
1146 final UnixRuntime[] tasks;
1149 private MP[] mps = new MP[0];
1152 public GlobalState() { this(255); }
1153 public GlobalState(int maxProcs) { this(maxProcs,true); }
1154 public GlobalState(int maxProcs, boolean defaultMounts) {
1155 tasks = new UnixRuntime[maxProcs+1];
1157 addMount("/",new HostFS());
1158 addMount("/dev",new DevFS());
1162 static class MP implements Sort.Comparable {
1163 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
1166 public int compareTo(Object o) {
1167 if(!(o instanceof MP)) return 1;
1168 return -path.compareTo(((MP)o).path);
1172 public synchronized FS getMount(String path) {
1173 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1174 if(path.equals("/")) return root;
1175 path = path.substring(1);
1176 for(int i=0;i<mps.length;i++)
1177 if(mps[i].path.equals(path)) return mps[i].fs;
1181 public synchronized void addMount(String path, FS fs) {
1182 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
1183 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1185 if(fs.owner != null) fs.owner.removeMount(fs);
1188 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
1189 path = path.substring(1);
1190 int oldLength = mps.length;
1191 MP[] newMPS = new MP[oldLength + 1];
1192 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
1193 newMPS[oldLength] = new MP(path,fs);
1197 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
1198 fs.devno = highdevno + 2;
1201 public synchronized void removeMount(FS fs) {
1202 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
1203 throw new IllegalArgumentException("mount point doesn't exist");
1206 public synchronized void removeMount(String path) {
1207 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1208 if(path.equals("/")) {
1211 path = path.substring(1);
1213 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
1214 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
1219 private void removeMount(int index) {
1220 if(index == -1) { root.owner = null; root = null; return; }
1221 MP[] newMPS = new MP[mps.length - 1];
1222 System.arraycopy(mps,0,newMPS,0,index);
1223 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
1227 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
1228 int pl = normalizedPath.length();
1231 synchronized(this) { list = mps; }
1232 for(int i=0;i<list.length;i++) {
1234 int mpl = mp.path.length();
1235 if(normalizedPath.startsWith(mp.path) && (pl == mpl || normalizedPath.charAt(mpl) == '/'))
1236 return mp.fs.dispatch(op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
1239 return root.dispatch(op,r,normalizedPath,arg1,arg2);
1242 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(FS.OPEN,r,path,flags,mode); }
1243 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.STAT,r,path,0,0); }
1244 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.LSTAT,r,path,0,0); }
1245 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(FS.MKDIR,r,path,mode,0); }
1246 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(FS.UNLINK,r,path,0,0); }
1248 private static class CacheEnt {
1249 public final long time;
1250 public final long size;
1251 public final Object o;
1252 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
1256 public abstract static class FS {
1257 static final int OPEN = 1;
1258 static final int STAT = 2;
1259 static final int LSTAT = 3;
1260 static final int MKDIR = 4;
1261 static final int UNLINK = 5;
1266 Object dispatch(int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
1268 case OPEN: return open(r,path,arg1,arg2);
1269 case STAT: return stat(r,path);
1270 case LSTAT: return lstat(r,path);
1271 case MKDIR: mkdir(r,path,arg1); return null;
1272 case UNLINK: unlink(r,path); return null;
1273 default: throw new Error("should never happen");
1277 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1279 // If this returns null it'll be truned into an ENOENT
1280 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
1281 // If this returns null it'll be turned into an ENOENT
1282 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
1283 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
1284 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
1287 // chroot support should go in here if it is ever implemented chroot support in here
1288 private String normalizePath(String path) {
1289 boolean absolute = path.startsWith("/");
1290 int cwdl = cwd.length();
1292 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
1293 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
1294 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
1296 char[] in = new char[path.length()+1];
1297 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
1301 do { inp++; } while(in[inp] == '/');
1302 } else if(cwdl != 0) {
1303 cwd.getChars(0,cwdl,out,0);
1307 path.getChars(0,path.length(),in,0);
1308 while(in[inp] != 0) {
1310 while(in[inp] != 0 && in[inp] != '/') { out[outp++] = in[inp++]; }
1311 if(in[inp] == '\0') break;
1312 while(in[inp] == '/') inp++;
1316 if(in[inp] == '\0') break;
1317 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
1319 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
1320 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
1321 // Just read a /..{$,/}
1323 if(outp > 0) outp--;
1324 while(outp > 0 && out[outp] != '/') outp--;
1325 //System.err.println("After ..: " + new String(out,0,outp));
1328 // Just read a /.[^.] or /..[^/$]
1333 if(outp > 0 && out[outp-1] == '/') outp--;
1334 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
1335 return new String(out,0,outp);
1338 FStat hostFStat(final File f, Object data) {
1341 FileInputStream fis = new FileInputStream(f);
1342 switch(fis.read()) {
1343 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
1344 case '#': e = fis.read() == '!';
1347 } catch(IOException e2) { }
1348 HostFS fs = (HostFS) data;
1349 final int inode = fs.inodes.get(f.getAbsolutePath());
1350 final int devno = fs.devno;
1351 return new HostFStat(f,e) {
1352 public int inode() { return inode; }
1353 public int dev() { return devno; }
1357 FD hostFSDirFD(File f, Object _fs) {
1358 HostFS fs = (HostFS) _fs;
1359 return fs.new HostDirFD(f);
1362 public static class HostFS extends FS {
1363 InodeCache inodes = new InodeCache(4000);
1364 protected File root;
1365 public File getRoot() { return root; }
1367 static File hostRootDir() {
1368 if(Platform.getProperty("nestedvm.root") != null) {
1369 File f = new File(Platform.getProperty("nestedvm.root"));
1370 if(f.isDirectory()) return f;
1371 // fall through to case below
1373 String cwd = Platform.getProperty("user.dir");
1374 File f = new File(cwd != null ? cwd : ".");
1375 if(!f.exists()) throw new Error("Couldn't get File for cwd");
1376 f = new File(f.getAbsolutePath());
1377 while(f.getParent() != null) f = new File(f.getParent());
1378 // This works around a bug in some versions of ClassPath
1379 if(f.getPath().length() == 0) f = new File("/");
1383 private File hostFile(String path) {
1384 char sep = File.separatorChar;
1386 char buf[] = path.toCharArray();
1387 for(int i=0;i<buf.length;i++) {
1389 if(c == '/') buf[i] = sep;
1390 else if(c == sep) buf[i] = '/';
1392 path = new String(buf);
1394 return new File(root,path);
1397 public HostFS() { this(hostRootDir()); }
1398 public HostFS(String root) { this(new File(root)); }
1399 public HostFS(File root) { this.root = root; }
1402 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1403 final File f = hostFile(path);
1404 return r.hostFSOpen(f,flags,mode,this);
1407 public void unlink(UnixRuntime r, String path) throws ErrnoException {
1408 File f = hostFile(path);
1409 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1410 if(!f.exists()) throw new ErrnoException(ENOENT);
1411 if(!f.delete()) throw new ErrnoException(EPERM);
1414 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1415 File f = hostFile(path);
1416 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1417 if(!f.exists()) return null;
1418 return r.hostFStat(f,this);
1421 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1422 File f = hostFile(path);
1423 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1424 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1425 if(f.exists()) throw new ErrnoException(ENOTDIR);
1426 File parent = getParentFile(f);
1427 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1428 if(!f.mkdir()) throw new ErrnoException(EIO);
1431 private static File getParentFile(File f) {
1432 String p = f.getParent();
1433 return p == null ? null : new File(f,p);
1436 public class HostDirFD extends DirFD {
1437 private final File f;
1438 private final File[] children;
1439 public HostDirFD(File f) {
1441 String[] l = f.list();
1442 children = new File[l.length];
1443 for(int i=0;i<l.length;i++) children[i] = new File(f,l[i]);
1445 public int size() { return children.length; }
1446 public String name(int n) { return children[n].getName(); }
1447 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1448 public int parentInode() {
1449 File parent = getParentFile(f);
1450 // HACK: myInode() isn't really correct if we're not the root
1451 return parent == null ? myInode() : inodes.get(parent.getAbsolutePath());
1453 public int myInode() { return inodes.get(f.getAbsolutePath()); }
1454 public int myDev() { return devno; }
1458 private static void putInt(byte[] buf, int off, int n) {
1459 buf[off+0] = (byte)((n>>>24)&0xff);
1460 buf[off+1] = (byte)((n>>>16)&0xff);
1461 buf[off+2] = (byte)((n>>> 8)&0xff);
1462 buf[off+3] = (byte)((n>>> 0)&0xff);
1465 public static abstract class DirFD extends FD {
1466 private int pos = -2;
1468 protected abstract int size();
1469 protected abstract String name(int n);
1470 protected abstract int inode(int n);
1471 protected abstract int myDev();
1472 protected abstract int parentInode();
1473 protected abstract int myInode();
1474 public int flags() { return O_RDONLY; }
1476 public int getdents(byte[] buf, int off, int len) {
1480 OUTER: for(;len > 0 && pos < size();pos++){
1484 ino = pos == -1 ? parentInode() : myInode();
1485 if(ino == -1) continue;
1486 reclen = 9 + (pos == -1 ? 2 : 1);
1487 if(reclen > len) break OUTER;
1489 if(pos == -1) buf[off+9] = '.';
1492 String f = name(pos);
1493 byte[] fb = getBytes(f);
1494 reclen = fb.length + 9;
1495 if(reclen > len) break OUTER;
1497 System.arraycopy(fb,0,buf,off+8,fb.length);
1500 buf[off+reclen-1] = 0; // null terminate
1501 reclen = (reclen + 3) & ~3; // add padding
1502 putInt(buf,off,reclen);
1503 putInt(buf,off+4,ino);
1510 protected FStat _fstat() {
1511 return new FStat() {
1512 public int type() { return S_IFDIR; }
1513 public int inode() { return myInode(); }
1514 public int dev() { return myDev(); }
1519 public static class DevFS extends FS {
1520 private static final int ROOT_INODE = 1;
1521 private static final int NULL_INODE = 2;
1522 private static final int ZERO_INODE = 3;
1523 private static final int FD_INODE = 4;
1524 private static final int FD_INODES = 32;
1526 private abstract class DevFStat extends FStat {
1527 public int dev() { return devno; }
1528 public int mode() { return 0666; }
1529 public int type() { return S_IFCHR; }
1530 public int nlink() { return 1; }
1531 public abstract int inode();
1534 private abstract class DevDirFD extends DirFD {
1535 public int myDev() { return devno; }
1538 private FD devZeroFD = new FD() {
1539 public int read(byte[] a, int off, int length) {
1540 /*Arrays.fill(a,off,off+length,(byte)0);*/
1541 for(int i=off;i<off+length;i++) a[i] = 0;
1544 public int write(byte[] a, int off, int length) { return length; }
1545 public int seek(int n, int whence) { return 0; }
1546 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1547 public int flags() { return O_RDWR; }
1549 private FD devNullFD = new FD() {
1550 public int read(byte[] a, int off, int length) { return 0; }
1551 public int write(byte[] a, int off, int length) { return length; }
1552 public int seek(int n, int whence) { return 0; }
1553 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1554 public int flags() { return O_RDWR; }
1557 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1558 if(path.equals("null")) return devNullFD;
1559 if(path.equals("zero")) return devZeroFD;
1560 if(path.startsWith("fd/")) {
1563 n = Integer.parseInt(path.substring(4));
1564 } catch(NumberFormatException e) {
1567 if(n < 0 || n >= OPEN_MAX) return null;
1568 if(r.fds[n] == null) return null;
1569 return r.fds[n].dup();
1571 if(path.equals("fd")) {
1573 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1574 final int[] files = new int[count];
1576 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1577 return new DevDirFD() {
1578 public int myInode() { return FD_INODE; }
1579 public int parentInode() { return ROOT_INODE; }
1580 public int inode(int n) { return FD_INODES + n; }
1581 public String name(int n) { return Integer.toString(files[n]); }
1582 public int size() { return files.length; }
1585 if(path.equals("")) {
1586 return new DevDirFD() {
1587 public int myInode() { return ROOT_INODE; }
1588 // HACK: We don't have any clean way to get the parent inode
1589 public int parentInode() { return ROOT_INODE; }
1590 public int inode(int n) {
1592 case 0: return NULL_INODE;
1593 case 1: return ZERO_INODE;
1594 case 2: return FD_INODE;
1599 public String name(int n) {
1601 case 0: return "null";
1602 case 1: return "zero";
1603 case 2: return "fd";
1604 default: return null;
1607 public int size() { return 3; }
1613 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1614 if(path.equals("null")) return devNullFD.fstat();
1615 if(path.equals("zero")) return devZeroFD.fstat();
1616 if(path.startsWith("fd/")) {
1619 n = Integer.parseInt(path.substring(3));
1620 } catch(NumberFormatException e) {
1623 if(n < 0 || n >= OPEN_MAX) return null;
1624 if(r.fds[n] == null) return null;
1625 return r.fds[n].fstat();
1627 if(path.equals("fd")) return new FStat() { public int inode() { return FD_INODE; } public int dev() { return devno; } public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1628 if(path.equals("")) return new FStat() { public int inode() { return ROOT_INODE; } public int dev() { return devno; } public int type() { return S_IFDIR; } public int mode() { return 0444; }};
1632 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1633 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }