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 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;
295 if((dst&3) == 0 && (src&3)==0) {
296 if((count&~3) != 0) {
301 int[] srcPage = readPages[s>>>(pageShift-2)];
302 if(srcPage == null) throw new ReadFaultException(s<<2);
303 int[] dstPage = writePages[d>>>(pageShift-2)];
304 if(dstPage == null) throw new WriteFaultException(d<<2);
305 int srcIndex = s&pageWordMask;
306 int dstIndex = d&pageWordMask;
307 int n = min(c,pageWords-max(srcIndex,dstIndex));
308 System.arraycopy(srcPage,srcIndex,dstPage,dstIndex,n);
309 s += n; d += n; c -= n;
311 src = s<<2; dst = d<<2; count&=3;
314 int word1 = memRead(src);
315 int word2 = memRead(dst);
317 case 1: memWrite(dst,(word1&0xff000000)|(word2&0x00ffffff)); break;
318 case 2: memWrite(dst,(word1&0xffff0000)|(word2&0x0000ffff)); break;
319 case 3: memWrite(dst,(word1&0xffffff00)|(word2&0x000000ff)); break;
324 int n = min(count,MAX_CHUNK);
325 byte[] buf = byteBuf(n);
328 count -= n; src += n; dst += n;
333 public final void memset(int addr, int ch, int count) throws FaultException {
334 int pageWords = (1<<pageShift)>>>2;
335 int pageWordMask = pageWords - 1;
337 int fourBytes = ((ch&0xff)<<24)|((ch&0xff)<<16)|((ch&0xff)<<8)|((ch&0xff)<<0);
339 int word = memRead(addr&~3);
341 case 1: word = (word&0xff00ffff)|((ch&0xff)<<16); if(--count==0) break;
342 case 2: word = (word&0xffff00ff)|((ch&0xff)<< 8); if(--count==0) break;
343 case 3: word = (word&0xffffff00)|((ch&0xff)<< 0); if(--count==0) break;
345 memWrite(addr&~3,word);
348 if((count&~3) != 0) {
352 int[] page = readPages[a>>>(pageShift-2)];
353 if(page == null) throw new WriteFaultException(a<<2);
354 int index = a&pageWordMask;
355 int n = min(c,pageWords-index);
356 Arrays.fill(page,index,index+n,fourBytes);
359 addr = a<<2; count&=3;
362 int word = memRead(addr);
364 case 1: word = (word&0x00ffffff)|(fourBytes&0xff000000); break;
365 case 2: word = (word&0x0000ffff)|(fourBytes&0xffff0000); break;
366 case 3: word = (word&0x000000ff)|(fourBytes&0xffffff00); break;
372 /** Read a word from the processes memory at <i>addr</i> */
373 public final int memRead(int addr) throws ReadFaultException {
374 if((addr & 3) != 0) throw new ReadFaultException(addr);
375 return unsafeMemRead(addr);
378 protected final int unsafeMemRead(int addr) throws ReadFaultException {
379 int page = addr >>> pageShift;
380 int entry = (addr&(1<<pageShift) - 1)>>2;
382 return readPages[page][entry];
383 } catch(ArrayIndexOutOfBoundsException e) {
384 if(page < 0 || page >= readPages.length) throw new ReadFaultException(addr);
385 throw e; // should never happen
386 } catch(NullPointerException e) {
387 throw new ReadFaultException(addr);
391 /** Writes a word to the processes memory at <i>addr</i> */
392 public final void memWrite(int addr, int value) throws WriteFaultException {
393 if((addr & 3) != 0) throw new WriteFaultException(addr);
394 unsafeMemWrite(addr,value);
397 protected final void unsafeMemWrite(int addr, int value) throws WriteFaultException {
398 int page = addr >>> pageShift;
399 int entry = (addr&(1<<pageShift) - 1)>>2;
401 writePages[page][entry] = value;
402 } catch(ArrayIndexOutOfBoundsException e) {
403 if(page < 0 || page >= writePages.length) throw new WriteFaultException(addr);
404 throw e; // should never happen
405 } catch(NullPointerException e) {
406 throw new WriteFaultException(addr);
410 /** Created a new non-empty writable page at page number <i>page</i> */
411 private final int[] initPage(int page) { return initPage(page,false); }
412 /** Created a new non-empty page at page number <i>page</i>. If <i>ro</i> is set the page will be read-only */
413 private final int[] initPage(int page, boolean ro) {
414 int[] buf = new int[(1<<pageShift)>>>2];
415 writePages[page] = ro ? null : buf;
416 readPages[page] = buf;
420 /** Returns the exit status of the process. (only valid if state == DONE)
421 @see Runtime#state */
422 public final int exitStatus() {
423 if(state != EXITED) throw new IllegalStateException("exitStatus() called in an inappropriate state");
427 private int addStringArray(String[] strings, int topAddr) throws FaultException {
428 int count = strings.length;
429 int total = 0; /* null last table entry */
430 for(int i=0;i<count;i++) total += strings[i].length() + 1;
431 total += (count+1)*4;
432 int start = (topAddr - total)&~3;
433 int addr = start + (count+1)*4;
434 int[] table = new int[count+1];
436 for(int i=0;i<count;i++) {
437 byte[] a = getBytes(strings[i]);
439 copyout(a,addr,a.length);
440 memset(addr+a.length,0,1);
441 addr += a.length + 1;
444 for(int i=0;i<count+1;i++) {
445 memWrite(addr,table[i]);
448 } catch(FaultException e) {
449 // should never happen
450 throw new Error(e.toString());
455 String[] createEnv(String[] extra) { if(extra == null) extra = new String[0]; return extra; }
457 /** Sets word number <i>index</i> in the _user_info table to <i>word</i>
458 * The user_info table is a chunk of memory in the program's memory defined by the
459 * symbol "user_info". The compiler/interpreter automatically determine the size
460 * and location of the user_info table from the ELF symbol table. setUserInfo and
461 * getUserInfo are used to modify the words in the user_info table. */
462 public void setUserInfo(int index, int word) {
463 if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
465 memWrite(userInfoBase()+index*4,word);
466 } catch(FaultException e) { throw new RuntimeException(e.toString()); }
469 /** Returns the word in the _user_info table entry <i>index</i>
470 @see Runtime#setUserInfo(int,int) setUserInfo */
471 public int getUserInfo(int index) {
472 if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
474 return memRead(userInfoBase()+index*4);
475 } catch(FaultException e) { throw new RuntimeException(e.toString()); }
478 /** Calls _execute() (subclass's execute()) and catches exceptions */
479 private void __execute() {
482 } catch(FaultException e) {
484 sys_exit(128+11); // SIGSEGV
486 } catch(ExecutionException e) {
488 System.err.println(e);
489 sys_exit(128+4); // SIGILL
494 /** Executes the process until the PAUSE syscall is invoked or the process exits. Returns true if the process exited. */
495 public final boolean execute() {
496 if(state != PAUSED) throw new IllegalStateException("execute() called in inappropriate state");
497 if(startTime == 0) startTime = System.currentTimeMillis();
500 if(state != PAUSED && state != EXITED && state != EXECED)
501 throw new IllegalStateException("execute() ended up in an inappropriate state (" + state + ")");
502 return state != PAUSED;
505 static String[] concatArgv(String argv0, String[] rest) {
506 String[] argv = new String[rest.length+1];
507 System.arraycopy(rest,0,argv,1,rest.length);
512 public final int run() { return run(null); }
513 public final int run(String argv0, String[] rest) { return run(concatArgv(argv0,rest)); }
514 public final int run(String[] args) { return run(args,null); }
516 /** Runs the process until it exits and returns the exit status.
517 If the process executes the PAUSE syscall execution will be paused for 500ms and a warning will be displayed */
518 public final int run(String[] args, String[] env) {
522 System.err.println("WARNING: Pause requested while executing run()");
524 if(state == EXECED) System.err.println("WARNING: Process exec()ed while being run under run()");
525 return state == EXITED ? exitStatus() : 0;
528 public final void start() { start(null); }
529 public final void start(String[] args) { start(args,null); }
531 /** Initializes the process and prepairs it to be executed with execute() */
532 public final void start(String[] args, String[] environ) {
533 int top, sp, argsAddr, envAddr;
534 if(state != STOPPED) throw new IllegalStateException("start() called in inappropriate state");
536 if(args == null) args = new String[]{getClass().getName()};
538 sp = top = writePages.length*(1<<pageShift);
540 sp = argsAddr = addStringArray(args,sp);
541 sp = envAddr = addStringArray(createEnv(environ),sp);
542 } catch(FaultException e) {
543 throw new IllegalArgumentException("args/environ too big");
546 if(top - sp > ARG_MAX) throw new IllegalArgumentException("args/environ too big");
548 CPUState cpuState = new CPUState();
549 cpuState.r[A0] = argsAddr;
550 cpuState.r[A1] = envAddr;
552 cpuState.r[RA] = 0xdeadbeef;
553 cpuState.r[GP] = gp();
554 cpuState.pc = entryPoint();
555 setCPUState(cpuState);
562 /** Hook for subclasses to do their own startup */
565 public final int call(String sym, Object[] args) throws CallException, FaultException {
566 if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
567 if(args.length > 7) throw new IllegalArgumentException("args.length > 7");
568 CPUState state = new CPUState();
571 int sp = state.r[SP];
572 int[] ia = new int[args.length];
573 for(int i=0;i<args.length;i++) {
576 if(o instanceof String) {
577 buf = getBytes((String)o);
578 } else if(o instanceof byte[]) {
580 } else if(o instanceof Number) {
581 ia[i] = ((Number)o).intValue();
585 copyout(buf,sp,buf.length);
589 int oldSP = state.r[SP];
590 if(oldSP == sp) return call(sym,ia);
594 int ret = call(sym,ia);
600 public final int call(String sym) throws CallException { return call(sym,new int[]{}); }
601 public final int call(String sym, int a0) throws CallException { return call(sym,new int[]{a0}); }
602 public final int call(String sym, int a0, int a1) throws CallException { return call(sym,new int[]{a0,a1}); }
604 /** Calls a function in the process with the given arguments */
605 public final int call(String sym, int[] args) throws CallException {
606 int func = lookupSymbol(sym);
607 if(func == -1) throw new CallException(sym + " not found");
608 int helper = lookupSymbol("_call_helper");
609 if(helper == -1) throw new CallException("_call_helper not found");
610 return call(helper,func,args);
613 /** Executes the code at <i>addr</i> in the process setting A0-A3 and S0-S3 to the given arguments
614 and returns the contents of V1 when the the pause syscall is invoked */
615 //public final int call(int addr, int a0, int a1, int a2, int a3, int s0, int s1, int s2, int s3) {
616 public final int call(int addr, int a0, int[] rest) throws CallException {
617 if(rest.length > 7) throw new IllegalArgumentException("rest.length > 7");
618 if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
619 int oldState = state;
620 CPUState saved = new CPUState();
622 CPUState cpustate = saved.dup();
624 cpustate.r[SP] = cpustate.r[SP]&~15;
625 cpustate.r[RA] = 0xdeadbeef;
627 switch(rest.length) {
628 case 7: cpustate.r[S3] = rest[6];
629 case 6: cpustate.r[S2] = rest[5];
630 case 5: cpustate.r[S1] = rest[4];
631 case 4: cpustate.r[S0] = rest[3];
632 case 3: cpustate.r[A3] = rest[2];
633 case 2: cpustate.r[A2] = rest[1];
634 case 1: cpustate.r[A1] = rest[0];
640 setCPUState(cpustate);
642 getCPUState(cpustate);
645 if(state != PAUSED) throw new CallException("Process exit()ed while servicing a call() request");
648 return cpustate.r[V1];
651 /** Allocated an entry in the FileDescriptor table for <i>fd</i> and returns the number.
652 Returns -1 if the table is full. This can be used by subclasses to use custom file
654 public final int addFD(FD fd) {
655 if(state == EXITED || state == EXECED) throw new IllegalStateException("addFD called in inappropriate state");
657 for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
658 if(i==OPEN_MAX) return -1;
660 closeOnExec[i] = false;
664 /** Closes file descriptor <i>fdn</i> and removes it from the file descriptor table */
665 public final boolean closeFD(int fdn) {
666 if(state == EXITED || state == EXECED) throw new IllegalStateException("closeFD called in inappropriate state");
667 if(fdn < 0 || fdn >= OPEN_MAX) return false;
668 if(fds[fdn] == null) return false;
674 /** Duplicates the file descriptor <i>fdn</i> and returns the new fs */
675 public final int dupFD(int fdn) {
677 if(fdn < 0 || fdn >= OPEN_MAX) return -1;
678 if(fds[fdn] == null) return -1;
679 for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
680 if(i==OPEN_MAX) return -1;
681 fds[i] = fds[fdn].dup();
685 public static final int RD_ONLY = 0;
686 public static final int WR_ONLY = 1;
687 public static final int RDWR = 2;
689 public static final int O_CREAT = 0x0200;
690 public static final int O_EXCL = 0x0800;
691 public static final int O_APPEND = 0x0008;
692 public static final int O_TRUNC = 0x0400;
693 public static final int O_NONBLOCK = 0x4000;
695 FD hostFSOpen(final File f, int flags, int mode, final Object data) throws ErrnoException {
696 if((flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)) != 0) {
697 System.err.println("WARNING: Unsupported flags passed to open(): " + toHex(flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)));
698 throw new ErrnoException(ENOTSUP);
700 boolean write = (flags&3) != RD_ONLY;
702 if(sm != null && !(write ? sm.allowWrite(f) : sm.allowRead(f))) throw new ErrnoException(EACCES);
704 if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT)) {
706 // NOTE: createNewFile is a Java2 function
707 if(!f.createNewFile()) throw new ErrnoException(EEXIST);
708 } catch(IOException e) {
709 throw new ErrnoException(EIO);
711 } else if(!f.exists()) {
712 if((flags&O_CREAT)==0) return null;
713 } else if(f.isDirectory()) {
714 return hostFSDirFD(f,data);
717 final Seekable.File sf;
719 sf = new Seekable.File(f,write);
720 } catch(FileNotFoundException e) {
721 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) throw new ErrnoException(EACCES);
723 } catch(IOException e) { throw new ErrnoException(EIO); }
725 return new SeekableFD(sf,flags) { protected FStat _fstat() { return hostFStat(f,data); } };
728 FStat hostFStat(File f, Object data) { return new HostFStat(f); }
730 FD hostFSDirFD(File f, Object data) { return null; }
732 FD _open(String path, int flags, int mode) throws ErrnoException {
733 return hostFSOpen(new File(path),flags,mode,null);
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 */
747 // FIXME: Handle pipe closed exception
748 private int sys_write(int fdn, int addr, int count) throws FaultException, ErrnoException {
749 count = Math.min(count,MAX_CHUNK);
750 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
751 if(fds[fdn] == null) return -EBADFD;
752 byte[] buf = byteBuf(count);
753 copyin(addr,buf,count);
754 return fds[fdn].write(buf,0,count);
757 /** The read syscall */
758 private int sys_read(int fdn, int addr, int count) throws FaultException, ErrnoException {
759 count = Math.min(count,MAX_CHUNK);
760 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
761 if(fds[fdn] == null) return -EBADFD;
762 byte[] buf = byteBuf(count);
763 int n = fds[fdn].read(buf,0,count);
768 /** The close syscall */
769 private int sys_close(int fdn) {
770 return closeFD(fdn) ? 0 : -EBADFD;
774 /** The seek syscall */
775 private int sys_lseek(int fdn, int offset, int whence) throws ErrnoException {
776 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
777 if(fds[fdn] == null) return -EBADFD;
778 if(whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) return -EINVAL;
779 int n = fds[fdn].seek(offset,whence);
780 return n < 0 ? -ESPIPE : n;
783 /** The stat/fstat syscall helper */
784 int stat(FStat fs, int addr) throws FaultException {
785 memWrite(addr+0,(fs.dev()<<16)|(fs.inode()&0xffff)); // st_dev (top 16), // st_ino (bottom 16)
786 memWrite(addr+4,((fs.type()&0xf000))|(fs.mode()&0xfff)); // st_mode
787 memWrite(addr+8,1<<16); // st_nlink (top 16) // st_uid (bottom 16)
788 memWrite(addr+12,0); // st_gid (top 16) // st_rdev (bottom 16)
789 memWrite(addr+16,fs.size()); // st_size
790 memWrite(addr+20,fs.atime()); // st_atime
791 // memWrite(addr+24,0) // st_spare1
792 memWrite(addr+28,fs.mtime()); // st_mtime
793 // memWrite(addr+32,0) // st_spare2
794 memWrite(addr+36,fs.ctime()); // st_ctime
795 // memWrite(addr+40,0) // st_spare3
796 memWrite(addr+44,fs.blksize()); // st_bklsize;
797 memWrite(addr+48,fs.blocks()); // st_blocks
798 // memWrite(addr+52,0) // st_spare4[0]
799 // memWrite(addr+56,0) // st_spare4[1]
803 /** The fstat syscall */
804 private int sys_fstat(int fdn, int addr) throws FaultException {
805 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
806 if(fds[fdn] == null) return -EBADFD;
807 return stat(fds[fdn].fstat(),addr);
816 private int sys_gettimeofday(int timevalAddr, int timezoneAddr) throws FaultException {
817 long now = System.currentTimeMillis();
818 int tv_sec = (int)(now / 1000);
819 int tv_usec = (int)((now%1000)*1000);
820 memWrite(timevalAddr+0,tv_sec);
821 memWrite(timevalAddr+4,tv_usec);
825 private int sys_sleep(int sec) {
826 if(sec < 0) sec = Integer.MAX_VALUE;
828 Thread.sleep((long)sec*1000);
830 } catch(InterruptedException e) {
836 #define _CLOCKS_PER_SEC_ 1000
837 #define _CLOCK_T_ unsigned long
845 private int sys_times(int tms) {
846 long now = System.currentTimeMillis();
847 int userTime = (int)((now - startTime)/16);
848 int sysTime = (int)((now - startTime)/16);
852 memWrite(tms+0,userTime);
853 memWrite(tms+4,sysTime);
854 memWrite(tms+8,userTime);
855 memWrite(tms+12,sysTime);
857 } catch(FaultException e) {
863 private int sys_sysconf(int n) {
865 case _SC_CLK_TCK: return 1000;
867 System.err.println("WARNING: Attempted to use unknown sysconf key: " + n);
872 /** The sbrk syscall. This can also be used by subclasses to allocate memory.
873 <i>incr</i> is how much to increase the break by */
874 public final int sbrk(int incr) {
875 if(incr < 0) return -ENOMEM;
876 if(incr==0) return heapEnd;
878 int oldEnd = heapEnd;
879 int newEnd = oldEnd + incr;
880 if(newEnd >= stackBottom) return -ENOMEM;
882 if(writePages.length > 1) {
883 int pageMask = (1<<pageShift) - 1;
884 int pageWords = (1<<pageShift) >>> 2;
885 int start = (oldEnd + pageMask) >>> pageShift;
886 int end = (newEnd + pageMask) >>> pageShift;
888 for(int i=start;i<end;i++) readPages[i] = writePages[i] = new int[pageWords];
889 } catch(OutOfMemoryError e) {
890 System.err.println("WARNING: Caught OOM Exception in sbrk: " + e);
898 /** The getpid syscall */
899 private int sys_getpid() { return getPid(); }
900 int getPid() { return 1; }
902 public static interface CallJavaCB { public int call(int a, int b, int c, int d); }
904 private int sys_calljava(int a, int b, int c, int d) {
905 if(state != RUNNING) throw new IllegalStateException("wound up calling sys_calljava while not in RUNNING");
906 if(callJavaCB != null) {
910 ret = callJavaCB.call(a,b,c,d);
911 } catch(RuntimeException e) {
912 System.err.println("Error while executing callJavaCB");
919 System.err.println("WARNING: calljava syscall invoked without a calljava callback set");
924 private int sys_pause() {
929 private int sys_getpagesize() { return writePages.length == 1 ? 4096 : (1<<pageShift); }
931 /** Hook for subclasses to do something when the process exits */
934 private int sys_exit(int status) {
936 for(int i=0;i<fds.length;i++) if(fds[i] != null) closeFD(i);
942 private int sys_fcntl(int fdn, int cmd, int arg) {
945 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
946 if(fds[fdn] == null) return -EBADFD;
951 if(arg < 0 || arg >= OPEN_MAX) return -EINVAL;
952 for(i=arg;i<OPEN_MAX;i++) if(fds[i]==null) break;
953 if(i==OPEN_MAX) return -EMFILE;
959 closeOnExec[fdn] = arg != 0;
962 return closeOnExec[fdn] ? 1 : 0;
964 System.err.println("WARNING: Unknown fcntl command: " + cmd);
969 /** The syscall dispatcher.
970 The should be called by subclasses when the syscall instruction is invoked.
971 <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
972 the contenst of A0, A1, A2, and A3. The call MAY change the state
973 @see Runtime#state state */
974 protected final int syscall(int syscall, int a, int b, int c, int d) {
976 return _syscall(syscall,a,b,c,d);
977 } catch(ErrnoException e) {
980 } catch(FaultException e) {
982 } catch(RuntimeException e) {
984 throw new Error("Internal Error in _syscall()");
988 int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
990 case SYS_null: return 0;
991 case SYS_exit: return sys_exit(a);
992 case SYS_pause: return sys_pause();
993 case SYS_write: return sys_write(a,b,c);
994 case SYS_fstat: return sys_fstat(a,b);
995 case SYS_sbrk: return sbrk(a);
996 case SYS_open: return sys_open(a,b,c);
997 case SYS_close: return sys_close(a);
998 case SYS_read: return sys_read(a,b,c);
999 case SYS_lseek: return sys_lseek(a,b,c);
1000 case SYS_getpid: return sys_getpid();
1001 case SYS_calljava: return sys_calljava(a,b,c,d);
1002 case SYS_gettimeofday: return sys_gettimeofday(a,b);
1003 case SYS_sleep: return sys_sleep(a);
1004 case SYS_times: return sys_times(a);
1005 case SYS_getpagesize: return sys_getpagesize();
1006 case SYS_fcntl: return sys_fcntl(a,b,c);
1007 case SYS_sysconf: return sys_sysconf(a);
1009 case SYS_memcpy: memcpy(a,b,c); return a;
1010 case SYS_memset: memset(a,b,c); return a;
1021 System.err.println("Attempted to use a UnixRuntime syscall in Runtime (" + syscall + ")");
1024 System.err.println("Attempted to use unknown syscall: " + syscall);
1029 public int xmalloc(int size) { int p=malloc(size); if(p==0) throw new RuntimeException("malloc() failed"); return p; }
1030 public int xrealloc(int addr,int newsize) { int p=realloc(addr,newsize); if(p==0) throw new RuntimeException("realloc() failed"); return p; }
1031 public int realloc(int addr, int newsize) { try { return call("realloc",addr,newsize); } catch(CallException e) { return 0; } }
1032 public int malloc(int size) { try { return call("malloc",size); } catch(CallException e) { return 0; } }
1033 public void free(int p) { try { if(p!=0) call("free",p); } catch(CallException e) { /*noop*/ } }
1035 /** Helper function to create a cstring in main memory */
1036 public int strdup(String s) {
1038 if(s == null) s = "(null)";
1039 byte[] a2 = getBytes(s);
1040 a = new byte[a2.length+1];
1041 System.arraycopy(a2,0,a,0,a2.length);
1042 int addr = malloc(a.length);
1043 if(addr == 0) return 0;
1045 copyout(a,addr,a.length);
1046 } catch(FaultException e) {
1053 /** Helper function to read a cstring from main memory */
1054 public final String cstring(int addr) throws ReadFaultException {
1055 StringBuffer sb = new StringBuffer();
1057 int word = memRead(addr&~3);
1059 case 0: if(((word>>>24)&0xff)==0) return sb.toString(); sb.append((char)((word>>>24)&0xff)); addr++;
1060 case 1: if(((word>>>16)&0xff)==0) return sb.toString(); sb.append((char)((word>>>16)&0xff)); addr++;
1061 case 2: if(((word>>> 8)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 8)&0xff)); addr++;
1062 case 3: if(((word>>> 0)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 0)&0xff)); addr++;
1067 /** File Descriptor class */
1068 public static abstract class FD {
1069 private int refCount = 1;
1071 /** Read some bytes. Should return the number of bytes read, 0 on EOF, or throw an IOException on error */
1072 public int read(byte[] a, int off, int length) throws ErrnoException { throw new ErrnoException(EBADFD); }
1073 /** Write. Should return the number of bytes written or throw an IOException on error */
1074 public int write(byte[] a, int off, int length) throws ErrnoException { throw new ErrnoException(EBADFD); }
1076 /** Seek in the filedescriptor. Whence is SEEK_SET, SEEK_CUR, or SEEK_END. Should return -1 on error or the new position. */
1077 public int seek(int n, int whence) throws ErrnoException { return -1; }
1079 public int getdents(byte[] a, int off, int length) throws ErrnoException { throw new ErrnoException(EBADFD); }
1081 public int flags() { return O_RDONLY; }
1083 /** Return a Seekable object representing this file descriptor (can be read only)
1084 This is required for exec() */
1085 Seekable seekable() { return null; }
1087 private FStat cachedFStat = null;
1088 public final FStat fstat() {
1089 if(cachedFStat == null) cachedFStat = _fstat();
1093 protected abstract FStat _fstat();
1095 /** Closes the fd */
1096 public final void close() { if(--refCount==0) _close(); }
1097 protected void _close() { /* noop*/ }
1099 FD dup() { refCount++; return this; }
1102 /** FileDescriptor class for normal files */
1103 public abstract static class SeekableFD extends FD {
1104 private final int flags;
1105 private final Seekable data;
1107 SeekableFD(Seekable data, int flags) { this.data = data; this.flags = flags; }
1109 protected abstract FStat _fstat();
1110 public int flags() { return flags; }
1112 Seekable seekable() { return data; }
1114 public int seek(int n, int whence) throws ErrnoException {
1117 case SEEK_SET: break;
1118 case SEEK_CUR: n += data.pos(); break;
1119 case SEEK_END: n += data.length(); break;
1124 } catch(IOException e) {
1125 throw new ErrnoException(ESPIPE);
1129 public int write(byte[] a, int off, int length) throws ErrnoException {
1130 if((flags&3) == RD_ONLY) throw new ErrnoException(EBADFD);
1131 // NOTE: There is race condition here but we can't fix it in pure java
1132 if((flags&O_APPEND) != 0) seek(0,SEEK_END);
1134 return data.write(a,off,length);
1135 } catch(IOException e) {
1136 throw new ErrnoException(EIO);
1140 public int read(byte[] a, int off, int length) throws ErrnoException {
1141 if((flags&3) == WR_ONLY) throw new ErrnoException(EBADFD);
1143 int n = data.read(a,off,length);
1144 return n < 0 ? 0 : n;
1145 } catch(IOException e) {
1146 throw new ErrnoException(EIO);
1150 protected void _close() { try { data.close(); } catch(IOException e) { /*ignore*/ } }
1153 public static class OutputStreamFD extends FD {
1154 private OutputStream os;
1155 public int flags() { return O_WRONLY; }
1156 public OutputStreamFD(OutputStream os) { this.os = os; }
1157 public int write(byte[] a, int off, int length) throws ErrnoException {
1159 os.write(a,off,length);
1161 } catch(IOException e) {
1162 throw new ErrnoException(EIO);
1165 public void _close() { try { os.close(); } catch(IOException e) { /*ignore*/ } }
1166 public FStat _fstat() { return new FStat(); }
1169 public static class InputStreamFD extends FD {
1170 private InputStream is;
1171 public int flags() { return O_RDONLY; }
1172 public InputStreamFD(InputStream is) { this.is = is; }
1173 public int read(byte[] a, int off, int length) throws ErrnoException {
1175 int n = is.read(a,off,length);
1176 return n < 0 ? 0 : n;
1177 } catch(IOException e) {
1178 throw new ErrnoException(EIO);
1181 public void _close() { try { is.close(); } catch(IOException e) { /*ignore*/ } }
1182 public FStat _fstat() { return new FStat(); }
1185 static class StdinFD extends InputStreamFD {
1186 public StdinFD(InputStream is) { super(is); }
1187 public void _close() { /* noop */ }
1188 public FStat _fstat() { return new FStat() { public int type() { return S_IFCHR; } }; }
1191 static class StdoutFD extends OutputStreamFD {
1192 public StdoutFD(OutputStream os) { super(os); }
1193 public void _close() { /* noop */ }
1194 public FStat _fstat() { return new FStat() { public int type() { return S_IFCHR; } }; }
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 public int inode() { return hashCode() & 0x7fff; }
1205 public int mode() { return 0; }
1206 public int type() { return S_IFIFO; }
1207 public int nlink() { return 0; }
1208 public int uid() { return 0; }
1209 public int gid() { return 0; }
1210 public int size() { return 0; }
1211 public int atime() { return 0; }
1212 public int mtime() { return 0; }
1213 public int ctime() { return 0; }
1214 public int blksize() { return 512; }
1215 public int blocks() { return (size()+blksize()-1)/blksize(); }
1218 static class HostFStat extends FStat {
1219 private final File f;
1220 private final boolean executable;
1221 public HostFStat(File f) { this(f,false); }
1222 public HostFStat(File f, boolean executable) {
1224 this.executable = executable;
1226 public int dev() { return 1; }
1227 public int inode() { return f.getName().hashCode() & 0xffff; }
1228 public int type() { return f.isDirectory() ? S_IFDIR : S_IFREG; }
1229 public int nlink() { return 1; }
1232 boolean canread = f.canRead();
1233 if(canread && (executable || f.isDirectory())) mode |= 0111;
1234 if(canread) mode |= 0444;
1235 if(f.canWrite()) mode |= 0222;
1238 public int size() { return (int) f.length(); }
1239 public int mtime() { return (int)(f.lastModified()/1000); }
1243 public static class ReadFaultException extends FaultException {
1244 public ReadFaultException(int addr) { super(addr); }
1246 public static class WriteFaultException extends FaultException {
1247 public WriteFaultException(int addr) { super(addr); }
1249 public static class FaultException extends ExecutionException {
1250 public final int addr;
1251 public final RuntimeException cause;
1252 public FaultException(int addr) { super("fault at: " + toHex(addr)); this.addr = addr; cause = null; }
1253 public FaultException(RuntimeException e) { super(e.toString()); addr = -1; cause = e; }
1255 public static class ExecutionException extends Exception {
1256 private String message = "(null)";
1257 private String location = "(unknown)";
1258 public ExecutionException() { /* noop */ }
1259 public ExecutionException(String s) { if(s != null) message = s; }
1260 void setLocation(String s) { location = s == null ? "(unknown)" : s; }
1261 public final String getMessage() { return message + " at " + location; }
1263 public static class CallException extends Exception {
1264 public CallException(String s) { super(s); }
1267 protected static class ErrnoException extends Exception {
1269 public ErrnoException(int errno) { super("Errno: " + errno); this.errno = errno; }
1273 protected static class CPUState {
1274 public CPUState() { /* noop */ }
1276 public int[] r = new int[32];
1277 /* Floating point regs */
1278 public int[] f = new int[32];
1283 public CPUState dup() {
1284 CPUState c = new CPUState();
1289 for(int i=0;i<32;i++) {
1297 public static class SecurityManager {
1298 public boolean allowRead(File f) { return true; }
1299 public boolean allowWrite(File f) { return true; }
1300 public boolean allowStat(File f) { return true; }
1303 // Null pointer check helper function
1304 protected final void nullPointerCheck(int addr) throws ExecutionException {
1306 throw new ExecutionException("Attempted to dereference a null pointer " + toHex(addr));
1309 // Utility functions
1310 byte[] byteBuf(int size) {
1311 if(_byteBuf==null) _byteBuf = new byte[size];
1312 else if(_byteBuf.length < size)
1313 _byteBuf = new byte[min(max(_byteBuf.length*2,size),MAX_CHUNK)];
1317 static String getSystemProperty(String key) {
1319 return System.getProperty(key);
1320 } catch(SecurityException e) {
1325 /** Decode a packed string */
1326 protected static final int[] decodeData(String s, int words) {
1327 if(s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
1328 if((s.length() / 8) * 7 < words*4) throw new IllegalArgumentException("string isn't big enough");
1329 int[] buf = new int[words];
1330 int prev = 0, left=0;
1331 for(int i=0,n=0;n<words;i+=8) {
1333 for(int j=0;j<8;j++) { l <<= 7; l |= s.charAt(i+j) & 0x7f; }
1334 if(left > 0) buf[n++] = prev | (int)(l>>>(56-left));
1335 if(n < words) buf[n++] = (int) (l >>> (24-left));
1336 left = (left + 8) & 0x1f;
1337 prev = (int)(l << left);
1342 static byte[] getBytes(String s) {
1344 return s.getBytes("ISO-8859-1");
1345 } catch(UnsupportedEncodingException e) {
1346 return null; // should never happen
1350 final static String toHex(int n) { return "0x" + Long.toString(n & 0xffffffffL, 16); }
1351 final static int min(int a, int b) { return a < b ? a : b; }
1352 final static int max(int a, int b) { return a > b ? a : b; }