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 cwd = userdir == null ? null : gs.mapHostPath(userdir);
50 if(cwd == null) cwd = "/";
51 cwd = cwd.substring(1);
55 private static String posixTZ() {
56 StringBuffer sb = new StringBuffer();
57 TimeZone zone = TimeZone.getDefault();
58 int off = zone.getRawOffset() / 1000;
59 sb.append(Platform.timeZoneGetDisplayName(zone,false,false));
60 if(off > 0) sb.append("-");
62 sb.append(off/3600); off = off%3600;
63 if(off > 0) sb.append(":").append(off/60); off=off%60;
64 if(off > 0) sb.append(":").append(off);
65 if(zone.useDaylightTime())
66 sb.append(Platform.timeZoneGetDisplayName(zone,true,false));
70 private static boolean envHas(String key,String[] environ) {
71 for(int i=0;i<environ.length;i++)
72 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
76 String[] createEnv(String[] extra) {
77 String[] defaults = new String[7];
79 if(extra == null) extra = new String[0];
81 if(!envHas("USER",extra) && Platform.getProperty("user.name") != null)
82 defaults[n++] = "USER=" + Platform.getProperty("user.name");
83 if(!envHas("HOME",extra) && (tmp=Platform.getProperty("user.home")) != null && (tmp=gs.mapHostPath(tmp)) != null)
84 defaults[n++] = "HOME=" + tmp;
85 if(!envHas("TMPDIR",extra) && (tmp=Platform.getProperty("java.io.tmpdir")) != null && (tmp=gs.mapHostPath(tmp)) != null)
86 defaults[n++] = "TMPDIR=" + tmp;
87 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
88 if(!envHas("TERM",extra) && !win32Hacks) defaults[n++] = "TERM=vt100";
89 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
90 if(!envHas("PATH",extra)) defaults[n++] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin";
91 String[] env = new String[extra.length+n];
92 for(int i=0;i<n;i++) env[i] = defaults[i];
93 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
97 private static class ProcessTableFullExn extends RuntimeException { }
100 UnixRuntime[] tasks = gs.tasks;
103 UnixRuntime prev = tasks[pid];
104 if(prev == null || prev == this || prev.pid != pid || prev.parent != parent)
105 throw new Error("should never happen");
106 synchronized(parent.children) {
107 int i = parent.activeChildren.indexOf(prev);
108 if(i == -1) throw new Error("should never happen");
109 parent.activeChildren.setElementAt(this,i);
113 int nextPID = gs.nextPID;
114 for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; }
115 if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; }
116 if(newpid == -1) throw new ProcessTableFullExn();
118 gs.nextPID = newpid + 1;
124 int _syscall(int syscall, int a, int b, int c, int d, int e, int f) throws ErrnoException, FaultException {
126 case SYS_kill: return sys_kill(a,b);
127 case SYS_fork: return sys_fork();
128 case SYS_pipe: return sys_pipe(a);
129 case SYS_dup2: return sys_dup2(a,b);
130 case SYS_dup: return sys_dup(a);
131 case SYS_waitpid: return sys_waitpid(a,b,c);
132 case SYS_stat: return sys_stat(a,b);
133 case SYS_lstat: return sys_lstat(a,b);
134 case SYS_mkdir: return sys_mkdir(a,b);
135 case SYS_getcwd: return sys_getcwd(a,b);
136 case SYS_chdir: return sys_chdir(a);
137 case SYS_exec: return sys_exec(a,b,c);
138 case SYS_getdents: return sys_getdents(a,b,c,d);
139 case SYS_unlink: return sys_unlink(a);
140 case SYS_getppid: return sys_getppid();
141 case SYS_socket: return sys_socket(a,b,c);
142 case SYS_connect: return sys_connect(a,b,c);
143 case SYS_resolve_hostname: return sys_resolve_hostname(a,b,c);
144 case SYS_setsockopt: return sys_setsockopt(a,b,c,d,e);
145 case SYS_getsockopt: return sys_getsockopt(a,b,c,d,e);
146 case SYS_bind: return sys_bind(a,b,c);
147 case SYS_listen: return sys_listen(a,b);
148 case SYS_accept: return sys_accept(a,b,c);
149 case SYS_shutdown: return sys_shutdown(a,b);
150 case SYS_sysctl: return sys_sysctl(a,b,c,d,e,f);
151 case SYS_sendto: return sys_sendto(a,b,c,d,e,f);
152 case SYS_recvfrom: return sys_recvfrom(a,b,c,d,e,f);
153 case SYS_select: return sys_select(a,b,c,d,e);
154 case SYS_access: return sys_access(a,b);
155 case SYS_realpath: return sys_realpath(a,b);
156 case SYS_chown: return sys_chown(a,b,c);
157 case SYS_lchown: return sys_chown(a,b,c);
158 case SYS_fchown: return sys_fchown(a,b,c);
159 case SYS_chmod: return sys_chmod(a,b,c);
160 case SYS_fchmod: return sys_fchmod(a,b,c);
161 case SYS_umask: return sys_umask(a);
163 default: return super._syscall(syscall,a,b,c,d,e,f);
167 FD _open(String path, int flags, int mode) throws ErrnoException {
168 return gs.open(this,normalizePath(path),flags,mode);
171 private int sys_getppid() {
172 return parent == null ? 1 : parent.pid;
175 private int sys_chown(int fileAddr, int uid, int gid) {
178 private int sys_lchown(int fileAddr, int uid, int gid) {
181 private int sys_fchown(int fd, int uid, int gid) {
184 private int sys_chmod(int fileAddr, int uid, int gid) {
187 private int sys_fchmod(int fd, int uid, int gid) {
190 private int sys_umask(int mask) {
194 private int sys_access(int cstring, int mode) throws ErrnoException, ReadFaultException {
195 // FEATURE: sys_access
196 return gs.stat(this,cstring(cstring)) == null ? -ENOENT : 0;
199 private int sys_realpath(int inAddr, int outAddr) throws FaultException {
200 String s = normalizePath(cstring(inAddr));
201 byte[] b = getNullTerminatedBytes(s);
202 if(b.length > PATH_MAX) return -ERANGE;
203 copyout(b,outAddr,b.length);
207 // FEATURE: Signal handling
208 // check flag only on backwards jumps to basic blocks without compulsatory checks
209 // (see A Portable Research Framework for the Execution of Java Bytecode - Etienne Gagnon, Chapter 2)
211 /** The kill syscall.
212 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
213 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
214 Anything else terminates the process. */
215 private int sys_kill(int pid, int signal) {
216 // This will only be called by raise() in newlib to invoke the default handler
217 // We don't have to worry about actually delivering the signal
218 if(pid != pid) return -ESRCH;
219 if(signal < 0 || signal >= 32) return -EINVAL;
232 exit(128+signal, true);
237 private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException {
238 final int WNOHANG = 1;
239 if((options & ~(WNOHANG)) != 0) return -EINVAL;
240 if(pid == 0 || pid < -1) {
241 if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid);
244 boolean blocking = (options&WNOHANG)==0;
246 if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD;
247 if(children == null) return blocking ? -ECHILD : 0;
249 UnixRuntime done = null;
251 synchronized(children) {
254 if(exitedChildren.size() > 0) {
255 done = (UnixRuntime)exitedChildren.elementAt(exitedChildren.size() - 1);
256 exitedChildren.removeElementAt(exitedChildren.size() - 1);
259 if(pid >= gs.tasks.length) return -ECHILD;
260 UnixRuntime t = gs.tasks[pid];
261 if(t.parent != this) return -ECHILD;
262 if(t.state == EXITED) {
263 if(!exitedChildren.removeElement(t)) throw new Error("should never happen");
267 // process group stuff, EINVAL returned above
268 throw new Error("should never happen");
271 if(!blocking) return 0;
272 try { children.wait(); } catch(InterruptedException e) {}
273 //System.err.println("waitpid woke up: " + exitedChildren.size());
275 gs.tasks[done.pid] = null;
280 if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8);
286 if(children != null) synchronized(children) {
287 for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) {
288 UnixRuntime child = (UnixRuntime) e.nextElement();
289 gs.tasks[child.pid] = null;
291 exitedChildren.removeAllElements();
292 for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) {
293 UnixRuntime child = (UnixRuntime) e.nextElement();
296 activeChildren.removeAllElements();
299 UnixRuntime _parent = parent;
300 if(_parent == null) {
301 gs.tasks[pid] = null;
303 synchronized(_parent.children) {
305 gs.tasks[pid] = null;
307 if(!parent.activeChildren.removeElement(this)) throw new Error("should never happen _exited: pid: " + pid);
308 parent.exitedChildren.addElement(this);
309 parent.children.notify();
315 protected Object clone() throws CloneNotSupportedException {
316 UnixRuntime r = (UnixRuntime) super.clone();
320 r.activeChildren = r.exitedChildren = null;
324 private int sys_fork() {
328 r = (UnixRuntime) clone();
329 } catch(Exception e) {
338 } catch(ProcessTableFullExn e) {
342 //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]);
343 if(children == null) {
344 children = new Object();
345 activeChildren = new Vector();
346 exitedChildren = new Vector();
348 activeChildren.addElement(r);
350 CPUState state = new CPUState();
352 state.r[V0] = 0; // return 0 to child
353 state.pc += 4; // skip over syscall instruction
354 r.setCPUState(state);
357 new ForkedProcess(r);
362 public static final class ForkedProcess extends Thread {
363 private final UnixRuntime initial;
364 public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); }
365 public void run() { UnixRuntime.executeAndExec(initial); }
368 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
369 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
371 public static int executeAndExec(UnixRuntime r) {
374 if(r.execute()) break;
375 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()");
377 if(r.state != EXECED) return r.exitStatus();
382 private String[] readStringArray(int addr) throws ReadFaultException {
384 for(int p=addr;memRead(p) != 0;p+=4) count++;
385 String[] a = new String[count];
386 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
390 private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException {
391 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
394 private final static Method runtimeCompilerCompile;
398 m = Class.forName("org.ibex.nestedvm.RuntimeCompiler").getMethod("compile",new Class[]{Seekable.class,String.class,String.class});
399 } catch(NoSuchMethodException e) {
401 } catch(ClassNotFoundException e) {
404 runtimeCompilerCompile = m;
407 public Class runtimeCompile(Seekable s, String sourceName) throws IOException {
408 if(runtimeCompilerCompile == null) {
409 if(STDERR_DIAG) System.err.println("WARNING: Exec attempted but RuntimeCompiler not found!");
414 return (Class) runtimeCompilerCompile.invoke(null,new Object[]{s,"unixruntime,maxinsnpermethod=256,lessconstants",sourceName});
415 } catch(IllegalAccessException e) {
418 } catch(InvocationTargetException e) {
419 Throwable t = e.getTargetException();
420 if(t instanceof IOException) throw (IOException) t;
421 if(t instanceof RuntimeException) throw (RuntimeException) t;
422 if(t instanceof Error) throw (Error) t;
423 if(STDERR_DIAG) t.printStackTrace();
428 private int exec(String path, String[] argv, String[] envp) throws ErrnoException {
429 if(argv.length == 0) argv = new String[]{""};
430 // HACK: Hideous hack to make a standalone busybox possible
431 if(path.equals("bin/busybox") && getClass().getName().endsWith("BusyBox"))
432 return execClass(getClass(),argv,envp);
434 // NOTE: For this little hack to work nestedvm.root MUST be "."
436 System.err.println("Execing normalized path: " + normalizedPath);
437 if(true) return exec(new Interpreter(normalizedPath),argv,envp);
438 } catch(IOException e) { throw new Error(e); }*/
440 FStat fstat = gs.stat(this,path);
441 if(fstat == null) return -ENOENT;
442 GlobalState.CacheEnt ent = (GlobalState.CacheEnt) gs.execCache.get(path);
443 long mtime = fstat.mtime();
444 long size = fstat.size();
446 //System.err.println("Found cached entry for " + path);
447 if(ent.time ==mtime && ent.size == size) {
448 if(ent.o instanceof Class)
449 return execClass((Class) ent.o,argv,envp);
450 if(ent.o instanceof String[])
451 return execScript(path,(String[]) ent.o,argv,envp);
452 throw new Error("should never happen");
454 //System.err.println("Cache was out of date");
455 gs.execCache.remove(path);
458 FD fd = gs.open(this,path,RD_ONLY,0);
459 if(fd == null) throw new ErrnoException(ENOENT);
460 Seekable s = fd.seekable();
461 if(s == null) throw new ErrnoException(EACCES);
463 byte[] buf = new byte[4096];
466 int n = s.read(buf,0,buf.length);
467 if(n == -1) throw new ErrnoException(ENOEXEC);
470 case '\177': // possible ELF
471 if(n < 4) s.tryReadFully(buf,n,4-n);
472 if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') return -ENOEXEC;
474 if(STDERR_DIAG) System.err.println("Running RuntimeCompiler for " + path);
475 Class c = runtimeCompile(s,path);
476 if(STDERR_DIAG) System.err.println("RuntimeCompiler finished for " + path);
477 if(c == null) throw new ErrnoException(ENOEXEC);
478 gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,c));
479 return execClass(c,argv,envp);
482 int n2 = s.read(buf,1,buf.length-1);
483 if(n2 == -1) return -ENOEXEC;
486 if(buf[1] != '!') return -ENOEXEC;
490 for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; }
492 if(p == buf.length) break OUTER;
493 n = s.read(buf,p,buf.length-p);
496 for(;cmdStart<p;cmdStart++) if(buf[cmdStart]!=' ') break;
497 if(cmdStart == p) throw new ErrnoException(ENOEXEC);
498 int argStart = cmdStart;
499 for(;argStart<p;argStart++) if(buf[argStart] == ' ') break;
500 int cmdEnd = argStart;
501 while(argStart < p && buf[argStart] == ' ') argStart++;
502 String[] command = new String[] {
503 new String(buf,cmdStart,cmdEnd-cmdStart),
504 argStart < p ? new String(buf,argStart,p-argStart) : null
506 gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,command));
507 return execScript(path,command,argv,envp);
511 } catch(IOException e) {
518 public int execScript(String path, String[] command, String[] argv, String[] envp) throws ErrnoException {
519 String[] newArgv = new String[argv.length-1 + (command[1] != null ? 3 : 2)];
520 int p = command[0].lastIndexOf('/');
521 newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1);
522 newArgv[1] = "/" + path;
524 if(command[1] != null) newArgv[p++] = command[1];
525 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
526 if(p != newArgv.length) throw new Error("p != newArgv.length");
527 System.err.println("Execing: " + command[0]);
528 for(int i=0;i<newArgv.length;i++) System.err.println("execing [" + i + "] " + newArgv[i]);
529 return exec(command[0],newArgv,envp);
532 public int execClass(Class c,String[] argv, String[] envp) {
534 UnixRuntime r = (UnixRuntime) c.getDeclaredConstructor(new Class[]{Boolean.TYPE}).newInstance(new Object[]{Boolean.TRUE});
535 return exec(r,argv,envp);
536 } catch(Exception e) {
542 private int exec(UnixRuntime r, String[] argv, String[] envp) {
543 //System.err.println("Execing " + r);
544 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
546 r.closeOnExec = closeOnExec;
547 // make sure this doesn't get messed with these since we didn't copy them
565 private final byte[] pipebuf = new byte[PIPE_BUF*4];
567 private int writePos;
569 public final FD reader = new Reader();
570 public final FD writer = new Writer();
572 public class Reader extends FD {
573 protected FStat _fstat() { return new SocketFStat(); }
574 public int read(byte[] buf, int off, int len) throws ErrnoException {
575 if(len == 0) return 0;
576 synchronized(Pipe.this) {
577 while(writePos != -1 && readPos == writePos) {
578 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
580 if(writePos == -1) return 0; // eof
581 len = Math.min(len,writePos-readPos);
582 System.arraycopy(pipebuf,readPos,buf,off,len);
584 if(readPos == writePos) Pipe.this.notify();
588 public int flags() { return O_RDONLY; }
589 public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } }
592 public class Writer extends FD {
593 protected FStat _fstat() { return new SocketFStat(); }
594 public int write(byte[] buf, int off, int len) throws ErrnoException {
595 if(len == 0) return 0;
596 synchronized(Pipe.this) {
597 if(readPos == -1) throw new ErrnoException(EPIPE);
598 if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) {
599 // not enough space to atomicly write the data
600 while(readPos != -1 && readPos != writePos) {
601 try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ }
603 if(readPos == -1) throw new ErrnoException(EPIPE);
604 readPos = writePos = 0;
606 len = Math.min(len,pipebuf.length - writePos);
607 System.arraycopy(buf,off,pipebuf,writePos,len);
608 if(readPos == writePos) Pipe.this.notify();
613 public int flags() { return O_WRONLY; }
614 public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } }
618 private int sys_pipe(int addr) {
619 Pipe pipe = new Pipe();
621 int fd1 = addFD(pipe.reader);
622 if(fd1 < 0) return -ENFILE;
623 int fd2 = addFD(pipe.writer);
624 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
628 memWrite(addr+4,fd2);
629 } catch(FaultException e) {
637 private int sys_dup2(int oldd, int newd) {
638 if(oldd == newd) return 0;
639 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
640 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
641 if(fds[oldd] == null) return -EBADFD;
642 if(fds[newd] != null) fds[newd].close();
643 fds[newd] = fds[oldd].dup();
647 private int sys_dup(int oldd) {
648 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
649 if(fds[oldd] == null) return -EBADFD;
650 FD fd = fds[oldd].dup();
651 int newd = addFD(fd);
652 if(newd < 0) { fd.close(); return -ENFILE; }
656 private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException {
657 FStat s = gs.stat(this,normalizePath(cstring(cstring)));
658 if(s == null) return -ENOENT;
662 private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException {
663 FStat s = gs.lstat(this,normalizePath(cstring(cstring)));
664 if(s == null) return -ENOENT;
668 private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException {
669 gs.mkdir(this,normalizePath(cstring(cstring)),mode);
673 private int sys_unlink(int cstring) throws FaultException, ErrnoException {
674 gs.unlink(this,normalizePath(cstring(cstring)));
678 private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException {
679 byte[] b = getBytes(cwd);
680 if(size == 0) return -EINVAL;
681 if(size < b.length+2) return -ERANGE;
683 copyout(b,addr+1,b.length);
684 memset(addr+b.length+1,0,1);
688 private int sys_chdir(int addr) throws ErrnoException, FaultException {
689 String path = normalizePath(cstring(addr));
690 FStat st = gs.stat(this,path);
691 if(st == null) return -ENOENT;
692 if(st.type() != FStat.S_IFDIR) return -ENOTDIR;
697 private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException {
698 count = Math.min(count,MAX_CHUNK);
699 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
700 if(fds[fdn] == null) return -EBADFD;
701 byte[] buf = byteBuf(count);
702 int n = fds[fdn].getdents(buf,0,count);
707 static class SocketFD extends FD {
708 public static final int TYPE_STREAM = 0;
709 public static final int TYPE_DGRAM = 1;
710 public static final int LISTEN = 2;
711 public int type() { return flags & 1; }
712 public boolean listen() { return (flags & 2) != 0; }
721 InetAddress bindAddr;
723 InetAddress connectAddr;
724 int connectPort = -1;
730 private static final byte[] EMPTY = new byte[0];
731 public SocketFD(int type) {
733 if(type == TYPE_DGRAM)
734 dp = new DatagramPacket(EMPTY,0);
737 public void setOptions() {
739 if(s != null && type() == TYPE_STREAM && !listen()) {
740 Platform.socketSetKeepAlive(s,(options & SO_KEEPALIVE) != 0);
742 } catch(SocketException e) {
743 if(STDERR_DIAG) e.printStackTrace();
747 public void _close() {
749 if(s != null) s.close();
750 if(ss != null) ss.close();
751 if(ds != null) ds.close();
752 } catch(IOException e) {
757 public int read(byte[] a, int off, int length) throws ErrnoException {
758 if(type() == TYPE_DGRAM) return recvfrom(a,off,length,null,null);
759 if(is == null) throw new ErrnoException(EPIPE);
761 int n = is.read(a,off,length);
762 return n < 0 ? 0 : n;
763 } catch(IOException e) {
764 throw new ErrnoException(EIO);
768 public int recvfrom(byte[] a, int off, int length, InetAddress[] sockAddr, int[] port) throws ErrnoException {
769 if(type() == TYPE_STREAM) return read(a,off,length);
771 if(off != 0) throw new IllegalArgumentException("off must be 0");
773 dp.setLength(length);
775 if(ds == null) ds = new DatagramSocket();
777 } catch(IOException e) {
778 if(STDERR_DIAG) e.printStackTrace();
779 throw new ErrnoException(EIO);
781 if(sockAddr != null) {
782 sockAddr[0] = dp.getAddress();
783 port[0] = dp.getPort();
785 return dp.getLength();
788 public int write(byte[] a, int off, int length) throws ErrnoException {
789 if(type() == TYPE_DGRAM) return sendto(a,off,length,null,-1);
791 if(os == null) throw new ErrnoException(EPIPE);
793 os.write(a,off,length);
795 } catch(IOException e) {
796 throw new ErrnoException(EIO);
800 public int sendto(byte[] a, int off, int length, InetAddress destAddr, int destPort) throws ErrnoException {
801 if(off != 0) throw new IllegalArgumentException("off must be 0");
802 if(type() == TYPE_STREAM) return write(a,off,length);
804 if(destAddr == null) {
805 destAddr = connectAddr;
806 destPort = connectPort;
808 if(destAddr == null) throw new ErrnoException(ENOTCONN);
811 dp.setAddress(destAddr);
812 dp.setPort(destPort);
814 dp.setLength(length);
817 if(ds == null) ds = new DatagramSocket();
819 } catch(IOException e) {
820 if(STDERR_DIAG) e.printStackTrace();
821 if("Network is unreachable".equals(e.getMessage())) throw new ErrnoException(EHOSTUNREACH);
822 throw new ErrnoException(EIO);
824 return dp.getLength();
827 public int flags() { return O_RDWR; }
828 public FStat _fstat() { return new SocketFStat(); }
831 private int sys_socket(int domain, int type, int proto) {
832 if(domain != AF_INET || (type != SOCK_STREAM && type != SOCK_DGRAM)) return -EPROTONOSUPPORT;
833 return addFD(new SocketFD(type == SOCK_STREAM ? SocketFD.TYPE_STREAM : SocketFD.TYPE_DGRAM));
836 private SocketFD getSocketFD(int fdn) throws ErrnoException {
837 if(fdn < 0 || fdn >= OPEN_MAX) throw new ErrnoException(EBADFD);
838 if(fds[fdn] == null) throw new ErrnoException(EBADFD);
839 if(!(fds[fdn] instanceof SocketFD)) throw new ErrnoException(ENOTSOCK);
841 return (SocketFD) fds[fdn];
844 private int sys_connect(int fdn, int addr, int namelen) throws ErrnoException, FaultException {
845 SocketFD fd = getSocketFD(fdn);
847 if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
848 int word1 = memRead(addr);
849 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
850 int port = word1 & 0xffff;
851 byte[] ip = new byte[4];
854 InetAddress inetAddr;
856 inetAddr = Platform.inetAddressFromBytes(ip);
857 } catch(UnknownHostException e) {
858 return -EADDRNOTAVAIL;
861 fd.connectAddr = inetAddr;
862 fd.connectPort = port;
866 case SocketFD.TYPE_STREAM: {
867 Socket s = new Socket(inetAddr,port);
870 fd.is = s.getInputStream();
871 fd.os = s.getOutputStream();
874 case SocketFD.TYPE_DGRAM:
877 throw new Error("should never happen");
879 } catch(IOException e) {
880 return -ECONNREFUSED;
886 private int sys_resolve_hostname(int chostname, int addr, int sizeAddr) throws FaultException {
887 String hostname = cstring(chostname);
888 int size = memRead(sizeAddr);
889 InetAddress[] inetAddrs;
891 inetAddrs = InetAddress.getAllByName(hostname);
892 } catch(UnknownHostException e) {
893 return HOST_NOT_FOUND;
895 int count = min(size/4,inetAddrs.length);
896 for(int i=0;i<count;i++,addr+=4) {
897 byte[] b = inetAddrs[i].getAddress();
900 memWrite(sizeAddr,count*4);
904 private int sys_setsockopt(int fdn, int level, int name, int valaddr, int len) throws ReadFaultException, ErrnoException {
905 SocketFD fd = getSocketFD(fdn);
911 if(len != 4) return -EINVAL;
912 int val = memRead(valaddr);
913 if(val != 0) fd.options |= name;
914 else fd.options &= ~name;
919 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
923 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
928 private int sys_getsockopt(int fdn, int level, int name, int valaddr, int lenaddr) throws ErrnoException, FaultException {
929 SocketFD fd = getSocketFD(fdn);
935 int len = memRead(lenaddr);
936 if(len < 4) return -EINVAL;
937 int val = (fd.options & name) != 0 ? 1 : 0;
938 memWrite(valaddr,val);
943 if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name);
947 if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level);
952 private int sys_bind(int fdn, int addr, int namelen) throws FaultException, ErrnoException {
953 SocketFD fd = getSocketFD(fdn);
955 if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN;
956 int word1 = memRead(addr);
957 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
958 int port = word1 & 0xffff;
959 InetAddress inetAddr = null;
960 if(memRead(addr+4) != 0) {
961 byte[] ip = new byte[4];
965 inetAddr = Platform.inetAddressFromBytes(ip);
966 } catch(UnknownHostException e) {
967 return -EADDRNOTAVAIL;
972 case SocketFD.TYPE_STREAM: {
973 fd.bindAddr = inetAddr;
977 case SocketFD.TYPE_DGRAM: {
978 if(fd.ds != null) fd.ds.close();
980 fd.ds = inetAddr != null ? new DatagramSocket(port,inetAddr) : new DatagramSocket(port);
981 } catch(IOException e) {
987 throw new Error("should never happen");
991 private int sys_listen(int fdn, int backlog) throws ErrnoException {
992 SocketFD fd = getSocketFD(fdn);
993 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
994 if(fd.ss != null || fd.s != null) return -EISCONN;
995 if(fd.bindPort < 0) return -EOPNOTSUPP;
998 fd.ss = new ServerSocket(fd.bindPort,backlog,fd.bindAddr);
999 fd.flags |= SocketFD.LISTEN;
1001 } catch(IOException e) {
1007 private int sys_accept(int fdn, int addr, int lenaddr) throws ErrnoException, FaultException {
1008 SocketFD fd = getSocketFD(fdn);
1009 if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP;
1010 if(!fd.listen()) return -EOPNOTSUPP;
1012 int size = memRead(lenaddr);
1014 ServerSocket s = fd.ss;
1017 client = s.accept();
1018 } catch(IOException e) {
1023 memWrite(addr,(6 << 24) | (AF_INET << 16) | client.getPort());
1024 byte[] b = client.getInetAddress().getAddress();
1025 copyout(b,addr+4,4);
1026 memWrite(lenaddr,8);
1029 SocketFD clientFD = new SocketFD(SocketFD.TYPE_STREAM);
1030 clientFD.s = client;
1032 clientFD.is = client.getInputStream();
1033 clientFD.os = client.getOutputStream();
1034 } catch(IOException e) {
1037 int n = addFD(clientFD);
1038 if(n == -1) { clientFD.close(); return -ENFILE; }
1042 private int sys_shutdown(int fdn, int how) throws ErrnoException {
1043 SocketFD fd = getSocketFD(fdn);
1044 if(fd.type() != SocketFD.TYPE_STREAM || fd.listen()) return -EOPNOTSUPP;
1045 if(fd.s == null) return -ENOTCONN;
1050 if(how == SHUT_RD || how == SHUT_RDWR) Platform.socketHalfClose(s,false);
1051 if(how == SHUT_WR || how == SHUT_RDWR) Platform.socketHalfClose(s,true);
1052 } catch(IOException e) {
1059 private int sys_sendto(int fdn, int addr, int count, int flags, int destAddr, int socklen) throws ErrnoException,ReadFaultException {
1060 SocketFD fd = getSocketFD(fdn);
1061 if(flags != 0) throw new ErrnoException(EINVAL);
1063 int word1 = memRead(destAddr);
1064 if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT;
1065 int port = word1 & 0xffff;
1066 InetAddress inetAddr;
1067 byte[] ip = new byte[4];
1068 copyin(destAddr+4,ip,4);
1070 inetAddr = Platform.inetAddressFromBytes(ip);
1071 } catch(UnknownHostException e) {
1072 return -EADDRNOTAVAIL;
1075 count = Math.min(count,MAX_CHUNK);
1076 byte[] buf = byteBuf(count);
1077 copyin(addr,buf,count);
1079 return fd.sendto(buf,0,count,inetAddr,port);
1080 } catch(ErrnoException e) {
1081 if(e.errno == EPIPE) exit(128+13,true);
1086 private int sys_recvfrom(int fdn, int addr, int count, int flags, int sourceAddr, int socklenAddr) throws ErrnoException, FaultException {
1087 SocketFD fd = getSocketFD(fdn);
1088 if(flags != 0) throw new ErrnoException(EINVAL);
1090 InetAddress[] inetAddr = sourceAddr == 0 ? null : new InetAddress[1];
1091 int[] port = sourceAddr == 0 ? null : new int[1];
1093 count = Math.min(count,MAX_CHUNK);
1094 byte[] buf = byteBuf(count);
1095 int n = fd.recvfrom(buf,0,count,inetAddr,port);
1096 copyout(buf,addr,n);
1098 if(sourceAddr != 0) {
1099 memWrite(sourceAddr,(AF_INET << 16) | port[0]);
1100 byte[] ip = inetAddr[0].getAddress();
1101 copyout(ip,sourceAddr+4,4);
1107 private int sys_select(int n, int readFDs, int writeFDs, int exceptFDs, int timevalAddr) throws ReadFaultException, ErrnoException {
1111 private static String hostName() {
1113 return InetAddress.getLocalHost().getHostName();
1114 } catch(UnknownHostException e) {
1119 private int sys_sysctl(int nameaddr, int namelen, int oldp, int oldlenaddr, int newp, int newlen) throws FaultException {
1120 if(newp != 0) return -EPERM;
1121 if(namelen == 0) return -ENOENT;
1122 if(oldp == 0) return 0;
1125 switch(memRead(nameaddr)) {
1127 if(namelen != 2) break;
1128 switch(memRead(nameaddr+4)) {
1129 case KERN_OSTYPE: o = "NestedVM"; break;
1130 case KERN_HOSTNAME: o = hostName(); break;
1131 case KERN_OSRELEASE: o = VERSION; break;
1132 case KERN_VERSION: o = "NestedVM Kernel Version " + VERSION; break;
1136 if(namelen != 2) break;
1137 switch(memRead(nameaddr+4)) {
1138 case HW_MACHINE: o = "NestedVM Virtual Machine"; break;
1142 if(o == null) return -ENOENT;
1143 int len = memRead(oldlenaddr);
1144 if(o instanceof String) {
1145 byte[] b = getNullTerminatedBytes((String)o);
1146 if(len < b.length) return -ENOMEM;
1148 copyout(b,oldp,len);
1149 memWrite(oldlenaddr,len);
1150 } else if(o instanceof Integer) {
1151 if(len < 4) return -ENOMEM;
1152 memWrite(oldp,((Integer)o).intValue());
1154 throw new Error("should never happen");
1159 public static final class GlobalState {
1160 Hashtable execCache = new Hashtable();
1162 final UnixRuntime[] tasks;
1165 private MP[] mps = new MP[0];
1168 public GlobalState() { this(255); }
1169 public GlobalState(int maxProcs) { this(maxProcs,true); }
1170 public GlobalState(int maxProcs, boolean defaultMounts) {
1171 tasks = new UnixRuntime[maxProcs+1];
1174 if(Platform.getProperty("nestedvm.root") != null) {
1175 root = new File(Platform.getProperty("nestedvm.root"));
1176 if(!root.isDirectory()) throw new IllegalArgumentException("nestedvm.root is not a directory");
1178 String cwd = Platform.getProperty("user.dir");
1179 root = Platform.getRoot(new File(cwd != null ? cwd : "."));
1182 addMount("/",new HostFS(root));
1184 if(Platform.getProperty("nestedvm.root") == null) {
1185 File[] roots = Platform.listRoots();
1186 for(int i=0;i<roots.length;i++) {
1187 String name = roots[i].getPath();
1188 if(name.endsWith(File.separator))
1189 name = name.substring(0,name.length()-1);
1190 if(name.length() == 0 || name.indexOf('/') != -1) continue;
1191 addMount("/" + name.toLowerCase(),new HostFS(roots[i]));
1195 addMount("/dev",new DevFS());
1196 addMount("/resource",new ResourceFS());
1200 public String mapHostPath(String s) { return mapHostPath(new File(s)); }
1201 public String mapHostPath(File f) {
1204 synchronized(this) { mps = this.mps; root = this.root; }
1205 if(!f.isAbsolute()) f = new File(f.getAbsolutePath());
1206 for(int i=mps.length;i>=0;i--) {
1207 FS fs = i == mps.length ? root : mps[i].fs;
1208 String path = i == mps.length ? "" : mps[i].path;
1209 if(!(fs instanceof HostFS)) continue;
1210 File fsroot = ((HostFS)fs).getRoot();
1211 if(!fsroot.isAbsolute()) fsroot = new File(fsroot.getAbsolutePath());
1212 if(f.getPath().startsWith(fsroot.getPath())) {
1213 char sep = File.separatorChar;
1214 String child = f.getPath().substring(fsroot.getPath().length());
1216 char[] child_ = child.toCharArray();
1217 for(int j=0;j<child_.length;j++) {
1218 if(child_[j] == '/') child_[j] = sep;
1219 else if(child_[j] == sep) child_[j] = '/';
1221 child = new String(child_);
1223 String mapped = "/" + (path.length()==0?"":path+"/") + child;
1230 static class MP implements Sort.Comparable {
1231 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
1234 public int compareTo(Object o) {
1235 if(!(o instanceof MP)) return 1;
1236 return -path.compareTo(((MP)o).path);
1240 public synchronized FS getMount(String path) {
1241 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1242 if(path.equals("/")) return root;
1243 path = path.substring(1);
1244 for(int i=0;i<mps.length;i++)
1245 if(mps[i].path.equals(path)) return mps[i].fs;
1249 public synchronized void addMount(String path, FS fs) {
1250 if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists");
1251 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1253 if(fs.owner != null) fs.owner.removeMount(fs);
1256 if(path.equals("/")) { root = fs; fs.devno = 1; return; }
1257 path = path.substring(1);
1258 int oldLength = mps.length;
1259 MP[] newMPS = new MP[oldLength + 1];
1260 if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength);
1261 newMPS[oldLength] = new MP(path,fs);
1265 for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno);
1266 fs.devno = highdevno + 2;
1269 public synchronized void removeMount(FS fs) {
1270 for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; }
1271 throw new IllegalArgumentException("mount point doesn't exist");
1274 public synchronized void removeMount(String path) {
1275 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
1276 if(path.equals("/")) {
1279 path = path.substring(1);
1281 for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break;
1282 if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist");
1287 private void removeMount(int index) {
1288 if(index == -1) { root.owner = null; root = null; return; }
1289 MP[] newMPS = new MP[mps.length - 1];
1290 System.arraycopy(mps,0,newMPS,0,index);
1291 System.arraycopy(mps,0,newMPS,index,mps.length-index-1);
1295 private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException {
1296 int pl = normalizedPath.length();
1299 synchronized(this) { list = mps; }
1300 for(int i=0;i<list.length;i++) {
1302 int mpl = mp.path.length();
1303 if(normalizedPath.startsWith(mp.path) && (pl == mpl || normalizedPath.charAt(mpl) == '/'))
1304 return mp.fs.dispatch(op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2);
1307 return root.dispatch(op,r,normalizedPath,arg1,arg2);
1310 public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(FS.OPEN,r,path,flags,mode); }
1311 public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.STAT,r,path,0,0); }
1312 public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.LSTAT,r,path,0,0); }
1313 public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(FS.MKDIR,r,path,mode,0); }
1314 public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(FS.UNLINK,r,path,0,0); }
1316 private static class CacheEnt {
1317 public final long time;
1318 public final long size;
1319 public final Object o;
1320 public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; }
1324 public abstract static class FS {
1325 static final int OPEN = 1;
1326 static final int STAT = 2;
1327 static final int LSTAT = 3;
1328 static final int MKDIR = 4;
1329 static final int UNLINK = 5;
1334 Object dispatch(int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException {
1336 case OPEN: return open(r,path,arg1,arg2);
1337 case STAT: return stat(r,path);
1338 case LSTAT: return lstat(r,path);
1339 case MKDIR: mkdir(r,path,arg1); return null;
1340 case UNLINK: unlink(r,path); return null;
1341 default: throw new Error("should never happen");
1345 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1347 // If this returns null it'll be truned into an ENOENT
1348 public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException;
1349 // If this returns null it'll be turned into an ENOENT
1350 public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException;
1351 public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException;
1352 public abstract void unlink(UnixRuntime r, String path) throws ErrnoException;
1355 // chroot support should go in here if it is ever implemented
1356 private String normalizePath(String path) {
1357 boolean absolute = path.startsWith("/");
1358 int cwdl = cwd.length();
1360 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
1361 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
1362 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
1364 char[] in = new char[path.length()+1];
1365 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
1366 path.getChars(0,path.length(),in,0);
1370 do { inp++; } while(in[inp] == '/');
1371 } else if(cwdl != 0) {
1372 cwd.getChars(0,cwdl,out,0);
1376 while(in[inp] != 0) {
1378 while(in[inp] != 0 && in[inp] != '/') { out[outp++] = in[inp++]; }
1379 if(in[inp] == '\0') break;
1380 while(in[inp] == '/') inp++;
1384 if(in[inp] == '\0') break;
1385 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
1387 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
1388 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
1389 // Just read a /..{$,/}
1391 if(outp > 0) outp--;
1392 while(outp > 0 && out[outp] != '/') outp--;
1393 //System.err.println("After ..: " + new String(out,0,outp));
1396 // Just read a /.[^.] or /..[^/$]
1401 if(outp > 0 && out[outp-1] == '/') outp--;
1402 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
1403 int outStart = out[0] == '/' ? 1 : 0;
1404 return new String(out,outStart,outp - outStart);
1407 FStat hostFStat(final File f, Object data) {
1410 FileInputStream fis = new FileInputStream(f);
1411 switch(fis.read()) {
1412 case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break;
1413 case '#': e = fis.read() == '!';
1416 } catch(IOException e2) { }
1417 HostFS fs = (HostFS) data;
1418 final int inode = fs.inodes.get(f.getAbsolutePath());
1419 final int devno = fs.devno;
1420 return new HostFStat(f,e) {
1421 public int inode() { return inode; }
1422 public int dev() { return devno; }
1426 FD hostFSDirFD(File f, Object _fs) {
1427 HostFS fs = (HostFS) _fs;
1428 return fs.new HostDirFD(f);
1431 public static class HostFS extends FS {
1432 InodeCache inodes = new InodeCache(4000);
1433 protected File root;
1434 public File getRoot() { return root; }
1436 private File hostFile(String path) {
1437 char sep = File.separatorChar;
1439 char buf[] = path.toCharArray();
1440 for(int i=0;i<buf.length;i++) {
1442 if(c == '/') buf[i] = sep;
1443 else if(c == sep) buf[i] = '/';
1445 path = new String(buf);
1447 return new File(root,path);
1450 public HostFS(String root) { this(new File(root)); }
1451 public HostFS(File root) { this.root = root; }
1453 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1454 final File f = hostFile(path);
1455 return r.hostFSOpen(f,flags,mode,this);
1458 public void unlink(UnixRuntime r, String path) throws ErrnoException {
1459 File f = hostFile(path);
1460 if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM);
1461 if(!f.exists()) throw new ErrnoException(ENOENT);
1462 if(!f.delete()) throw new ErrnoException(EPERM);
1465 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1466 File f = hostFile(path);
1467 if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES);
1468 if(!f.exists()) return null;
1469 return r.hostFStat(f,this);
1472 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException {
1473 File f = hostFile(path);
1474 if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES);
1475 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
1476 if(f.exists()) throw new ErrnoException(ENOTDIR);
1477 File parent = getParentFile(f);
1478 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
1479 if(!f.mkdir()) throw new ErrnoException(EIO);
1482 private static File getParentFile(File f) {
1483 String p = f.getParent();
1484 return p == null ? null : new File(p);
1487 public class HostDirFD extends DirFD {
1488 private final File f;
1489 private final File[] children;
1490 public HostDirFD(File f) {
1492 String[] l = f.list();
1493 children = new File[l.length];
1494 for(int i=0;i<l.length;i++) children[i] = new File(f,l[i]);
1496 public int size() { return children.length; }
1497 public String name(int n) { return children[n].getName(); }
1498 public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); }
1499 public int parentInode() {
1500 File parent = getParentFile(f);
1501 // HACK: myInode() isn't really correct if we're not the root
1502 return parent == null ? myInode() : inodes.get(parent.getAbsolutePath());
1504 public int myInode() { return inodes.get(f.getAbsolutePath()); }
1505 public int myDev() { return devno; }
1509 private static void putInt(byte[] buf, int off, int n) {
1510 buf[off+0] = (byte)((n>>>24)&0xff);
1511 buf[off+1] = (byte)((n>>>16)&0xff);
1512 buf[off+2] = (byte)((n>>> 8)&0xff);
1513 buf[off+3] = (byte)((n>>> 0)&0xff);
1516 public static abstract class DirFD extends FD {
1517 private int pos = -2;
1519 protected abstract int size();
1520 protected abstract String name(int n);
1521 protected abstract int inode(int n);
1522 protected abstract int myDev();
1523 protected abstract int parentInode();
1524 protected abstract int myInode();
1525 public int flags() { return O_RDONLY; }
1527 public int getdents(byte[] buf, int off, int len) {
1531 OUTER: for(;len > 0 && pos < size();pos++){
1535 ino = pos == -1 ? parentInode() : myInode();
1536 if(ino == -1) continue;
1537 reclen = 9 + (pos == -1 ? 2 : 1);
1538 if(reclen > len) break OUTER;
1540 if(pos == -1) buf[off+9] = '.';
1543 String f = name(pos);
1544 byte[] fb = getBytes(f);
1545 reclen = fb.length + 9;
1546 if(reclen > len) break OUTER;
1548 System.arraycopy(fb,0,buf,off+8,fb.length);
1551 buf[off+reclen-1] = 0; // null terminate
1552 reclen = (reclen + 3) & ~3; // add padding
1553 putInt(buf,off,reclen);
1554 putInt(buf,off+4,ino);
1561 protected FStat _fstat() {
1562 return new FStat() {
1563 public int type() { return S_IFDIR; }
1564 public int inode() { return myInode(); }
1565 public int dev() { return myDev(); }
1570 public static class DevFS extends FS {
1571 private static final int ROOT_INODE = 1;
1572 private static final int NULL_INODE = 2;
1573 private static final int ZERO_INODE = 3;
1574 private static final int FD_INODE = 4;
1575 private static final int FD_INODES = 32;
1577 private abstract class DevFStat extends FStat {
1578 public int dev() { return devno; }
1579 public int mode() { return 0666; }
1580 public int type() { return S_IFCHR; }
1581 public int nlink() { return 1; }
1582 public abstract int inode();
1585 private abstract class DevDirFD extends DirFD {
1586 public int myDev() { return devno; }
1589 private FD devZeroFD = new FD() {
1590 public int read(byte[] a, int off, int length) {
1591 /*Arrays.fill(a,off,off+length,(byte)0);*/
1592 for(int i=off;i<off+length;i++) a[i] = 0;
1595 public int write(byte[] a, int off, int length) { return length; }
1596 public int seek(int n, int whence) { return 0; }
1597 public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; }
1598 public int flags() { return O_RDWR; }
1600 private FD devNullFD = new FD() {
1601 public int read(byte[] a, int off, int length) { return 0; }
1602 public int write(byte[] a, int off, int length) { return length; }
1603 public int seek(int n, int whence) { return 0; }
1604 public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; }
1605 public int flags() { return O_RDWR; }
1608 public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException {
1609 if(path.equals("null")) return devNullFD;
1610 if(path.equals("zero")) return devZeroFD;
1611 if(path.startsWith("fd/")) {
1614 n = Integer.parseInt(path.substring(4));
1615 } catch(NumberFormatException e) {
1618 if(n < 0 || n >= OPEN_MAX) return null;
1619 if(r.fds[n] == null) return null;
1620 return r.fds[n].dup();
1622 if(path.equals("fd")) {
1624 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; }
1625 final int[] files = new int[count];
1627 for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i;
1628 return new DevDirFD() {
1629 public int myInode() { return FD_INODE; }
1630 public int parentInode() { return ROOT_INODE; }
1631 public int inode(int n) { return FD_INODES + n; }
1632 public String name(int n) { return Integer.toString(files[n]); }
1633 public int size() { return files.length; }
1636 if(path.equals("")) {
1637 return new DevDirFD() {
1638 public int myInode() { return ROOT_INODE; }
1639 // HACK: We don't have any clean way to get the parent inode
1640 public int parentInode() { return ROOT_INODE; }
1641 public int inode(int n) {
1643 case 0: return NULL_INODE;
1644 case 1: return ZERO_INODE;
1645 case 2: return FD_INODE;
1650 public String name(int n) {
1652 case 0: return "null";
1653 case 1: return "zero";
1654 case 2: return "fd";
1655 default: return null;
1658 public int size() { return 3; }
1664 public FStat stat(UnixRuntime r,String path) throws ErrnoException {
1665 if(path.equals("null")) return devNullFD.fstat();
1666 if(path.equals("zero")) return devZeroFD.fstat();
1667 if(path.startsWith("fd/")) {
1670 n = Integer.parseInt(path.substring(3));
1671 } catch(NumberFormatException e) {
1674 if(n < 0 || n >= OPEN_MAX) return null;
1675 if(r.fds[n] == null) return null;
1676 return r.fds[n].fstat();
1678 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; }};
1679 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; }};
1683 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1684 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }
1688 public static class ResourceFS extends FS {
1689 final InodeCache inodes = new InodeCache(500);
1691 public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); }
1692 public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); }
1693 public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); }
1695 FStat connFStat(final URLConnection conn) {
1696 return new FStat() {
1697 public int type() { return S_IFREG; }
1698 public int nlink() { return 1; }
1699 public int mode() { return 0444; }
1700 public int size() { return conn.getContentLength(); }
1701 public int mtime() { return (int)(conn.getDate() / 1000); }
1702 public int inode() { return inodes.get(conn.getURL().toString()); }
1703 public int dev() { return devno; }
1707 public FStat stat(UnixRuntime r, String path) throws ErrnoException {
1708 URL url = r.getClass().getResource("/" + path);
1709 if(url == null) return null;
1711 return connFStat(url.openConnection());
1712 } catch(IOException e) {
1713 throw new ErrnoException(EIO);
1717 public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException {
1718 if((flags & ~3) != 0) {
1720 System.err.println("WARNING: Unsupported flags passed to ResourceFS.open(\"" + path + "\"): " + toHex(flags & ~3));
1721 throw new ErrnoException(ENOTSUP);
1723 if((flags&3) != RD_ONLY) throw new ErrnoException(EROFS);
1724 URL url = r.getClass().getResource("/" + path);
1725 if(url == null) return null;
1727 final URLConnection conn = url.openConnection();
1728 Seekable.InputStream si = new Seekable.InputStream(conn.getInputStream());
1729 return new SeekableFD(si,flags) { protected FStat _fstat() { return connFStat(conn); } };
1730 } catch(FileNotFoundException e) {
1731 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) throw new ErrnoException(EACCES);
1733 } catch(IOException e) { throw new ErrnoException(EIO); }