1 package org.ibex.nestedvm;
3 import org.ibex.nestedvm.util.*;
7 // FEATURE: BusyBox's ASH doesn't like \r\n at the end of lines
8 // is ash just broken or are many apps like this? if so workaround in nestedvm
10 // FEATURE: Throw ErrnoException and catch in syscall whereever possible
11 // (only in cases where we've already paid the price for a throw)
13 public abstract class UnixRuntime extends Runtime implements Cloneable {
14 /** The pid of this "process" */
17 protected int getPid() { return pid; }
19 /** processes filesystem */
21 public FS getFS() { return fs; }
22 public void setFS(FS fs) {
23 if(state != STOPPED) throw new IllegalStateException("Can't change fs while process is running");
27 /** proceses' current working directory - absolute path WITHOUT leading slash
28 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
31 /** The runtime that should be run next when in state == EXECED */
32 private UnixRuntime execedRuntime;
35 // FEATURE: Most of this is O(n) or worse - fix it
36 private final Object waitNotification = new Object();
37 private final static int MAX_TASKS = 256;
38 private final static UnixRuntime[] tasks = new UnixRuntime[MAX_TASKS];
39 private static int addTask(UnixRuntime rt) {
41 for(int i=1;i<MAX_TASKS;i++) {
42 if(tasks[i] == null) {
51 private static void removeTask(UnixRuntime rt) {
53 for(int i=1;i<MAX_TASKS;i++)
54 if(tasks[i] == rt) { tasks[i] = null; break; }
58 public UnixRuntime(int pageSize, int totalPages) {
59 super(pageSize,totalPages);
61 FS root = new HostFS();
63 MountPointFS mounts = new MountPointFS(root);
64 mounts.add("/dev",dev);
67 // FEATURE: Do the proper mangling for non-unix hosts
68 String userdir = getSystemProperty("user.dir");
69 cwd = userdir != null && userdir.startsWith("/") && File.separatorChar == '/' ? userdir.substring(1) : "";
72 // NOTE: getDisplayName() is a Java2 function
73 private static String posixTZ() {
74 StringBuffer sb = new StringBuffer();
75 TimeZone zone = TimeZone.getDefault();
76 int off = zone.getRawOffset() / 1000;
77 sb.append(zone.getDisplayName(false,TimeZone.SHORT));
78 if(off > 0) sb.append("-");
80 sb.append(off/3600); off = off%3600;
81 if(off > 0) sb.append(":").append(off/60); off=off%60;
82 if(off > 0) sb.append(":").append(off);
83 if(zone.useDaylightTime())
84 sb.append(zone.getDisplayName(true,TimeZone.SHORT));
88 private static boolean envHas(String key,String[] environ) {
89 for(int i=0;i<environ.length;i++)
90 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
94 protected String[] createEnv(String[] extra) {
95 String[] defaults = new String[5];
97 if(extra == null) extra = new String[0];
98 if(!envHas("USER",extra) && getSystemProperty("user.name") != null)
99 defaults[n++] = "USER=" + getSystemProperty("user.name");
100 if(!envHas("HOME",extra) && getSystemProperty("user.name") != null)
101 defaults[n++] = "HOME=" + getSystemProperty("user.home");
102 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
103 if(!envHas("TERM",extra)) defaults[n++] = "TERM=vt100";
104 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
105 String[] env = new String[extra.length+n];
106 for(int i=0;i<n;i++) env[i] = defaults[i];
107 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
111 protected void _start() {
112 if(addTask(this) < 0) throw new Error("Task list full");
115 protected void _exit() {
116 synchronized(tasks) {
117 if(ppid == 0) removeTask(this);
118 for(int i=0;i<MAX_TASKS;i++) {
119 if(tasks[i] != null && tasks[i].ppid == pid) {
120 if(tasks[i].state == EXITED) removeTask(tasks[i]);
121 else tasks[i].ppid = 0;
125 if(ppid != 0) synchronized(tasks[ppid].waitNotification) { tasks[ppid].waitNotification.notify(); }
129 protected int syscall(int syscall, int a, int b, int c, int d) {
131 case SYS_kill: return sys_kill(a,b);
132 case SYS_fork: return sys_fork();
133 case SYS_pipe: return sys_pipe(a);
134 case SYS_dup2: return sys_dup2(a,b);
135 case SYS_waitpid: return sys_waitpid(a,b,c);
136 case SYS_stat: return sys_stat(a,b);
137 case SYS_mkdir: return sys_mkdir(a,b);
138 case SYS_getcwd: return sys_getcwd(a,b);
139 case SYS_chdir: return sys_chdir(a);
140 case SYS_execve: return sys_execve(a,b,c);
142 default: return super.syscall(syscall,a,b,c,d);
146 protected FD open(String path, int flags, int mode) throws IOException {
147 return fs.open(normalizePath(path),flags,mode);
150 // FEATURE: Allow simple, broken signal delivery to other processes
151 // (check if a signal was delivered before and after syscalls)
152 // FEATURE: Implement raise() in terms of call("raise",...) - kinda cheap, but it keeps the complexity in newlib
153 /** The kill syscall.
154 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
155 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
156 Anything else terminates the process. */
157 private int sys_kill(int pid, int signal) {
158 // This will only be called by raise() in newlib to invoke the default handler
159 // We don't have to worry about actually delivering the signal
160 if(pid != pid) return -ESRCH;
161 if(signal < 0 || signal >= 32) return -EINVAL;
176 return syscall(SYS_exit,128+signal,0,0,0);
181 private int sys_waitpid(int pid, int statusAddr, int options) {
182 final int WNOHANG = 1;
183 if((options & ~(WNOHANG)) != 0) return -EINVAL;
184 if(pid !=-1 && (pid <= 0 || pid >= MAX_TASKS)) return -ECHILD;
186 synchronized(tasks) {
187 UnixRuntime task = null;
189 for(int i=0;i<MAX_TASKS;i++) {
190 if(tasks[i] != null && tasks[i].ppid == this.pid && tasks[i].state == EXITED) {
195 } else if(tasks[pid] != null && tasks[pid].ppid == this.pid && tasks[pid].state == EXITED) {
202 if(statusAddr!=0) memWrite(statusAddr,task.exitStatus()<<8);
203 } catch(FaultException e) {
210 if((options&WNOHANG)!=0) return 0;
211 synchronized(waitNotification) {
212 try { waitNotification.wait(); } catch(InterruptedException e) { /* ignore */ }
217 protected Object clone() throws CloneNotSupportedException {
218 UnixRuntime r = (UnixRuntime) super.clone();
223 private int sys_fork() {
224 CPUState state = new CPUState();
226 int sp = state.r[SP];
230 r = (UnixRuntime) clone();
231 } catch(Exception e) {
236 int childPID = addTask(r);
237 if(childPID < 0) return -ENOMEM;
241 state.r[V0] = 0; // return 0 to child
242 state.pc += 4; // skip over syscall instruction
243 r.setCPUState(state);
250 } catch(Exception e) {
251 System.err.println("Forked process threw exception: ");
260 public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); }
261 public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); }
263 public static int executeAndExec(UnixRuntime r) {
266 if(r.execute()) break;
267 System.err.println("WARNING: Pause requested while executing runAndExec()");
269 if(r.state != EXECED) return r.exitStatus();
274 private String[] readStringArray(int addr) throws ReadFaultException {
276 for(int p=addr;memRead(p) != 0;p+=4) count++;
277 String[] a = new String[count];
278 for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p));
282 // FEATURE: call the syscall just "exec"
283 private int sys_execve(int cpath, int cargv, int cenvp) {
285 return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp));
286 } catch(FaultException e) {
291 private int exec(String path, String[] argv, String[] envp) {
292 if(argv.length == 0) argv = new String[]{""};
297 fd = fs.open(path,RD_ONLY,0);
298 System.err.println(fd + " " + path);
299 if(fd == null) return -ENOENT;
301 if(s == null) return -ENOEXEC;
303 catch(ErrnoException e) { return -e.errno; }
304 catch(FileNotFoundException e) {
305 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
308 catch(IOException e) { return -EIO; }
312 byte[] buf = new byte[4096];
314 int n = s.read(buf,p,buf.length-p);
316 for(;n > 0; n--) if(buf[p++] == '\n' || p == 4096) break OUTER;
318 if(buf[0] == '!' && buf[1] == '#') {
319 String cmd = new String(buf,2,p-2);
321 if((p = cmd.indexOf(' ')) != -1) {
322 do { p++; } while(cmd.charAt(p)==' ');
323 argv1 = cmd.substring(p);
324 cmd = cmd.substring(0,p-1);
326 String[] newArgv = new String[argv.length + argv1 != null ? 2 : 1];
328 newArgv[p++] = argv[0];
329 if(argv1 != null) newArgv[p++] = argv1;
331 for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i];
333 return exec(cmd,newArgv,envp);
334 } else if(buf[0] == '\177' && buf[1] == 'E' && buf[2] == 'L' && buf[3] == 'F') {
336 UnixRuntime r = new Interpreter(s);
338 return exec(r,argv,envp);
342 } catch(IOException e) {
348 private int exec(UnixRuntime r, String[] argv, String[] envp) {
349 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
351 r.closeOnExec = closeOnExec;
352 // make sure this doesn't get messed with these since we didn't copy them
368 // FEATURE: Use custom PipeFD - be sure to support PIPE_BUF of data
369 private int sys_pipe(int addr) {
370 PipedOutputStream writerStream = new PipedOutputStream();
371 PipedInputStream readerStream;
373 readerStream = new PipedInputStream(writerStream);
374 } catch(IOException e) {
377 FD reader = new InputStreamFD(readerStream);
378 FD writer = new OutputStreamFD(writerStream);
379 int fd1 = addFD(reader);
380 if(fd1 < 0) return -ENFILE;
381 int fd2 = addFD(writer);
382 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
385 memWrite(addr+4,fd2);
386 } catch(FaultException e) {
394 private int sys_dup2(int oldd, int newd) {
395 if(oldd == newd) return 0;
396 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
397 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
398 if(fds[oldd] == null) return -EBADFD;
399 if(fds[newd] != null) fds[newd].close();
400 fds[newd] = fds[oldd].dup();
404 private int sys_stat(int cstring, int addr) {
406 String path = normalizePath(cstring(cstring));
407 return stat(fs.stat(path),addr);
409 catch(ErrnoException e) { return -e.errno; }
410 catch(FileNotFoundException e) {
411 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
414 catch(IOException e) { return -EIO; }
415 catch(FaultException e) { return -EFAULT; }
419 private int sys_mkdir(int cstring, int mode) {
421 fs.mkdir(normalizePath(cstring(cstring)));
424 catch(ErrnoException e) { return -e.errno; }
425 catch(FileNotFoundException e) { return -ENOENT; }
426 catch(IOException e) { return -EIO; }
427 catch(FaultException e) { return -EFAULT; }
431 private int sys_getcwd(int addr, int size) {
432 byte[] b = getBytes(cwd);
433 if(size == 0) return -EINVAL;
434 if(size < b.length+2) return -ERANGE;
437 copyout(b,addr+1,b.length);
438 memset(addr+b.length+1,0,1);
440 } catch(FaultException e) {
445 private int sys_chdir(int addr) {
447 String path = normalizePath(cstring(addr));
448 System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
449 if(fs.stat(path).type() != FStat.S_IFDIR) return -ENOTDIR;
451 System.err.println("Now: [" + cwd + "]");
454 catch(ErrnoException e) { return -e.errno; }
455 catch(FileNotFoundException e) { return -ENOENT; }
456 catch(IOException e) { return -EIO; }
457 catch(FaultException e) { return -EFAULT; }
460 public void chdir(String dir) throws FileNotFoundException {
461 if(state != STOPPED) throw new IllegalStateException("Can't chdir while process is running");
463 dir = normalizePath(dir);
464 if(fs.stat(dir).type() != FStat.S_IFDIR) throw new FileNotFoundException();
465 } catch(IOException e) {
466 throw new FileNotFoundException();
471 public abstract static class FS {
472 protected FD _open(String path, int flags, int mode) throws IOException { return null; }
473 protected FStat _stat(String path) throws IOException { return null; }
474 protected void _mkdir(String path) throws IOException { throw new ErrnoException(EROFS); }
476 protected static final int OPEN = 1;
477 protected static final int STAT = 2;
478 protected static final int MKDIR = 3;
480 protected Object op(int op, String path, int arg1, int arg2) throws IOException {
482 case OPEN: return _open(path,arg1,arg2);
483 case STAT: return _stat(path);
484 case MKDIR: _mkdir(path); return null;
485 default: throw new IllegalArgumentException("Unknown FS OP");
489 public final FD open(String path, int flags, int mode) throws IOException { return (FD) op(OPEN,path,flags,mode); }
490 public final FStat stat(String path) throws IOException { return (FStat) op(STAT,path,0,0); }
491 public final void mkdir(String path) throws IOException { op(MKDIR,path,0,0); }
494 // FEATURE: inode stuff
495 // FEATURE: Implement whatever is needed to get newlib's opendir and friends to work - that patch is a pain
496 protected static FD directoryFD(String[] files, int hashCode) throws IOException {
497 ByteArrayOutputStream bos = new ByteArrayOutputStream();
498 DataOutputStream dos = new DataOutputStream(bos);
499 for(int i=0;i<files.length;i++) {
500 byte[] b = getBytes(files[i]);
501 int inode = (files[i].hashCode() ^ hashCode) & 0xfffff;
503 dos.writeInt(b.length);
504 dos.write(b,0,b.length);
506 final byte[] data = bos.toByteArray();
507 return new SeekableFD(new Seekable.ByteArray(data,false),RD_ONLY) {
508 protected FStat _fstat() { return new FStat() {
509 public int length() { return data.length; }
510 public int type() { return S_IFDIR; }
516 private String normalizePath(String path) {
517 boolean absolute = path.startsWith("/");
518 int cwdl = cwd.length();
519 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
520 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
521 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
523 char[] in = new char[path.length()+1];
524 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
528 do { inp++; } while(in[inp] == '/');
529 } else if(cwdl != 0) {
530 cwd.getChars(0,cwdl,out,0);
534 path.getChars(0,path.length(),in,0);
535 while(in[inp] != 0) {
537 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
538 while(in[inp] == '/') inp++;
540 if(in[inp] == '\0') continue;
541 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
542 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
543 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
546 while(outp > 0 && out[outp] != '/') outp--;
547 System.err.println("After ..: " + new String(out,0,outp));
554 if(outp > 0 && out[outp-1] == '/') outp--;
555 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
556 return new String(out,0,outp);
559 public static class MountPointFS extends FS {
560 private static class MP {
561 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
564 public int compareTo(Object o) {
565 if(!(o instanceof MP)) return 1;
566 return -path.compareTo(((MP)o).path);
569 private final MP[][] mps = new MP[128][];
570 private final FS root;
571 public MountPointFS(FS root) { this.root = root; }
573 private static String fixup(String path) {
574 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
575 path = path.substring(1);
576 if(path.length() == 0) throw new IllegalArgumentException("Zero length mount point path");
579 public synchronized FS get(String path) {
581 int f = path.charAt(0) & 0x7f;
582 for(int i=0;mps[f] != null && i < mps[f].length;i++)
583 if(mps[f][i].path.equals(path)) return mps[f][i].fs;
587 public synchronized void add(String path, FS fs) {
588 if(get(path) != null) throw new IllegalArgumentException("mount point already exists");
590 int f = path.charAt(0) & 0x7f;
591 int oldLength = mps[f] == null ? 0 : mps[f].length;
592 MP[] newList = new MP[oldLength + 1];
593 if(oldLength != 0) System.arraycopy(mps[f],0,newList,0,oldLength);
594 newList[oldLength] = new MP(path,fs);
595 Arrays.sort(newList);
599 public synchronized void remove(String path) {
601 if(get(path) == null) throw new IllegalArgumentException("mount point doesn't exist");
602 int f = path.charAt(0) & 0x7f;
603 MP[] oldList = mps[f];
604 MP[] newList = new MP[oldList.length - 1];
606 for(p=0;p<oldList.length;p++) if(oldList[p].path.equals(path)) break;
607 if(p == oldList.length) throw new Error("should never happen");
608 System.arraycopy(oldList,0,newList,0,p);
609 System.arraycopy(oldList,0,newList,p,oldList.length-p-1);
613 protected Object op(int op, String path, int arg1, int arg2) throws IOException {
614 int pl = path.length();
616 MP[] list = mps[path.charAt(0) & 0x7f];
617 if(list != null) for(int i=0;i<list.length;i++) {
619 int mpl = mp.path.length();
620 if(pl == mpl || (pl < mpl && path.charAt(mpl) == '/'))
621 return mp.fs.op(op,pl == mpl ? "" : path.substring(mpl+1),arg1,arg2);
624 return root.op(op,path,arg1,arg2);
628 public static class HostFS extends FS {
630 public File getRoot() { return root; }
632 private static File hostRootDir() {
633 String cwd = getSystemProperty("user.dir");
634 File f = new File(cwd != null ? cwd : ".");
635 f = new File(f.getAbsolutePath());
636 while(f.getParent() != null) f = new File(f.getParent());
640 File hostFile(String path) {
641 char sep = File.separatorChar;
643 char buf[] = path.toCharArray();
644 for(int i=0;i<buf.length;i++) {
646 if(c == '/') buf[i] = sep;
647 else if(c == sep) buf[i] = '/';
649 path = new String(buf);
651 return new File(root,path);
654 public HostFS() { this(hostRootDir()); }
655 public HostFS(String root) { this(new File(root)); }
656 public HostFS(File root) { this.root = root; }
659 // FEATURE: This shares a lot with Runtime.open
660 // NOTE: createNewFile is a Java2 function
661 public FD _open(String path, int flags, int mode) throws IOException {
662 final File f = hostFile(path);
663 System.err.println(path + " -> " + f + " " + f.exists());
664 if(f.isDirectory()) {
665 if((flags&3)!=RD_ONLY) throw new ErrnoException(EACCES);
666 return directoryFD(f.list(),path.hashCode());
668 if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT))
669 if(!f.createNewFile()) throw new ErrnoException(EEXIST);
670 if((flags&O_CREAT) == 0 && !f.exists())
672 final Seekable.File sf = new Seekable.File(f,(flags&3)!=RD_ONLY);
673 if((flags&O_TRUNC)!=0) sf.setLength(0);
674 return new SeekableFD(sf,mode) {
675 protected FStat _fstat() { return new HostFStat(f) {
677 try { return sf.length(); } catch(IOException e) { return 0; }
683 public FStat _stat(String path) throws FileNotFoundException {
684 File f = hostFile(path);
685 if(!f.exists()) throw new FileNotFoundException();
686 return new HostFStat(f);
689 public void _mkdir(String path) throws IOException {
690 File f = hostFile(path);
691 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
692 if(f.exists()) throw new ErrnoException(ENOTDIR);
693 File parent = f.getParentFile();
694 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
695 if(!f.mkdir()) throw new ErrnoException(EIO);
699 private static class DevFStat extends FStat {
700 public int dev() { return 1; }
701 public int mode() { return 0666; }
702 public int type() { return S_IFCHR; }
703 public int nlink() { return 1; }
705 private static FD devZeroFD = new FD() {
706 public boolean readable() { return true; }
707 public boolean writable() { return true; }
708 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
709 public int write(byte[] a, int off, int length) { return length; }
710 public int seek(int n, int whence) { return 0; }
711 public FStat _fstat() { return new DevFStat(); }
713 private static FD devNullFD = new FD() {
714 public boolean readable() { return true; }
715 public boolean writable() { return true; }
716 public int read(byte[] a, int off, int length) { return 0; }
717 public int write(byte[] a, int off, int length) { return length; }
718 public int seek(int n, int whence) { return 0; }
719 public FStat _fstat() { return new DevFStat(); }
722 // FIXME: Support /dev/fd (need to have syscalls pass along Runtime instance)
723 public static class DevFS extends FS {
724 public FD _open(String path, int mode, int flags) throws IOException {
725 if(path.equals("null")) return devNullFD;
726 if(path.equals("zero")) return devZeroFD;
727 /*if(path.startsWith("fd/")) {
730 n = Integer.parseInt(path.substring(4));
731 } catch(NumberFormatException e) {
732 throw new FileNotFoundException();
734 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
735 if(fds[n] == null) throw new FileNotFoundException();
738 if(path.equals("fd")) {
740 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) count++;
741 String[] files = new String[count];
743 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) files[count++] = Integer.toString(i);
744 return directoryFD(files,hashCode());
746 if(path.equals("")) {
747 String[] files = { "null", "zero", "fd" };
748 return directoryFD(files,hashCode());
750 throw new FileNotFoundException();
753 public FStat _stat(String path) throws IOException {
754 if(path.equals("null")) return devNullFD.fstat();
755 if(path.equals("zero")) return devZeroFD.fstat();
756 /*if(path.startsWith("fd/")) {
759 n = Integer.parseInt(path.substring(4));
760 } catch(NumberFormatException e) {
761 throw new FileNotFoundException();
763 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
764 if(fds[n] == null) throw new FileNotFoundException();
765 return fds[n].fstat();
767 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
769 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
770 throw new FileNotFoundException();
773 public void _mkdir(String path) throws IOException { throw new ErrnoException(EACCES); }