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 public abstract class UnixRuntime extends Runtime {
11 /** The pid of this "process" */
14 protected int getPid() { return pid; }
16 /** processes filesystem */
18 public FS getFS() { return fs; }
19 public void setFS(FS fs) {
20 if(state >= RUNNING) throw new IllegalStateException("Can't change fs while process is running");
24 /** proceses' current working directory - absolute path WITHOUT leading slash
25 "" = root, "bin" = /bin "usr/bin" = /usr/bin */
29 // FEATURE: Most of this is O(n) or worse - fix it
30 private final Object waitNotification = new Object();
31 private final static int MAX_TASKS = 256;
32 private final static UnixRuntime[] tasks = new UnixRuntime[MAX_TASKS];
33 private static int addTask(UnixRuntime rt) {
35 for(int i=1;i<MAX_TASKS;i++) {
36 if(tasks[i] == null) {
45 private static void removeTask(UnixRuntime rt) {
47 for(int i=1;i<MAX_TASKS;i++)
48 if(tasks[i] == rt) { tasks[i] = null; break; }
52 public UnixRuntime(int pageSize, int totalPages, boolean allowEmptyPages) {
53 super(pageSize,totalPages,allowEmptyPages);
55 FS root = new HostFS();
57 MountPointFS mounts = new MountPointFS(root);
58 mounts.add("/dev",dev);
61 // FEATURE: Do the proper mangling for non-unix hosts
62 String userdir = getSystemProperty("user.dir");
63 cwd = userdir != null && userdir.startsWith("/") && File.separatorChar == '/' ? userdir.substring(1) : "";
66 // NOTE: getDisplayName() is a Java2 function
67 private static String posixTZ() {
68 StringBuffer sb = new StringBuffer();
69 TimeZone zone = TimeZone.getDefault();
70 int off = zone.getRawOffset() / 1000;
71 sb.append(zone.getDisplayName(false,TimeZone.SHORT));
72 if(off > 0) sb.append("-");
74 sb.append(off/3600); off = off%3600;
75 if(off > 0) sb.append(":").append(off/60); off=off%60;
76 if(off > 0) sb.append(":").append(off);
77 if(zone.useDaylightTime())
78 sb.append(zone.getDisplayName(true,TimeZone.SHORT));
82 private static boolean envHas(String key,String[] environ) {
83 for(int i=0;i<environ.length;i++)
84 if(environ[i]!=null && environ[i].startsWith(key + "=")) return true;
88 protected String[] createEnv(String[] extra) {
89 String[] defaults = new String[5];
91 if(extra == null) extra = new String[0];
92 if(!envHas("USER",extra) && getSystemProperty("user.name") != null)
93 defaults[n++] = "USER=" + getSystemProperty("user.name");
94 if(!envHas("HOME",extra) && getSystemProperty("user.name") != null)
95 defaults[n++] = "HOME=" + getSystemProperty("user.home");
96 if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh";
97 if(!envHas("TERM",extra)) defaults[n++] = "TERM=vt100";
98 if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ();
99 String[] env = new String[extra.length+n];
100 for(int i=0;i<n;i++) env[i] = defaults[i];
101 for(int i=0;i<extra.length;i++) env[n++] = extra[i];
105 protected void _start() {
106 if(addTask(this) < 0) throw new Error("Task list full");
109 protected void _exit() {
110 synchronized(tasks) {
111 if(ppid == 0) removeTask(this);
112 for(int i=0;i<MAX_TASKS;i++) {
113 if(tasks[i] != null && tasks[i].ppid == pid) {
114 if(tasks[i].state == DONE) removeTask(tasks[i]);
115 else tasks[i].ppid = 0;
119 if(ppid != 0) synchronized(tasks[ppid].waitNotification) { tasks[ppid].waitNotification.notify(); }
123 protected int syscall(int syscall, int a, int b, int c, int d) {
125 case SYS_kill: return sys_kill(a,b);
126 case SYS_fork: return sys_fork();
127 case SYS_pipe: return sys_pipe(a);
128 case SYS_dup2: return sys_dup2(a,b);
129 case SYS_waitpid: return sys_waitpid(a,b,c);
130 case SYS_stat: return sys_stat(a,b);
131 case SYS_mkdir: return sys_mkdir(a,b);
132 case SYS_getcwd: return sys_getcwd(a,b);
133 case SYS_chdir: return sys_chdir(a);
134 case SYS_execve: return sys_execve(a,b.c);
136 default: return super.syscall(syscall,a,b,c,d);
140 protected FD open(String path, int flags, int mode) throws IOException {
141 return fs.open(normalizePath(path),flags,mode);
144 // FEATURE: Allow simple, broken signal delivery to other processes
145 // (check if a signal was delivered before and after syscalls)
146 // FEATURE: Implement raise() in terms of call("raise",...) - kinda cheap, but it keeps the complexity in newlib
147 /** The kill syscall.
148 SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process.
149 SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored.
150 Anything else terminates the process. */
151 private int sys_kill(int pid, int signal) {
152 // This will only be called by raise() in newlib to invoke the default handler
153 // We don't have to worry about actually delivering the signal
154 if(pid != pid) return -ESRCH;
155 if(signal < 0 || signal >= 32) return -EINVAL;
170 String msg = "Terminating on signal: " + signal + "\n";
174 System.out.print(msg);
177 byte[] b = getBytes(msg);
178 fds[2].write(b,0,b.length);
180 catch(IOException e) { /* ignore */ }
187 private int sys_waitpid(int pid, int statusAddr, int options) {
188 final int WNOHANG = 1;
189 if((options & ~(WNOHANG)) != 0) return -EINVAL;
190 if(pid !=-1 && (pid <= 0 || pid >= MAX_TASKS)) return -ECHILD;
192 synchronized(tasks) {
193 UnixRuntime task = null;
195 for(int i=0;i<MAX_TASKS;i++) {
196 if(tasks[i] != null && tasks[i].ppid == this.pid && tasks[i].state == DONE) {
201 } else if(tasks[pid] != null && tasks[pid].ppid == this.pid && tasks[pid].state == DONE) {
208 if(statusAddr!=0) memWrite(statusAddr,task.exitStatus()<<8);
209 } catch(FaultException e) {
216 if((options&WNOHANG)!=0) return 0;
217 synchronized(waitNotification) {
218 try { waitNotification.wait(); } catch(InterruptedException e) { /* ignore */ }
223 // FEATURE: Make this cleaner
224 // Great ugliness lies within.....
225 private int sys_fork() {
226 CPUState state = getCPUState();
227 int sp = state.r[SP];
230 r = (UnixRuntime) getClass().newInstance();
231 } catch(Exception e) {
232 System.err.println(e);
235 int child_pid = addTask(r);
236 if(child_pid < 0) return -ENOMEM;
240 r.fds = new FD[OPEN_MAX];
241 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) r.fds[i] = fds[i].dup();
244 for(int i=0;i<TOTAL_PAGES;i++) {
245 if(readPages[i] == null) continue;
246 if(isEmptyPage(writePages[i])) {
247 r.readPages[i] = r.writePages[i] = writePages[i];
248 } else if(writePages[i] != null) {
249 r.readPages[i] = r.writePages[i] = new int[PAGE_WORDS];
250 if(STACK_BOTTOM == 0 || i*PAGE_SIZE < STACK_BOTTOM || i*PAGE_SIZE >= sp-PAGE_SIZE*2)
251 System.arraycopy(writePages[i],0,r.writePages[i],0,PAGE_WORDS);
253 r.readPages[i] = r.readPages[i];
258 r.setCPUState(state);
265 } catch(Exception e) {
266 System.err.println("Forked process threw exception: ");
275 private int sys_execve(int cstring, int argv, int envp) {
278 String path = cstring(cstring);
279 FStat stat = fs.stat(path);
283 catch(FaultException e) { return -EFAULT; }
284 catch(FileNotFoundException e) { return -ENOENT; }
285 catch(IOException e) { return -EIO; }*/
286 throw new Error("FIXME - exec() isn't finished");
289 private int sys_pipe(int addr) {
290 PipedOutputStream writerStream = new PipedOutputStream();
291 PipedInputStream readerStream;
293 readerStream = new PipedInputStream(writerStream);
294 } catch(IOException e) {
297 FD reader = new InputStreamFD(readerStream);
298 FD writer = new OutputStreamFD(writerStream);
299 int fd1 = addFD(reader);
300 if(fd1 < 0) return -ENFILE;
301 int fd2 = addFD(writer);
302 if(fd2 < 0) { closeFD(fd1); return -ENFILE; }
305 memWrite(addr+4,fd2);
306 } catch(FaultException e) {
314 private int sys_dup2(int oldd, int newd) {
315 if(oldd == newd) return 0;
316 if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD;
317 if(newd < 0 || newd >= OPEN_MAX) return -EBADFD;
318 if(fds[oldd] == null) return -EBADFD;
319 if(fds[newd] != null) fds[newd].close();
320 fds[newd] = fds[oldd].dup();
324 private int sys_stat(int cstring, int addr) {
326 String path = normalizePath(cstring(cstring));
327 return stat(fs.stat(path),addr);
329 catch(ErrnoException e) { return -e.errno; }
330 catch(FileNotFoundException e) {
331 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) return -EACCES;
334 catch(IOException e) { return -EIO; }
335 catch(FaultException e) { return -EFAULT; }
339 private int sys_mkdir(int cstring, int mode) {
341 fs.mkdir(normalizePath(cstring(cstring)));
344 catch(ErrnoException e) { return -e.errno; }
345 catch(FileNotFoundException e) { return -ENOENT; }
346 catch(IOException e) { return -EIO; }
347 catch(FaultException e) { return -EFAULT; }
351 private int sys_getcwd(int addr, int size) {
352 byte[] b = getBytes(cwd);
353 if(size == 0) return -EINVAL;
354 if(size < b.length+2) return -ERANGE;
357 copyout(b,addr+1,b.length);
358 memset(addr+b.length+1,0,1);
360 } catch(FaultException e) {
365 private int sys_chdir(int addr) {
367 String path = normalizePath(cstring(addr));
368 System.err.println("Chdir: " + cstring(addr) + " -> " + path + " pwd: " + cwd);
369 if(fs.stat(path).type() != FStat.S_IFDIR) return -ENOTDIR;
371 System.err.println("Now: [" + cwd + "]");
374 catch(ErrnoException e) { return -e.errno; }
375 catch(FileNotFoundException e) { return -ENOENT; }
376 catch(IOException e) { return -EIO; }
377 catch(FaultException e) { return -EFAULT; }
380 public void chdir(String dir) throws FileNotFoundException {
381 if(state >= RUNNING) throw new IllegalStateException("Can't chdir while process is running");
383 dir = normalizePath(dir);
384 if(fs.stat(dir).type() != FStat.S_IFDIR) throw new FileNotFoundException();
385 } catch(IOException e) {
386 throw new FileNotFoundException();
391 public abstract static class FS {
392 protected FD _open(String path, int flags, int mode) throws IOException { return null; }
393 protected FStat _stat(String path) throws IOException { return null; }
394 protected void _mkdir(String path) throws IOException { throw new ErrnoException(EROFS); }
396 protected static final int OPEN = 1;
397 protected static final int STAT = 2;
398 protected static final int MKDIR = 3;
400 protected Object op(int op, String path, int arg1, int arg2) throws IOException {
402 case OPEN: return _open(path,arg1,arg2);
403 case STAT: return _stat(path);
404 case MKDIR: _mkdir(path); return null;
405 default: throw new IllegalArgumentException("Unknown FS OP");
409 public final FD open(String path, int flags, int mode) throws IOException { return (FD) op(OPEN,path,flags,mode); }
410 public final FStat stat(String path) throws IOException { return (FStat) op(STAT,path,0,0); }
411 public final void mkdir(String path) throws IOException { op(MKDIR,path,0,0); }
413 // FIXME: inode stuff
414 protected static FD directoryFD(String[] files, int hashCode) throws IOException {
415 ByteArrayOutputStream bos = new ByteArrayOutputStream();
416 DataOutputStream dos = new DataOutputStream(bos);
417 for(int i=0;i<files.length;i++) {
418 byte[] b = getBytes(files[i]);
419 int inode = (files[i].hashCode() ^ hashCode) & 0xfffff;
421 dos.writeInt(b.length);
422 dos.write(b,0,b.length);
424 final byte[] data = bos.toByteArray();
425 return new SeekableFD(new Seekable.ByteArray(data,false),RD_ONLY) {
426 protected FStat _fstat() { return new FStat() {
427 public int length() { return data.length; }
428 public int type() { return S_IFDIR; }
434 private String normalizePath(String path) {
435 boolean absolute = path.startsWith("/");
436 int cwdl = cwd.length();
437 // NOTE: This isn't just a fast path, it handles cases the code below doesn't
438 if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith("."))
439 return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path;
441 char[] in = new char[path.length()+1];
442 char[] out = new char[in.length + (absolute ? -1 : cwd.length())];
446 do { inp++; } while(in[inp] == '/');
447 } else if(cwdl != 0) {
448 cwd.getChars(0,cwdl,out,0);
452 path.getChars(0,path.length(),in,0);
453 while(in[inp] != 0) {
455 if(in[inp] != '/') { out[outp++] = in[inp++]; continue; }
456 while(in[inp] == '/') inp++;
458 if(in[inp] == '\0') continue;
459 if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; }
460 if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; }
461 if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // ..
464 while(outp > 0 && out[outp] != '/') outp--;
465 System.err.println("After ..: " + new String(out,0,outp));
471 if(outp > 0 && out[outp-1] == '/') outp--;
472 //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")");
473 return new String(out,0,outp);
476 // FIXME: This is probably still buggy
477 // FEATURE: Remove some of the "should never happen checks"
478 /*protected static String cleanupPath(String p) throws ErrnoException {
479 if(p.length() == 0) throw new ErrnoException(ENOENT);
480 if(needsCleanup(p)) {
481 char[] in = p.toCharArray();
485 out = new char[in.length];
488 out = new char[cwd.length() + in.length + 1];
490 for(int i=0;i<outp;i++) out[i] = cwd.charAt(i);
491 if(outp == 0 || out[0] != '/') throw new Error("should never happen");
493 int inLength = in.length;
495 while(inp<inLength) {
496 if(inp == 0 || in[inp] == '/') {
497 while(inp < inLength && in[inp] == '/') inp++;
498 if(inp == inLength) break;
500 if(inp+1 == inLength) break;
501 if(in[inp+1] == '.' && (inp+2 == inLength || in[inp+2] == '/')) {
503 if(outp == 0) continue;
504 do { outp--; } while(outp > 0 && out[outp] != '/');
505 } else if(in[inp+1] == '/') {
512 out[outp++] = in[inp++];
515 out[outp++] = in[inp++];
518 if(outp == 0) out[outp++] = '/';
519 return new String(out,0,outp);
521 if(p.startsWith("/")) return p;
522 StringBuffer sb = new StringBuffer(cwd);
523 if(!cwd.equals("/")) sb.append('/');
524 return sb.append(p).toString();
528 public static class MountPointFS extends FS {
529 private static class MP {
530 public MP(String path, FS fs) { this.path = path; this.fs = fs; }
533 public int compareTo(Object o) {
534 if(!(o instanceof MP)) return 1;
535 return -path.compareTo(((MP)o).path);
538 private final MP[][] mps = new MP[128][];
539 private final FS root;
540 public MountPointFS(FS root) { this.root = root; }
542 private static String fixup(String path) {
543 if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /");
544 path = path.substring(1);
545 if(path.length() == 0) throw new IllegalArgumentException("Zero length mount point path");
548 public FS get(String path) {
550 int f = path.charAt(0) & 0x7f;
551 for(int i=0;mps[f] != null && i < mps[f].length;i++)
552 if(mps[f][i].path.equals(path)) return mps[f][i].fs;
556 public void add(String path, FS fs) {
557 if(get(path) != null) throw new IllegalArgumentException("mount point already exists");
559 int f = path.charAt(0) & 0x7f;
560 int oldLength = mps[f] == null ? 0 : mps[f].length;
561 MP[] newList = new MP[oldLength + 1];
562 if(oldLength != 0) System.arraycopy(mps[f],0,newList,0,oldLength);
563 newList[oldLength] = new MP(path,fs);
564 Arrays.sort(newList);
568 public void remove(String path) {
570 if(get(path) == null) throw new IllegalArgumentException("mount point doesn't exist");
571 int f = path.charAt(0) & 0x7f;
572 MP[] oldList = mps[f];
573 MP[] newList = new MP[oldList.length - 1];
575 for(p=0;p<oldList.length;p++) if(oldList[p].path.equals(path)) break;
576 if(p == oldList.length) throw new Error("should never happen");
577 System.arraycopy(oldList,0,newList,0,p);
578 System.arraycopy(oldList,0,newList,p,oldList.length-p-1);
582 protected Object op(int op, String path, int arg1, int arg2) throws IOException {
583 int pl = path.length();
585 MP[] list = mps[path.charAt(0) & 0x7f];
586 if(list != null) for(int i=0;i<list.length;i++) {
588 int mpl = mp.path.length();
589 if(pl == mpl || (pl < mpl && path.charAt(mpl) == '/'))
590 return mp.fs.op(op,pl == mpl ? "" : path.substring(mpl+1),arg1,arg2);
593 return root.op(op,path,arg1,arg2);
597 // FEATURE: Probably should make this more general - support mountpoints, etc
598 /*public class UnixOverlayFS extends FS {
599 private final FS root;
600 private final FS dev = new DevFS();
601 public UnixOverlayFS(FS root) {
604 private String devPath(String path) {
605 if(path.startsWith("/dev")) {
606 if(path.length() == 4) return "/";
607 if(path.charAt(4) == '/') return path.substring(4);
611 public FD open(String path, int flags, int mode) throws IOException{
612 String dp = devPath(path);
613 return dp == null ? root.open(path,flags,mode) : dev.open(dp,flags,mode);
615 public FStat stat(String path) throws IOException {
616 String dp = devPath(path);
617 return dp == null ? root.stat(path) : dev.stat(dp);
619 public void mkdir(String path) throws IOException {
620 String dp = devPath(path);
621 if(dp == null) root.mkdir(path);
626 public static class HostFS extends FS {
628 public File getRoot() { return root; }
630 private static File hostRootDir() {
631 String cwd = getSystemProperty("user.dir");
632 File f = new File(cwd != null ? cwd : ".");
633 f = new File(f.getAbsolutePath());
634 while(f.getParent() != null) f = new File(f.getParent());
638 private File hostFile(String path) {
639 if(File.separatorChar != '/') path = path.replace('/',File.separatorChar);
640 return new File(root,path);
643 public HostFS() { this(hostRootDir()); }
644 public HostFS(String root) { this(new File(root)); }
645 public HostFS(File root) { this.root = root; }
648 // FEATURE: This shares a lot with Runtime.open
649 // NOTE: createNewFile is a Java2 function
650 public FD _open(String path, int flags, int mode) throws IOException {
651 final File f = hostFile(path);
652 if(f.isDirectory()) {
653 if((flags&3)!=RD_ONLY) throw new ErrnoException(EACCES);
654 return directoryFD(f.list(),path.hashCode());
656 if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT))
657 if(!f.createNewFile()) throw new ErrnoException(EEXIST);
658 if((flags&O_CREAT) == 0 && !f.exists())
660 final Seekable.File sf = new Seekable.File(f,(flags&3)!=RD_ONLY);
661 if((flags&O_TRUNC)!=0) sf.setLength(0);
662 return new SeekableFD(sf,mode) {
663 protected FStat _fstat() { return new HostFStat(f) {
665 try { return sf.length(); } catch(IOException e) { return 0; }
671 public FStat _stat(String path) throws FileNotFoundException {
672 File f = hostFile(path);
673 if(!f.exists()) throw new FileNotFoundException();
674 return new HostFStat(f);
677 public void _mkdir(String path) throws IOException {
678 File f = hostFile(path);
679 if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST);
680 if(f.exists()) throw new ErrnoException(ENOTDIR);
681 File parent = f.getParentFile();
682 if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR);
683 if(!f.mkdir()) throw new ErrnoException(EIO);
687 private static class DevFStat extends FStat {
688 public int dev() { return 1; }
689 public int mode() { return 0666; }
690 public int type() { return S_IFCHR; }
691 public int nlink() { return 1; }
693 private static FD devZeroFD = new FD() {
694 public boolean readable() { return true; }
695 public boolean writable() { return true; }
696 public int read(byte[] a, int off, int length) { Arrays.fill(a,off,off+length,(byte)0); return length; }
697 public int write(byte[] a, int off, int length) { return length; }
698 public int seek(int n, int whence) { return 0; }
699 public FStat _fstat() { return new DevFStat(); }
701 private static FD devNullFD = new FD() {
702 public boolean readable() { return true; }
703 public boolean writable() { return true; }
704 public int read(byte[] a, int off, int length) { return 0; }
705 public int write(byte[] a, int off, int length) { return length; }
706 public int seek(int n, int whence) { return 0; }
707 public FStat _fstat() { return new DevFStat(); }
710 public class DevFS extends FS {
711 public FD _open(String path, int mode, int flags) throws IOException {
712 if(path.equals("null")) return devNullFD;
713 if(path.equals("zero")) return devZeroFD;
714 if(path.startsWith("fd/")) {
717 n = Integer.parseInt(path.substring(4));
718 } catch(NumberFormatException e) {
719 throw new FileNotFoundException();
721 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
722 if(fds[n] == null) throw new FileNotFoundException();
725 if(path.equals("fd")) {
727 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) count++;
728 String[] files = new String[count];
730 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) files[count++] = Integer.toString(i);
731 return directoryFD(files,hashCode());
733 if(path.equals("")) {
734 String[] files = { "null", "zero", "fd" };
735 return directoryFD(files,hashCode());
737 throw new FileNotFoundException();
740 public FStat _stat(String path) throws IOException {
741 if(path.equals("null")) return devNullFD.fstat();
742 if(path.equals("zero")) return devZeroFD.fstat();
743 if(path.startsWith("fd/")) {
746 n = Integer.parseInt(path.substring(4));
747 } catch(NumberFormatException e) {
748 throw new FileNotFoundException();
750 if(n < 0 || n >= OPEN_MAX) throw new FileNotFoundException();
751 if(fds[n] == null) throw new FileNotFoundException();
752 return fds[n].fstat();
754 if(path.equals("fd")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
755 if(path.equals("")) return new FStat() { public int type() { return S_IFDIR; } public int mode() { return 0444; }};
756 throw new FileNotFoundException();
759 public void _mkdir(String path) throws IOException { throw new ErrnoException(EACCES); }