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) {
294 throw new Error("FIXME exec() not finished");
295 //Class klass = fs.getClass(path);
296 //if(klass != null) return exec(klass,argv,envp);
299 Seekable s = fs.getSeekable(path);
301 boolean script = false;
303 case '\177': elf = s.read() == 'E' && s.read() == 'L' && s.read() == 'F'; break;
304 case '#': script = s.read() == '!';
309 throw new Error("FIXME can't exec scripts yet");
314 if(klass == null) return -ENOEXEC;
315 return exec(klass,argv,envp);
320 // FEATURE: Way too much overlap in the handling of ioexeptions everhwere
321 /*catch(ErrnoException e) { return -e.errno; }
322 catch(FileNotFoundException e) {
323 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
326 catch(IOException e) { return -EIO; }
327 catch(FaultException e) { return -EFAULT; }*/
330 private int exec(Class c, String[] argv, String[] envp) {
334 r = (UnixRuntime) c.newInstance();
335 } catch(Exception e) {
339 for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i);
341 r.closeOnExec = closeOnExec;
342 // make sure this doesn't get messed with these since we didn't copy them
358 // FEATURE: Use custom PipeFD - be sure to support PIPE_BUF of data
359 private int sys_pipe(int addr) {
360 PipedOutputStream writerStream = new PipedOutputStream();
361 PipedInputStream readerStream;
363 readerStream = new PipedInputStream(writerStream);
364 } catch(IOException e) {
367 FD reader = new InputStreamFD(readerStream);
368 FD writer = new OutputStreamFD(writerStream);
369 int fd1 = addFD(reader);
370 if(fd1 < 0) return -ENFILE;
371 int fd2 = addFD(writer);
372 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
375 memWrite(addr+4,fd2);
376 } catch(FaultException e) {
384 private int sys_dup2(int oldd, int newd) {
385 if(oldd == newd) return 0;
386 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
387 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
388 if(fds[oldd] == null) return -EBADFD;
389 if(fds[newd] != null) fds[newd].close();
390 fds[newd] = fds[oldd].dup();
394 private int sys_stat(int cstring, int addr) {
396 String path = normalizePath(cstring(cstring));
397 return stat(fs.stat(path),addr);
399 catch(ErrnoException e) { return -e.errno; }
400 catch(FileNotFoundException e) {
401 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
404 catch(IOException e) { return -EIO; }
405 catch(FaultException e) { return -EFAULT; }
409 private int sys_mkdir(int cstring, int mode) {
411 fs.mkdir(normalizePath(cstring(cstring)));
414 catch(ErrnoException e) { return -e.errno; }
415 catch(FileNotFoundException e) { return -ENOENT; }
416 catch(IOException e) { return -EIO; }
417 catch(FaultException e) { return -EFAULT; }
421 private int sys_getcwd(int addr, int size) {
422 byte[] b = getBytes(cwd);
423 if(size == 0) return -EINVAL;
424 if(size < b.length+2) return -ERANGE;
427 copyout(b,addr+1,b.length);
428 memset(addr+b.length+1,0,1);
430 } catch(FaultException e) {
435 private int sys_chdir(int addr) {
437 String path = normalizePath(cstring(addr));
438 System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
439 if(fs.stat(path).type() != FStat.S_IFDIR) return -ENOTDIR;
441 System.err.println("Now: [" + cwd + "]");
444 catch(ErrnoException e) { return -e.errno; }
445 catch(FileNotFoundException e) { return -ENOENT; }
446 catch(IOException e) { return -EIO; }
447 catch(FaultException e) { return -EFAULT; }
450 public void chdir(String dir) throws FileNotFoundException {
451 if(state != STOPPED) throw new IllegalStateException("Can't chdir while process is running");
453 dir = normalizePath(dir);
454 if(fs.stat(dir).type() != FStat.S_IFDIR) throw new FileNotFoundException();
455 } catch(IOException e) {
456 throw new FileNotFoundException();
461 public abstract static class FS {
462 protected FD _open(String path, int flags, int mode) throws IOException { return null; }
463 protected FStat _stat(String path) throws IOException { return null; }
464 protected void _mkdir(String path) throws IOException { throw new ErrnoException(EROFS); }
466 protected static final int OPEN = 1;
467 protected static final int STAT = 2;
468 protected static final int MKDIR = 3;
470 protected Object op(int op, String path, int arg1, int arg2) throws IOException {
472 case OPEN: return _open(path,arg1,arg2);
473 case STAT: return _stat(path);
474 case MKDIR: _mkdir(path); return null;
475 default: throw new IllegalArgumentException("Unknown FS OP");
479 public final FD open(String path, int flags, int mode) throws IOException { return (FD) op(OPEN,path,flags,mode); }
480 public final FStat stat(String path) throws IOException { return (FStat) op(STAT,path,0,0); }
481 public final void mkdir(String path) throws IOException { op(MKDIR,path,0,0); }
484 // FEATURE: inode stuff
485 // FEATURE: Implement whatever is needed to get newlib's opendir and friends to work - that patch is a pain
486 protected static FD directoryFD(String[] files, int hashCode) throws IOException {
487 ByteArrayOutputStream bos = new ByteArrayOutputStream();
488 DataOutputStream dos = new DataOutputStream(bos);
489 for(int i=0;i<files.length;i++) {
490 byte[] b = getBytes(files[i]);
491 int inode = (files[i].hashCode() ^ hashCode) & 0xfffff;
493 dos.writeInt(b.length);
494 dos.write(b,0,b.length);
496 final byte[] data = bos.toByteArray();
497 return new SeekableFD(new Seekable.ByteArray(data,false),RD_ONLY) {
498 protected FStat _fstat() { return new FStat() {
499 public int length() { return data.length; }
500 public int type() { return S_IFDIR; }
506 private String normalizePath(String path) {
507 boolean absolute = path.startsWith("/");
508 int cwdl = cwd.length();
509 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
510 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
511 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
513 char[] in = new char[path.length()+1];
514 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
518 do { inp++; } while(in[inp] == '/');
519 } else if(cwdl != 0) {
520 cwd.getChars(0,cwdl,out,0);
524 path.getChars(0,path.length(),in,0);
525 while(in[inp] != 0) {
527 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
528 while(in[inp] == '/') inp++;
530 if(in[inp] == '\0') continue;
531 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
532 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
533 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
536 while(outp > 0 && out[outp] != '/') outp--;
537 System.err.println("After ..: " + new String(out,0,outp));
544 if(outp > 0 && out[outp-1] == '/') outp--;
545 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
546 return new String(out,0,outp);
549 public static class MountPointFS extends FS {
550 private static class MP {
551 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
554 public int compareTo(Object o) {
555 if(!(o instanceof MP)) return 1;
556 return -path.compareTo(((MP)o).path);
559 private final MP[][] mps = new MP[128][];
560 private final FS root;
561 public MountPointFS(FS root) { this.root = root; }
563 private static String fixup(String path) {
564 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
565 path = path.substring(1);
566 if(path.length() == 0) throw new IllegalArgumentException("Zero length mount point path");
569 public synchronized FS get(String path) {
571 int f = path.charAt(0) & 0x7f;
572 for(int i=0;mps[f] != null && i < mps[f].length;i++)
573 if(mps[f][i].path.equals(path)) return mps[f][i].fs;
577 public synchronized void add(String path, FS fs) {
578 if(get(path) != null) throw new IllegalArgumentException("mount point already exists");
580 int f = path.charAt(0) & 0x7f;
581 int oldLength = mps[f] == null ? 0 : mps[f].length;
582 MP[] newList = new MP[oldLength + 1];
583 if(oldLength != 0) System.arraycopy(mps[f],0,newList,0,oldLength);
584 newList[oldLength] = new MP(path,fs);
585 Arrays.sort(newList);
589 public synchronized void remove(String path) {
591 if(get(path) == null) throw new IllegalArgumentException("mount point doesn't exist");
592 int f = path.charAt(0) & 0x7f;
593 MP[] oldList = mps[f];
594 MP[] newList = new MP[oldList.length - 1];
596 for(p=0;p<oldList.length;p++) if(oldList[p].path.equals(path)) break;
597 if(p == oldList.length) throw new Error("should never happen");
598 System.arraycopy(oldList,0,newList,0,p);
599 System.arraycopy(oldList,0,newList,p,oldList.length-p-1);
603 protected Object op(int op, String path, int arg1, int arg2) throws IOException {
604 int pl = path.length();
606 MP[] list = mps[path.charAt(0) & 0x7f];
607 if(list != null) for(int i=0;i<list.length;i++) {
609 int mpl = mp.path.length();
610 if(pl == mpl || (pl < mpl && path.charAt(mpl) == '/'))
611 return mp.fs.op(op,pl == mpl ? "" : path.substring(mpl+1),arg1,arg2);
614 return root.op(op,path,arg1,arg2);
618 public static class HostFS extends FS {
620 public File getRoot() { return root; }
622 private static File hostRootDir() {
623 String cwd = getSystemProperty("user.dir");
624 File f = new File(cwd != null ? cwd : ".");
625 f = new File(f.getAbsolutePath());
626 while(f.getParent() != null) f = new File(f.getParent());
630 File hostFile(String path) {
631 char sep = File.separatorChar;
633 char buf[] = path.toCharArray();
634 for(int i=0;i<buf.length;i++) {
636 if(c == '/') buf[i] = sep;
637 else if(c == sep) buf[i] = '/';
639 path = new String(buf);
641 return new File(root,path);
644 public HostFS() { this(hostRootDir()); }
645 public HostFS(String root) { this(new File(root)); }
646 public HostFS(File root) { this.root = root; }
649 // FEATURE: This shares a lot with Runtime.open
650 // NOTE: createNewFile is a Java2 function
651 public FD _open(String path, int flags, int mode) throws IOException {
652 final File f = hostFile(path);
653 if(f.isDirectory()) {
654 if((flags&3)!=RD_ONLY) throw new ErrnoException(EACCES);
655 return directoryFD(f.list(),path.hashCode());
657 if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT))
658 if(!f.createNewFile()) throw new ErrnoException(EEXIST);
659 if((flags&O_CREAT) == 0 && !f.exists())
661 final Seekable.File sf = new Seekable.File(f,(flags&3)!=RD_ONLY);
662 if((flags&O_TRUNC)!=0) sf.setLength(0);
663 return new SeekableFD(sf,mode) {
664 protected FStat _fstat() { return new HostFStat(f) {
666 try { return sf.length(); } catch(IOException e) { return 0; }
672 public FStat _stat(String path) throws FileNotFoundException {
673 File f = hostFile(path);
674 if(!f.exists()) throw new FileNotFoundException();
675 return new HostFStat(f);
678 public void _mkdir(String path) throws IOException {
679 File f = hostFile(path);
680 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
681 if(f.exists()) throw new ErrnoException(ENOTDIR);
682 File parent = f.getParentFile();
683 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
684 if(!f.mkdir()) throw new ErrnoException(EIO);
688 private static class DevFStat extends FStat {
689 public int dev() { return 1; }
690 public int mode() { return 0666; }
691 public int type() { return S_IFCHR; }
692 public int nlink() { return 1; }
694 private static FD devZeroFD = new FD() {
695 public boolean readable() { return true; }
696 public boolean writable() { return true; }
697 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
698 public int write(byte[] a, int off, int length) { return length; }
699 public int seek(int n, int whence) { return 0; }
700 public FStat _fstat() { return new DevFStat(); }
702 private static FD devNullFD = new FD() {
703 public boolean readable() { return true; }
704 public boolean writable() { return true; }
705 public int read(byte[] a, int off, int length) { return 0; }
706 public int write(byte[] a, int off, int length) { return length; }
707 public int seek(int n, int whence) { return 0; }
708 public FStat _fstat() { return new DevFStat(); }
711 // FIXME: Support /dev/fd (need to have syscalls pass along Runtime instance)
712 public static class DevFS extends FS {
713 public FD _open(String path, int mode, int flags) throws IOException {
714 if(path.equals("null")) return devNullFD;
715 if(path.equals("zero")) return devZeroFD;
716 /*if(path.startsWith("fd/")) {
719 n = Integer.parseInt(path.substring(4));
720 } catch(NumberFormatException e) {
721 throw new FileNotFoundException();
723 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
724 if(fds[n] == null) throw new FileNotFoundException();
727 if(path.equals("fd")) {
729 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) count++;
730 String[] files = new String[count];
732 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) files[count++] = Integer.toString(i);
733 return directoryFD(files,hashCode());
735 if(path.equals("")) {
736 String[] files = { "null", "zero", "fd" };
737 return directoryFD(files,hashCode());
739 throw new FileNotFoundException();
742 public FStat _stat(String path) throws IOException {
743 if(path.equals("null")) return devNullFD.fstat();
744 if(path.equals("zero")) return devZeroFD.fstat();
745 /*if(path.startsWith("fd/")) {
748 n = Integer.parseInt(path.substring(4));
749 } catch(NumberFormatException e) {
750 throw new FileNotFoundException();
752 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
753 if(fds[n] == null) throw new FileNotFoundException();
754 return fds[n].fstat();
756 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
758 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
759 throw new FileNotFoundException();
762 public void _mkdir(String path) throws IOException { throw new ErrnoException(EACCES); }