1 // Copyright 2003 Brian Alliet
2 // Based on org.xwt.imp.MIPS by Adam Megacz
3 // Portions Copyright 2003 Adam Megacz
5 package org.ibex.nestedvm;
7 import org.ibex.nestedvm.util.*;
9 import java.util.Arrays;
11 public abstract class Runtime implements UsermodeConstants,Registers,Cloneable {
12 /** Number of bits to shift to get the page number (1<<<pageShift == pageSize) */
13 protected final int pageShift;
14 /** Bottom of region of memory allocated to the stack */
15 private final int stackBottom;
17 /** Readable main memory pages */
18 protected int[][] readPages;
19 /** Writable main memory pages.
20 If the page is writable writePages[x] == readPages[x]; if not writePages[x] == null. */
21 protected int[][] writePages;
23 /** The address of the end of the heap */
26 /** Number of guard pages to keep between the stack and the heap */
27 private static final int STACK_GUARD_PAGES = 4;
29 /** The last address the executable uses (other than the heap/stack) */
30 protected abstract int heapStart();
32 /** The program's entry point */
33 protected abstract int entryPoint();
35 /** The location of the _user_info block (or 0 is there is none) */
36 protected int userInfoBase() { return 0; }
37 protected int userInfoSize() { return 0; }
39 /** The location of the global pointer */
40 protected abstract int gp();
42 /** When the process started */
43 private long startTime;
45 /** Text/Data loaded in memory */
46 public final static int STOPPED = 0;
47 /** Program is executing instructions */
48 public final static int RUNNING = 1;
49 /** Prgram has been started but is paused */
50 public final static int PAUSED = 2;
51 /** Program is executing a callJava() method */
52 public final static int CALLJAVA = 3;
53 /** Program has exited (it cannot currently be restarted) */
54 public final static int EXITED = 4;
55 /** Program has executed a successful exec(), a new Runtime needs to be run (used by UnixRuntime) */
56 public final static int EXECED = 5;
58 /** The current state */
59 protected int state = STOPPED;
60 /** @see Runtime#state state */
61 public final int getState() { return state; }
63 /** The exit status if the process (only valid if state==DONE)
65 private int exitStatus;
66 public ExecutionException exitException;
68 /** Table containing all open file descriptors. (Entries are null if the fd is not in use */
69 FD[] fds = new FD[OPEN_MAX]; // package-private for UnixRuntime
70 boolean closeOnExec[] = new boolean[OPEN_MAX];
72 /** Pointer to a SecurityManager for this process */
74 public void setSecurityManager(SecurityManager sm) { this.sm = sm; }
76 /** Pointer to a callback for the call_java syscall */
77 private CallJavaCB callJavaCB;
78 public void setCallJavaCB(CallJavaCB callJavaCB) { this.callJavaCB = callJavaCB; }
80 /** Temporary buffer for read/write operations */
81 private byte[] _byteBuf;
82 /** Max size of temporary buffer
83 @see Runtime#_byteBuf */
84 private final static int MAX_CHUNK = 16*1024*1024 - 1024;
86 /** Subclasses should actually execute program in this method. They should continue
87 executing until state != RUNNING. Only syscall() can modify state. It is safe
88 to only check the state attribute after a call to syscall() */
89 protected abstract void _execute() throws ExecutionException;
91 /** Subclasses should return the address of the symbol <i>symbol</i> or -1 it it doesn't exits in this method
92 This method is only required if the call() function is used */
93 protected int lookupSymbol(String symbol) { return -1; }
95 /** Subclasses should populate a CPUState object representing the cpu state */
96 protected abstract void getCPUState(CPUState state);
98 /** Subclasses should set the CPUState to the state held in <i>state</i> */
99 protected abstract void setCPUState(CPUState state);
101 protected Object clone() throws CloneNotSupportedException {
102 Runtime r = (Runtime) super.clone();
105 r.fds = new FD[OPEN_MAX];
106 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) r.fds[i] = fds[i].dup();
107 int totalPages = writePages.length;
108 r.readPages = new int[totalPages][];
109 r.writePages = new int[totalPages][];
110 for(int i=0;i<totalPages;i++) {
111 if(readPages[i] == null) continue;
112 if(writePages[i] == null) r.readPages[i] = readPages[i];
113 else r.readPages[i] = r.writePages[i] = (int[])writePages[i].clone();
118 protected Runtime(int pageSize, int totalPages) {
119 if(pageSize <= 0) throw new IllegalArgumentException("pageSize <= 0");
120 if(totalPages <= 0) throw new IllegalArgumentException("totalPages <= 0");
121 if((pageSize&(pageSize-1)) != 0) throw new IllegalArgumentException("pageSize not a power of two");
124 while(pageSize>>>_pageShift != 1) _pageShift++;
125 pageShift = _pageShift;
127 int heapStart = heapStart();
128 int totalMemory = totalPages * pageSize;
129 int stackSize = max(totalMemory/512,ARG_MAX+65536);
132 stackSize = max(stackSize,pageSize);
133 stackSize = (stackSize + pageSize - 1) & ~(pageSize-1);
134 stackPages = stackSize >>> pageShift;
135 heapStart = (heapStart + pageSize) & ~(pageSize-1);
136 if(stackPages + STACK_GUARD_PAGES + (heapStart >>> pageShift) >= totalPages)
137 throw new IllegalArgumentException("total pages too small");
139 if(pageSize < heapStart + stackSize) throw new IllegalArgumentException("total memory too small");
140 heapStart = (heapStart + 4095) & ~4096;
143 stackBottom = totalMemory - stackSize;
146 readPages = new int[totalPages][];
147 writePages = new int[totalPages][];
149 if(totalPages == 1) {
150 readPages[0] = writePages[0] = new int[pageSize>>2];
152 for(int i=(stackBottom >>> pageShift);i<writePages.length;i++) {
153 readPages[i] = writePages[i] = new int[pageSize>>2];
157 addFD(new StdinFD(System.in));
158 addFD(new StdoutFD(System.out));
159 addFD(new StdoutFD(System.err));
162 /** Copy everything from <i>src</i> to <i>addr</i> initializing uninitialized pages if required.
163 Newly initalized pages will be marked read-only if <i>ro</i> is set */
164 protected final void initPages(int[] src, int addr, boolean ro) {
165 int pageWords = (1<<pageShift)>>>2;
166 int pageMask = (1<<pageShift) - 1;
168 for(int i=0;i<src.length;) {
169 int page = addr >>> pageShift;
170 int start = (addr&pageMask)>>2;
171 int elements = min(pageWords-start,src.length-i);
172 if(readPages[page]==null) {
175 if(writePages[page] == null) writePages[page] = readPages[page];
177 System.arraycopy(src,i,readPages[page],start,elements);
183 /** Initialize <i>words</i> of pages starting at <i>addr</i> to 0 */
184 protected final void clearPages(int addr, int words) {
185 int pageWords = (1<<pageShift)>>>2;
186 int pageMask = (1<<pageShift) - 1;
188 for(int i=0;i<words;) {
189 int page = addr >>> pageShift;
190 int start = (addr&pageMask)>>2;
191 int elements = min(pageWords-start,words-i);
192 if(readPages[page]==null) {
193 readPages[page] = writePages[page] = new int[pageWords];
195 if(writePages[page] == null) writePages[page] = readPages[page];
196 for(int j=start;j<start+elements;j++) writePages[page][j] = 0;
203 /** Copies <i>length</i> bytes from the processes memory space starting at
204 <i>addr</i> INTO a java byte array <i>a</i> */
205 public final void copyin(int addr, byte[] buf, int count) throws ReadFaultException {
206 int pageWords = (1<<pageShift)>>>2;
207 int pageMask = pageWords - 1;
210 if(count == 0) return;
212 int word = memRead(addr&~3);
214 case 1: buf[x++] = (byte)((word>>>16)&0xff); if(--count==0) break;
215 case 2: buf[x++] = (byte)((word>>> 8)&0xff); if(--count==0) break;
216 case 3: buf[x++] = (byte)((word>>> 0)&0xff); if(--count==0) break;
220 if((count&~3) != 0) {
224 int[] page = readPages[a >>> (pageShift-2)];
225 if(page == null) throw new ReadFaultException(a<<2);
226 int index = a&pageMask;
227 int n = min(c,pageWords-index);
228 for(int i=0;i<n;i++,x+=4) {
229 int word = page[index+i];
230 buf[x+0] = (byte)((word>>>24)&0xff); buf[x+1] = (byte)((word>>>16)&0xff);
231 buf[x+2] = (byte)((word>>> 8)&0xff); buf[x+3] = (byte)((word>>> 0)&0xff);
235 addr = a<<2; count &=3;
238 int word = memRead(addr);
240 case 3: buf[x+2] = (byte)((word>>>8)&0xff);
241 case 2: buf[x+1] = (byte)((word>>>16)&0xff);
242 case 1: buf[x+0] = (byte)((word>>>24)&0xff);
247 /** Copies <i>length</i> bytes OUT OF the java array <i>a</i> into the processes memory
248 space at <i>addr</i> */
249 public final void copyout(byte[] buf, int addr, int count) throws FaultException {
250 int pageWords = (1<<pageShift)>>>2;
251 int pageWordMask = pageWords - 1;
254 if(count == 0) return;
256 int word = memRead(addr&~3);
258 case 1: word = (word&0xff00ffff)|((buf[x++]&0xff)<<16); if(--count==0) break;
259 case 2: word = (word&0xffff00ff)|((buf[x++]&0xff)<< 8); if(--count==0) break;
260 case 3: word = (word&0xffffff00)|((buf[x++]&0xff)<< 0); if(--count==0) break;
262 memWrite(addr&~3,word);
266 if((count&~3) != 0) {
270 int[] page = writePages[a >>> (pageShift-2)];
271 if(page == null) throw new WriteFaultException(a<<2);
272 int index = a&pageWordMask;
273 int n = min(c,pageWords-index);
274 for(int i=0;i<n;i++,x+=4)
275 page[index+i] = ((buf[x+0]&0xff)<<24)|((buf[x+1]&0xff)<<16)|((buf[x+2]&0xff)<<8)|((buf[x+3]&0xff)<<0);
278 addr = a<<2; count&=3;
282 int word = memRead(addr);
284 case 1: word = (word&0x00ffffff)|((buf[x+0]&0xff)<<24); break;
285 case 2: word = (word&0x0000ffff)|((buf[x+0]&0xff)<<24)|((buf[x+1]&0xff)<<16); break;
286 case 3: word = (word&0x000000ff)|((buf[x+0]&0xff)<<24)|((buf[x+1]&0xff)<<16)|((buf[x+2]&0xff)<<8); break;
292 public final void memcpy(int dst, int src, int count) throws FaultException {
293 int pageWords = (1<<pageShift)>>>2;
294 int pageWordMask = pageWords - 1;
296 if((dst&3) == 0 && (src&3)==0) {
297 if((count&~3) != 0) {
302 int[] srcPage = readPages[s>>>(pageShift-2)];
303 if(srcPage == null) throw new ReadFaultException(s<<2);
304 int[] dstPage = writePages[d>>>(pageShift-2)];
305 if(dstPage == null) throw new WriteFaultException(d<<2);
306 int srcIndex = s&pageWordMask;
307 int dstIndex = d&pageWordMask;
308 int n = min(c,pageWords-max(srcIndex,dstIndex));
309 System.arraycopy(srcPage,srcIndex,dstPage,dstIndex,n);
310 s += n; d += n; c -= n;
312 src = s<<2; dst = d<<2; count&=3;
315 int word1 = memRead(src);
316 int word2 = memRead(dst);
318 case 1: memWrite(dst,(word1&0xff000000)|(word2&0x00ffffff)); break;
319 case 2: memWrite(dst,(word1&0xffff0000)|(word2&0x0000ffff)); break;
320 case 3: memWrite(dst,(word1&0xffffff00)|(word2&0x000000ff)); break;
325 int n = min(count,MAX_CHUNK);
326 byte[] buf = byteBuf(n);
329 count -= n; src += n; dst += n;
334 public final void memset(int addr, int ch, int count) throws FaultException {
335 int pageWords = (1<<pageShift)>>>2;
336 int pageWordMask = pageWords - 1;
338 int fourBytes = ((ch&0xff)<<24)|((ch&0xff)<<16)|((ch&0xff)<<8)|((ch&0xff)<<0);
340 int word = memRead(addr&~3);
342 case 1: word = (word&0xff00ffff)|((ch&0xff)<<16); if(--count==0) break;
343 case 2: word = (word&0xffff00ff)|((ch&0xff)<< 8); if(--count==0) break;
344 case 3: word = (word&0xffffff00)|((ch&0xff)<< 0); if(--count==0) break;
346 memWrite(addr&~3,word);
349 if((count&~3) != 0) {
353 int[] page = readPages[a>>>(pageShift-2)];
354 if(page == null) throw new WriteFaultException(a<<2);
355 int index = a&pageWordMask;
356 int n = min(c,pageWords-index);
357 Arrays.fill(page,index,index+n,fourBytes);
360 addr = a<<2; count&=3;
363 int word = memRead(addr);
365 case 1: word = (word&0x00ffffff)|(fourBytes&0xff000000); break;
366 case 2: word = (word&0x0000ffff)|(fourBytes&0xffff0000); break;
367 case 3: word = (word&0x000000ff)|(fourBytes&0xffffff00); break;
373 /** Read a word from the processes memory at <i>addr</i> */
374 public final int memRead(int addr) throws ReadFaultException {
375 if((addr & 3) != 0) throw new ReadFaultException(addr);
376 return unsafeMemRead(addr);
379 protected final int unsafeMemRead(int addr) throws ReadFaultException {
380 int page = addr >>> pageShift;
381 int entry = (addr&(1<<pageShift) - 1)>>2;
383 return readPages[page][entry];
384 } catch(ArrayIndexOutOfBoundsException e) {
385 if(page < 0 || page >= readPages.length) throw new ReadFaultException(addr);
386 throw e; // should never happen
387 } catch(NullPointerException e) {
388 throw new ReadFaultException(addr);
392 /** Writes a word to the processes memory at <i>addr</i> */
393 public final void memWrite(int addr, int value) throws WriteFaultException {
394 if((addr & 3) != 0) throw new WriteFaultException(addr);
395 unsafeMemWrite(addr,value);
398 protected final void unsafeMemWrite(int addr, int value) throws WriteFaultException {
399 int page = addr >>> pageShift;
400 int entry = (addr&(1<<pageShift) - 1)>>2;
402 writePages[page][entry] = value;
403 } catch(ArrayIndexOutOfBoundsException e) {
404 if(page < 0 || page >= writePages.length) throw new WriteFaultException(addr);
405 throw e; // should never happen
406 } catch(NullPointerException e) {
407 throw new WriteFaultException(addr);
411 /** Created a new non-empty writable page at page number <i>page</i> */
412 private final int[] initPage(int page) { return initPage(page,false); }
413 /** Created a new non-empty page at page number <i>page</i>. If <i>ro</i> is set the page will be read-only */
414 private final int[] initPage(int page, boolean ro) {
415 int[] buf = new int[(1<<pageShift)>>>2];
416 writePages[page] = ro ? null : buf;
417 readPages[page] = buf;
421 /** Returns the exit status of the process. (only valid if state == DONE)
422 @see Runtime#state */
423 public final int exitStatus() {
424 if(state != EXITED) throw new IllegalStateException("exitStatus() called in an inappropriate state");
428 private int addStringArray(String[] strings, int topAddr) throws FaultException {
429 int count = strings.length;
430 int total = 0; /* null last table entry */
431 for(int i=0;i<count;i++) total += strings[i].length() + 1;
432 total += (count+1)*4;
433 int start = (topAddr - total)&~3;
434 int addr = start + (count+1)*4;
435 int[] table = new int[count+1];
437 for(int i=0;i<count;i++) {
438 byte[] a = getBytes(strings[i]);
440 copyout(a,addr,a.length);
441 memset(addr+a.length,0,1);
442 addr += a.length + 1;
445 for(int i=0;i<count+1;i++) {
446 memWrite(addr,table[i]);
449 } catch(FaultException e) {
450 // should never happen
451 throw new Error(e.toString());
456 String[] createEnv(String[] extra) { if(extra == null) extra = new String[0]; return extra; }
458 /** Sets word number <i>index</i> in the _user_info table to <i>word</i>
459 * The user_info table is a chunk of memory in the program's memory defined by the
460 * symbol "user_info". The compiler/interpreter automatically determine the size
461 * and location of the user_info table from the ELF symbol table. setUserInfo and
462 * getUserInfo are used to modify the words in the user_info table. */
463 public void setUserInfo(int index, int word) {
464 if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
466 memWrite(userInfoBase()+index*4,word);
467 } catch(FaultException e) { throw new RuntimeException(e.toString()); }
470 /** Returns the word in the _user_info table entry <i>index</i>
471 @see Runtime#setUserInfo(int,int) setUserInfo */
472 public int getUserInfo(int index) {
473 if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
475 return memRead(userInfoBase()+index*4);
476 } catch(FaultException e) { throw new RuntimeException(e.toString()); }
479 /** Calls _execute() (subclass's execute()) and catches exceptions */
480 private void __execute() {
483 } catch(FaultException e) {
485 sys_exit(128+11); // SIGSEGV
487 } catch(ExecutionException e) {
489 System.err.println(e);
490 sys_exit(128+4); // SIGILL
495 /** Executes the process until the PAUSE syscall is invoked or the process exits. Returns true if the process exited. */
496 public final boolean execute() {
497 if(state != PAUSED) throw new IllegalStateException("execute() called in inappropriate state");
498 if(startTime == 0) startTime = System.currentTimeMillis();
501 if(state != PAUSED && state != EXITED && state != EXECED)
502 throw new IllegalStateException("execute() ended up in an inappropriate state (" + state + ")");
503 return state != PAUSED;
506 static String[] concatArgv(String argv0, String[] rest) {
507 String[] argv = new String[rest.length+1];
508 System.arraycopy(rest,0,argv,1,rest.length);
513 public final int run() { return run(null); }
514 public final int run(String argv0, String[] rest) { return run(concatArgv(argv0,rest)); }
515 public final int run(String[] args) { return run(args,null); }
517 /** Runs the process until it exits and returns the exit status.
518 If the process executes the PAUSE syscall execution will be paused for 500ms and a warning will be displayed */
519 public final int run(String[] args, String[] env) {
523 System.err.println("WARNING: Pause requested while executing run()");
525 if(state == EXECED) System.err.println("WARNING: Process exec()ed while being run under run()");
526 return state == EXITED ? exitStatus() : 0;
529 public final void start() { start(null); }
530 public final void start(String[] args) { start(args,null); }
532 /** Initializes the process and prepairs it to be executed with execute() */
533 public final void start(String[] args, String[] environ) {
534 int top, sp, argsAddr, envAddr;
535 if(state != STOPPED) throw new IllegalStateException("start() called in inappropriate state");
537 if(args == null) args = new String[]{getClass().getName()};
539 sp = top = writePages.length*(1<<pageShift);
541 sp = argsAddr = addStringArray(args,sp);
542 sp = envAddr = addStringArray(createEnv(environ),sp);
543 } catch(FaultException e) {
544 throw new IllegalArgumentException("args/environ too big");
547 if(top - sp > ARG_MAX) throw new IllegalArgumentException("args/environ too big");
549 CPUState cpuState = new CPUState();
550 cpuState.r[A0] = argsAddr;
551 cpuState.r[A1] = envAddr;
553 cpuState.r[RA] = 0xdeadbeef;
554 cpuState.r[GP] = gp();
555 cpuState.pc = entryPoint();
556 setCPUState(cpuState);
563 /** Hook for subclasses to do their own startup */
566 public final int call(String sym, Object[] args) throws CallException, FaultException {
567 if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
568 if(args.length > 7) throw new IllegalArgumentException("args.length > 7");
569 CPUState state = new CPUState();
572 int sp = state.r[SP];
573 int[] ia = new int[args.length];
574 for(int i=0;i<args.length;i++) {
577 if(o instanceof String) {
578 buf = getBytes((String)o);
579 } else if(o instanceof byte[]) {
581 } else if(o instanceof Number) {
582 ia[i] = ((Number)o).intValue();
586 copyout(buf,sp,buf.length);
590 int oldSP = state.r[SP];
591 if(oldSP == sp) return call(sym,ia);
595 int ret = call(sym,ia);
601 public final int call(String sym) throws CallException { return call(sym,new int[]{}); }
602 public final int call(String sym, int a0) throws CallException { return call(sym,new int[]{a0}); }
603 public final int call(String sym, int a0, int a1) throws CallException { return call(sym,new int[]{a0,a1}); }
605 /** Calls a function in the process with the given arguments */
606 public final int call(String sym, int[] args) throws CallException {
607 int func = lookupSymbol(sym);
608 if(func == -1) throw new CallException(sym + " not found");
609 int helper = lookupSymbol("_call_helper");
610 if(helper == -1) throw new CallException("_call_helper not found");
611 return call(helper,func,args);
614 /** Executes the code at <i>addr</i> in the process setting A0-A3 and S0-S3 to the given arguments
615 and returns the contents of V1 when the the pause syscall is invoked */
616 //public final int call(int addr, int a0, int a1, int a2, int a3, int s0, int s1, int s2, int s3) {
617 public final int call(int addr, int a0, int[] rest) throws CallException {
618 if(rest.length > 7) throw new IllegalArgumentException("rest.length > 7");
619 if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
620 int oldState = state;
621 CPUState saved = new CPUState();
623 CPUState cpustate = saved.dup();
625 cpustate.r[SP] = cpustate.r[SP]&~15;
626 cpustate.r[RA] = 0xdeadbeef;
628 switch(rest.length) {
629 case 7: cpustate.r[S3] = rest[6];
630 case 6: cpustate.r[S2] = rest[5];
631 case 5: cpustate.r[S1] = rest[4];
632 case 4: cpustate.r[S0] = rest[3];
633 case 3: cpustate.r[A3] = rest[2];
634 case 2: cpustate.r[A2] = rest[1];
635 case 1: cpustate.r[A1] = rest[0];
641 setCPUState(cpustate);
643 getCPUState(cpustate);
646 if(state != PAUSED) throw new CallException("Process exit()ed while servicing a call() request");
649 return cpustate.r[V1];
652 /** Allocated an entry in the FileDescriptor table for <i>fd</i> and returns the number.
653 Returns -1 if the table is full. This can be used by subclasses to use custom file
655 public final int addFD(FD fd) {
656 if(state == EXITED || state == EXECED) throw new IllegalStateException("addFD called in inappropriate state");
658 for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
659 if(i==OPEN_MAX) return -1;
661 closeOnExec[i] = false;
665 /** Closes file descriptor <i>fdn</i> and removes it from the file descriptor table */
666 public final boolean closeFD(int fdn) {
667 if(state == EXITED || state == EXECED) throw new IllegalStateException("closeFD called in inappropriate state");
668 if(fdn < 0 || fdn >= OPEN_MAX) return false;
669 if(fds[fdn] == null) return false;
675 /** Duplicates the file descriptor <i>fdn</i> and returns the new fs */
676 public final int dupFD(int fdn) {
678 if(fdn < 0 || fdn >= OPEN_MAX) return -1;
679 if(fds[fdn] == null) return -1;
680 for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
681 if(i==OPEN_MAX) return -1;
682 fds[i] = fds[fdn].dup();
686 public static final int RD_ONLY = 0;
687 public static final int WR_ONLY = 1;
688 public static final int RDWR = 2;
690 public static final int O_CREAT = 0x0200;
691 public static final int O_EXCL = 0x0800;
692 public static final int O_APPEND = 0x0008;
693 public static final int O_TRUNC = 0x0400;
694 public static final int O_NONBLOCK = 0x4000;
696 FD hostFSOpen(final File f, int flags, int mode) throws ErrnoException {
697 if((flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)) != 0) {
698 System.err.println("WARNING: Unsupported flags passed to open(): " + toHex(flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)));
699 throw new ErrnoException(ENOTSUP);
701 boolean write = mode!=RD_ONLY;
703 if(sm != null && !(write ? sm.allowWrite(f) : sm.allowRead(f))) throw new ErrnoException(EACCES);
705 if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT)) {
707 // NOTE: createNewFile is a Java2 function
708 if(!f.createNewFile()) throw new ErrnoException(EEXIST);
709 } catch(IOException e) {
710 throw new ErrnoException(EIO);
712 } else if(!f.exists()) {
713 if((flags&O_CREAT)==0) return null;
714 } else if(f.isDirectory()) {
715 return hostFSDirFD(f);
718 final Seekable.File sf;
720 sf = new Seekable.File(f,write);
721 } catch(FileNotFoundException e) {
722 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) throw new ErrnoException(EACCES);
724 } catch(IOException e) { throw new ErrnoException(EIO); }
726 return new SeekableFD(sf,flags) { protected FStat _fstat() { return hostFStat(f); } };
729 FStat hostFStat(File f) { return new HostFStat(f); }
730 FD hostFSDirFD(File f) { return null; }
732 FD _open(String path, int flags, int mode) throws ErrnoException {
733 return hostFSOpen(new File(path),flags,mode);
736 /** The open syscall */
737 private int sys_open(int addr, int flags, int mode) throws ErrnoException, FaultException {
738 FD fd = _open(cstring(addr),flags,mode);
739 if(fd == null) return -ENOENT;
741 if(fdn == -1) { fd.close(); return -ENFILE; }
745 /** The write syscall */
746 private int sys_write(int fdn, int addr, int count) throws FaultException {
747 count = Math.min(count,MAX_CHUNK);
748 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
749 if(fds[fdn] == null || !fds[fdn].writable()) return -EBADFD;
751 byte[] buf = byteBuf(count);
752 copyin(addr,buf,count);
753 return fds[fdn].write(buf,0,count);
754 } catch(IOException e) {
755 // NOTE: This should really send a SIGPIPE
756 if(e.getMessage().equals("Pipe closed")) return sys_exit(128+13);
761 /** The read syscall */
762 private int sys_read(int fdn, int addr, int count) throws FaultException {
763 count = Math.min(count,MAX_CHUNK);
764 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
765 if(fds[fdn] == null || !fds[fdn].readable()) return -EBADFD;
767 byte[] buf = byteBuf(count);
768 int n = fds[fdn].read(buf,0,count);
771 } catch(IOException e) {
776 /** The close syscall */
777 private int sys_close(int fdn) {
778 return closeFD(fdn) ? 0 : -EBADFD;
782 /** The seek syscall */
783 private int sys_lseek(int fdn, int offset, int whence) {
784 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
785 if(fds[fdn] == null) return -EBADFD;
786 if(whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) return -EINVAL;
788 int n = fds[fdn].seek(offset,whence);
789 return n < 0 ? -ESPIPE : n;
790 } catch(IOException e) {
795 /** The stat/fstat syscall helper */
796 int stat(FStat fs, int addr) throws FaultException {
797 memWrite(addr+0,(fs.dev()<<16)|(fs.inode()&0xffff)); // st_dev (top 16), // st_ino (bottom 16)
798 memWrite(addr+4,((fs.type()&0xf000))|(fs.mode()&0xfff)); // st_mode
799 memWrite(addr+8,1<<16); // st_nlink (top 16) // st_uid (bottom 16)
800 memWrite(addr+12,0); // st_gid (top 16) // st_rdev (bottom 16)
801 memWrite(addr+16,fs.size()); // st_size
802 memWrite(addr+20,fs.atime()); // st_atime
803 // memWrite(addr+24,0) // st_spare1
804 memWrite(addr+28,fs.mtime()); // st_mtime
805 // memWrite(addr+32,0) // st_spare2
806 memWrite(addr+36,fs.ctime()); // st_ctime
807 // memWrite(addr+40,0) // st_spare3
808 memWrite(addr+44,fs.blksize()); // st_bklsize;
809 memWrite(addr+48,fs.blocks()); // st_blocks
810 // memWrite(addr+52,0) // st_spare4[0]
811 // memWrite(addr+56,0) // st_spare4[1]
815 /** The fstat syscall */
816 private int sys_fstat(int fdn, int addr) throws FaultException {
817 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
818 if(fds[fdn] == null) return -EBADFD;
819 return stat(fds[fdn].fstat(),addr);
828 private int sys_gettimeofday(int timevalAddr, int timezoneAddr) throws FaultException {
829 long now = System.currentTimeMillis();
830 int tv_sec = (int)(now / 1000);
831 int tv_usec = (int)((now%1000)*1000);
832 memWrite(timevalAddr+0,tv_sec);
833 memWrite(timevalAddr+4,tv_usec);
837 private int sys_sleep(int sec) {
838 if(sec < 0) sec = Integer.MAX_VALUE;
840 Thread.sleep((long)sec*1000);
842 } catch(InterruptedException e) {
848 #define _CLOCKS_PER_SEC_ 1000
849 #define _CLOCK_T_ unsigned long
857 private int sys_times(int tms) {
858 long now = System.currentTimeMillis();
859 int userTime = (int)((now - startTime)/16);
860 int sysTime = (int)((now - startTime)/16);
864 memWrite(tms+0,userTime);
865 memWrite(tms+4,sysTime);
866 memWrite(tms+8,userTime);
867 memWrite(tms+12,sysTime);
869 } catch(FaultException e) {
875 private int sys_sysconf(int n) {
877 case _SC_CLK_TCK: return 1000;
879 System.err.println("WARNING: Attempted to use unknown sysconf key: " + n);
884 /** The sbrk syscall. This can also be used by subclasses to allocate memory.
885 <i>incr</i> is how much to increase the break by */
886 public final int sbrk(int incr) {
887 if(incr < 0) return -ENOMEM;
888 if(incr==0) return heapEnd;
890 int oldEnd = heapEnd;
891 int newEnd = oldEnd + incr;
892 if(newEnd >= stackBottom) return -ENOMEM;
894 if(writePages.length > 1) {
895 int pageMask = (1<<pageShift) - 1;
896 int pageWords = (1<<pageShift) >>> 2;
897 int start = (oldEnd + pageMask) >>> pageShift;
898 int end = (newEnd + pageMask) >>> pageShift;
900 for(int i=start;i<end;i++) readPages[i] = writePages[i] = new int[pageWords];
901 } catch(OutOfMemoryError e) {
902 System.err.println("WARNING: Caught OOM Exception in sbrk: " + e);
910 /** The getpid syscall */
911 private int sys_getpid() { return getPid(); }
912 int getPid() { return 1; }
914 public static interface CallJavaCB { public int call(int a, int b, int c, int d); }
916 private int sys_calljava(int a, int b, int c, int d) {
917 if(state != RUNNING) throw new IllegalStateException("wound up calling sys_calljava while not in RUNNING");
918 if(callJavaCB != null) {
922 ret = callJavaCB.call(a,b,c,d);
923 } catch(RuntimeException e) {
924 System.err.println("Error while executing callJavaCB");
931 System.err.println("WARNING: calljava syscall invoked without a calljava callback set");
936 private int sys_pause() {
941 private int sys_getpagesize() { return writePages.length == 1 ? 4096 : (1<<pageShift); }
943 private int sys_isatty(int fdn) {
944 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
945 if(fds[fdn] == null) return -EBADFD;
946 return fds[fdn].isatty() ? 1 : 0;
950 /** Hook for subclasses to do something when the process exits */
953 private int sys_exit(int status) {
955 for(int i=0;i<fds.length;i++) if(fds[i] != null) closeFD(i);
961 private int sys_fcntl(int fdn, int cmd, int arg) {
964 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
965 if(fds[fdn] == null) return -EBADFD;
970 if(arg < 0 || arg >= OPEN_MAX) return -EINVAL;
971 for(i=arg;i<OPEN_MAX;i++) if(fds[i]==null) break;
972 if(i==OPEN_MAX) return -EMFILE;
977 if(fd.writable() && fd.readable()) flags = 2;
978 else if(fd.writable()) flags = 1;
981 closeOnExec[fdn] = arg != 0;
984 return closeOnExec[fdn] ? 1 : 0;
986 System.err.println("WARNING: Unknown fcntl command: " + cmd);
991 /** The syscall dispatcher.
992 The should be called by subclasses when the syscall instruction is invoked.
993 <i>syscall</i> should be the contents of V0 and <i>a</i>, <i>b</i>, <i>c</i>, and <i>d</i> should be
994 the contenst of A0, A1, A2, and A3. The call MAY change the state
995 @see Runtime#state state */
996 protected final int syscall(int syscall, int a, int b, int c, int d) {
998 return _syscall(syscall,a,b,c,d);
999 } catch(ErrnoException e) {
1000 e.printStackTrace();
1002 } catch(FaultException e) {
1004 } catch(RuntimeException e) {
1005 e.printStackTrace();
1006 throw new Error("Internal Error in _syscall()");
1010 int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
1012 case SYS_null: return 0;
1013 case SYS_exit: return sys_exit(a);
1014 case SYS_pause: return sys_pause();
1015 case SYS_write: return sys_write(a,b,c);
1016 case SYS_fstat: return sys_fstat(a,b);
1017 case SYS_sbrk: return sbrk(a);
1018 case SYS_open: return sys_open(a,b,c);
1019 case SYS_close: return sys_close(a);
1020 case SYS_read: return sys_read(a,b,c);
1021 case SYS_lseek: return sys_lseek(a,b,c);
1022 case SYS_getpid: return sys_getpid();
1023 case SYS_calljava: return sys_calljava(a,b,c,d);
1024 case SYS_gettimeofday: return sys_gettimeofday(a,b);
1025 case SYS_sleep: return sys_sleep(a);
1026 case SYS_times: return sys_times(a);
1027 case SYS_getpagesize: return sys_getpagesize();
1028 case SYS_isatty: return sys_isatty(a);
1029 case SYS_fcntl: return sys_fcntl(a,b,c);
1030 case SYS_sysconf: return sys_sysconf(a);
1041 System.err.println("Attempted to use a UnixRuntime syscall in Runtime (" + syscall + ")");
1044 System.err.println("Attempted to use unknown syscall: " + syscall);
1049 public int xmalloc(int size) { int p=malloc(size); if(p==0) throw new RuntimeException("malloc() failed"); return p; }
1050 public int xrealloc(int addr,int newsize) { int p=realloc(addr,newsize); if(p==0) throw new RuntimeException("realloc() failed"); return p; }
1051 public int realloc(int addr, int newsize) { try { return call("realloc",addr,newsize); } catch(CallException e) { return 0; } }
1052 public int malloc(int size) { try { return call("malloc",size); } catch(CallException e) { return 0; } }
1053 public void free(int p) { try { if(p!=0) call("free",p); } catch(CallException e) { /*noop*/ } }
1055 /** Helper function to create a cstring in main memory */
1056 public int strdup(String s) {
1058 if(s == null) s = "(null)";
1059 byte[] a2 = getBytes(s);
1060 a = new byte[a2.length+1];
1061 System.arraycopy(a2,0,a,0,a2.length);
1062 int addr = malloc(a.length);
1063 if(addr == 0) return 0;
1065 copyout(a,addr,a.length);
1066 } catch(FaultException e) {
1073 /** Helper function to read a cstring from main memory */
1074 public final String cstring(int addr) throws ReadFaultException {
1075 StringBuffer sb = new StringBuffer();
1077 int word = memRead(addr&~3);
1079 case 0: if(((word>>>24)&0xff)==0) return sb.toString(); sb.append((char)((word>>>24)&0xff)); addr++;
1080 case 1: if(((word>>>16)&0xff)==0) return sb.toString(); sb.append((char)((word>>>16)&0xff)); addr++;
1081 case 2: if(((word>>> 8)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 8)&0xff)); addr++;
1082 case 3: if(((word>>> 0)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 0)&0xff)); addr++;
1087 /** File Descriptor class */
1088 public static abstract class FD {
1089 private int refCount = 1;
1091 /** returns true if the fd is readable */
1092 public boolean readable() { return false; }
1093 /** returns true if the fd is writable */
1094 public boolean writable() { return false; }
1096 /** Read some bytes. Should return the number of bytes read, 0 on EOF, or throw an IOException on error */
1097 public int read(byte[] a, int off, int length) throws IOException { throw new IOException("no definition"); }
1098 /** Write. Should return the number of bytes written or throw an IOException on error */
1099 public int write(byte[] a, int off, int length) throws IOException { throw new IOException("no definition"); }
1101 /** Seek in the filedescriptor. Whence is SEEK_SET, SEEK_CUR, or SEEK_END. Should return -1 on error or the new position. */
1102 public int seek(int n, int whence) throws IOException { return -1; }
1104 /** Return a Seekable object representing this file descriptor (can be read only)
1105 This is required for exec() */
1106 Seekable seekable() { return null; }
1108 /** Should return true if this is a tty */
1109 // FIXME: get rid of the isatty syscall and just do with newlib's dumb isatty.c
1110 public boolean isatty() { return false; }
1112 private FStat cachedFStat = null;
1113 public final FStat fstat() {
1114 if(cachedFStat == null) cachedFStat = _fstat();
1118 protected abstract FStat _fstat();
1120 /** Closes the fd */
1121 public final void close() { if(--refCount==0) _close(); }
1122 protected void _close() { /* noop*/ }
1124 FD dup() { refCount++; return this; }
1127 /** FileDescriptor class for normal files */
1128 public abstract static class SeekableFD extends FD {
1129 private final int flags;
1130 private final Seekable data;
1131 public boolean readable() { return (flags&3) != WR_ONLY; }
1132 public boolean writable() { return (flags&3) != RD_ONLY; }
1134 SeekableFD(Seekable data, int flags) { this.data = data; this.flags = flags; }
1136 protected abstract FStat _fstat();
1138 Seekable seekable() { return data; }
1140 public int seek(int n, int whence) throws IOException {
1142 case SEEK_SET: break;
1143 case SEEK_CUR: n += data.pos(); break;
1144 case SEEK_END: n += data.length(); break;
1151 public int write(byte[] a, int off, int length) throws IOException {
1152 // NOTE: There is race condition here but we can't fix it in pure java
1153 if((flags&O_APPEND) != 0) seek(0,SEEK_END);
1154 return data.write(a,off,length);
1157 public int read(byte[] a, int off, int length) throws IOException {
1158 int n = data.read(a,off,length);
1159 return n < 0 ? 0 : n;
1162 protected void _close() { try { data.close(); } catch(IOException e) { /*ignore*/ } }
1165 public static class OutputStreamFD extends FD {
1166 private OutputStream os;
1167 public boolean writable() { return true; }
1168 public OutputStreamFD(OutputStream os) { this.os = os; }
1169 public int write(byte[] a, int off, int length) throws IOException { os.write(a,off,length); return length; }
1170 public void _close() { try { os.close(); } catch(IOException e) { /*ignore*/ } }
1171 public FStat _fstat() { return new FStat(); }
1174 public static class InputStreamFD extends FD {
1175 private InputStream is;
1176 public boolean readable() { return true; }
1177 public InputStreamFD(InputStream is) { this.is = is; }
1178 public int read(byte[] a, int off, int length) throws IOException { int n = is.read(a,off,length); return n < 0 ? 0 : n; }
1179 public void _close() { try { is.close(); } catch(IOException e) { /*ignore*/ } }
1180 public FStat _fstat() { return new FStat(); }
1183 static class StdinFD extends InputStreamFD {
1184 public StdinFD(InputStream is) { super(is); }
1185 public void _close() { /* noop */ }
1186 public FStat _fstat() { return new FStat() { public int type() { return S_IFCHR; } }; }
1187 public boolean isatty() { return true; }
1190 static class StdoutFD extends OutputStreamFD {
1191 public StdoutFD(OutputStream os) { super(os); }
1192 public void _close() { /* noop */ }
1193 public FStat _fstat() { return new FStat() { public int type() { return S_IFCHR; } }; }
1194 public boolean isatty() { return true; }
1197 public static class FStat {
1198 public static final int S_IFIFO = 0010000;
1199 public static final int S_IFCHR = 0020000;
1200 public static final int S_IFDIR = 0040000;
1201 public static final int S_IFREG = 0100000;
1203 public int dev() { return -1; }
1204 // FIXME: inode numbers are calculated inconsistently throught the runtime
1205 public int inode() { return hashCode() & 0xfffff; }
1206 public int mode() { return 0; }
1207 public int type() { return S_IFIFO; }
1208 public int nlink() { return 0; }
1209 public int uid() { return 0; }
1210 public int gid() { return 0; }
1211 public int size() { return 0; }
1212 public int atime() { return 0; }
1213 public int mtime() { return 0; }
1214 public int ctime() { return 0; }
1215 public int blksize() { return 512; }
1216 public int blocks() { return (size()+blksize()-1)/blksize(); }
1219 static class HostFStat extends FStat {
1220 private final File f;
1221 private final boolean executable;
1222 public HostFStat(File f) { this(f,false); }
1223 public HostFStat(File f, boolean executable) {
1225 this.executable = executable;
1227 public int dev() { return 1; }
1228 public int inode() { return f.getName().hashCode() & 0xffff; }
1229 public int type() { return f.isDirectory() ? S_IFDIR : S_IFREG; }
1230 public int nlink() { return 1; }
1233 boolean canread = f.canRead();
1234 if(canread && (executable || f.isDirectory())) mode |= 0111;
1235 if(canread) mode |= 0444;
1236 if(f.canWrite()) mode |= 0222;
1239 public int size() { return (int) f.length(); }
1240 public int mtime() { return (int)(f.lastModified()/1000); }
1244 public static class ReadFaultException extends FaultException {
1245 public ReadFaultException(int addr) { super(addr); }
1247 public static class WriteFaultException extends FaultException {
1248 public WriteFaultException(int addr) { super(addr); }
1250 public static class FaultException extends ExecutionException {
1251 public final int addr;
1252 public final RuntimeException cause;
1253 public FaultException(int addr) { super("fault at: " + toHex(addr)); this.addr = addr; cause = null; }
1254 public FaultException(RuntimeException e) { super(e.toString()); addr = -1; cause = e; }
1256 public static class ExecutionException extends Exception {
1257 private String message = "(null)";
1258 private String location = "(unknown)";
1259 public ExecutionException() { /* noop */ }
1260 public ExecutionException(String s) { if(s != null) message = s; }
1261 void setLocation(String s) { location = s == null ? "(unknown)" : s; }
1262 public final String getMessage() { return message + " at " + location; }
1264 public static class CallException extends Exception {
1265 public CallException(String s) { super(s); }
1268 protected static class ErrnoException extends Exception {
1270 public ErrnoException(int errno) { super("Errno: " + errno); this.errno = errno; }
1274 protected static class CPUState {
1275 public CPUState() { /* noop */ }
1277 public int[] r = new int[32];
1278 /* Floating point regs */
1279 public int[] f = new int[32];
1284 public CPUState dup() {
1285 CPUState c = new CPUState();
1290 for(int i=0;i<32;i++) {
1298 public static class SecurityManager {
1299 public boolean allowRead(File f) { return true; }
1300 public boolean allowWrite(File f) { return true; }
1301 public boolean allowStat(File f) { return true; }
1304 // Null pointer check helper function
1305 protected final void nullPointerCheck(int addr) throws ExecutionException {
1307 throw new ExecutionException("Attempted to dereference a null pointer " + toHex(addr));
1310 // Utility functions
1311 private byte[] byteBuf(int size) {
1312 if(_byteBuf==null) _byteBuf = new byte[size];
1313 else if(_byteBuf.length < size)
1314 _byteBuf = new byte[min(max(_byteBuf.length*2,size),MAX_CHUNK)];
1318 static String getSystemProperty(String key) {
1320 return System.getProperty(key);
1321 } catch(SecurityException e) {
1326 /** Decode a packed string */
1327 protected static final int[] decodeData(String s, int words) {
1328 if(s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
1329 if((s.length() / 8) * 7 < words*4) throw new IllegalArgumentException("string isn't big enough");
1330 int[] buf = new int[words];
1331 int prev = 0, left=0;
1332 for(int i=0,n=0;n<words;i+=8) {
1334 for(int j=0;j<8;j++) { l <<= 7; l |= s.charAt(i+j) & 0x7f; }
1335 if(left > 0) buf[n++] = prev | (int)(l>>>(56-left));
1336 if(n < words) buf[n++] = (int) (l >>> (24-left));
1337 left = (left + 8) & 0x1f;
1338 prev = (int)(l << left);
1343 static byte[] getBytes(String s) {
1345 return s.getBytes("ISO-8859-1");
1346 } catch(UnsupportedEncodingException e) {
1347 return null; // should never happen
1351 final static String toHex(int n) { return "0x" + Long.toString(n & 0xffffffffL, 16); }
1352 final static int min(int a, int b) { return a < b ? a : b; }
1353 final static int max(int a, int b) { return a > b ? a : b; }