fix sltiu
[nestedvm.git] / src / org / ibex / nestedvm / Runtime.java
1 // Copyright 2003 Brian Alliet
2 // Based on org.xwt.imp.MIPS by Adam Megacz
3 // Portions Copyright 2003 Adam Megacz
4
5 package org.ibex.nestedvm;
6
7 import org.ibex.nestedvm.util.*;
8 import java.io.*;
9 import java.util.Arrays;
10
11 public abstract class Runtime implements UsermodeConstants,Registers,Cloneable {
12     /** True to write useful diagnostic information to stderr when things go wrong */
13     final static boolean STDERR_DIAG = true;
14     
15     /** Number of bits to shift to get the page number (1<<<pageShift == pageSize) */
16     protected final int pageShift;
17     /** Bottom of region of memory allocated to the stack */
18     private final int stackBottom;
19     
20     /** Readable main memory pages */
21     protected int[][] readPages;
22     /** Writable main memory pages.
23         If the page is writable writePages[x] == readPages[x]; if not writePages[x] == null. */
24     protected int[][] writePages;
25     
26     /** The address of the end of the heap */
27     private int heapEnd;
28     
29     /** Number of guard pages to keep between the stack and the heap */
30     private static final int STACK_GUARD_PAGES = 4;
31     
32     /** The last address the executable uses (other than the heap/stack) */
33     protected abstract int heapStart();
34         
35     /** The program's entry point */
36     protected abstract int entryPoint();
37
38     /** The location of the _user_info block (or 0 is there is none) */
39     protected int userInfoBase() { return 0; }
40     protected int userInfoSize() { return 0; }
41     
42     /** The location of the global pointer */
43     protected abstract int gp();
44     
45     /** When the process started */
46     private long startTime;
47     
48     /**  Text/Data loaded in memory  */
49     public final static int STOPPED = 0;
50     /** Program is executing instructions */
51     public final static int RUNNING = 1;
52     /** Prgram has been started but is paused */
53     public final static int PAUSED = 2;
54     /** Program is executing a callJava() method */
55     public final static int CALLJAVA = 3;
56     /** Program has exited (it cannot currently be restarted) */
57     public final static int EXITED = 4;
58     /** Program has executed a successful exec(), a new Runtime needs to be run (used by UnixRuntime) */
59     public final static int EXECED = 5;
60     
61     /** The current state */
62     protected int state = STOPPED;
63     /** @see Runtime#state state */
64     public final int getState() { return state; }
65     
66     /** The exit status if the process (only valid if state==DONE) 
67         @see Runtime#state */
68     private int exitStatus;
69     public ExecutionException exitException;
70     
71     /** Table containing all open file descriptors. (Entries are null if the fd is not in use */
72     FD[] fds = new FD[OPEN_MAX]; // package-private for UnixRuntime
73     boolean closeOnExec[] = new boolean[OPEN_MAX];
74     
75     /** Pointer to a SecurityManager for this process */
76     SecurityManager sm;
77     public void setSecurityManager(SecurityManager sm) { this.sm = sm; }
78     
79     /** Pointer to a callback for the call_java syscall */
80     private CallJavaCB callJavaCB;
81     public void setCallJavaCB(CallJavaCB callJavaCB) { this.callJavaCB = callJavaCB; }
82         
83     /** Temporary buffer for read/write operations */
84     private byte[] _byteBuf;
85     /** Max size of temporary buffer
86         @see Runtime#_byteBuf */
87     final static int MAX_CHUNK = 16*1024*1024 - 1024;
88         
89     /** Subclasses should actually execute program in this method. They should continue 
90         executing until state != RUNNING. Only syscall() can modify state. It is safe 
91         to only check the state attribute after a call to syscall() */
92     protected abstract void _execute() throws ExecutionException;
93     
94     /** Subclasses should return the address of the symbol <i>symbol</i> or -1 it it doesn't exits in this method 
95         This method is only required if the call() function is used */
96     protected int lookupSymbol(String symbol) { return -1; }
97     
98     /** Subclasses should populate a CPUState object representing the cpu state */
99     protected abstract void getCPUState(CPUState state);
100     
101     /** Subclasses should set the CPUState to the state held in <i>state</i> */
102     protected abstract void setCPUState(CPUState state);
103     
104     protected Object clone() throws CloneNotSupportedException {
105         Runtime r = (Runtime) super.clone();
106         r._byteBuf = null;
107         r.startTime = 0;
108         r.fds = new FD[OPEN_MAX];
109         for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) r.fds[i] = fds[i].dup();
110         int totalPages = writePages.length;
111         r.readPages = new int[totalPages][];
112         r.writePages = new int[totalPages][];
113         for(int i=0;i<totalPages;i++) {
114             if(readPages[i] == null) continue;
115             if(writePages[i] == null) r.readPages[i] = readPages[i];
116             else r.readPages[i] = r.writePages[i] = (int[])writePages[i].clone();
117         }
118         return r;
119     }
120     
121     protected Runtime(int pageSize, int totalPages) {
122         if(pageSize <= 0) throw new IllegalArgumentException("pageSize <= 0");
123         if(totalPages <= 0) throw new IllegalArgumentException("totalPages <= 0");
124         if((pageSize&(pageSize-1)) != 0) throw new IllegalArgumentException("pageSize not a power of two");
125
126         int _pageShift = 0;
127         while(pageSize>>>_pageShift != 1) _pageShift++;
128         pageShift = _pageShift;
129         
130         int heapStart = heapStart();
131         int totalMemory = totalPages * pageSize;
132         int stackSize = max(totalMemory/512,ARG_MAX+65536);
133         int stackPages = 0;
134         if(totalPages > 1) {
135             stackSize = max(stackSize,pageSize);
136             stackSize = (stackSize + pageSize - 1) & ~(pageSize-1);
137             stackPages = stackSize >>> pageShift;
138             heapStart = (heapStart + pageSize) & ~(pageSize-1);
139             if(stackPages + STACK_GUARD_PAGES + (heapStart >>> pageShift) >= totalPages)
140                 throw new IllegalArgumentException("total pages too small");
141         } else {
142             if(pageSize < heapStart + stackSize) throw new IllegalArgumentException("total memory too small");
143             heapStart = (heapStart + 4095) & ~4096;
144         }
145         
146         stackBottom = totalMemory - stackSize;
147         heapEnd = heapStart;
148         
149         readPages = new int[totalPages][];
150         writePages = new int[totalPages][];
151         
152         if(totalPages == 1) {
153             readPages[0] = writePages[0] = new int[pageSize>>2];
154         } else {
155             for(int i=(stackBottom >>> pageShift);i<writePages.length;i++) {
156                 readPages[i] = writePages[i] = new int[pageSize>>2];
157             }
158         }
159     
160         addFD(new StdinFD(System.in));
161         addFD(new StdoutFD(System.out));
162         addFD(new StdoutFD(System.err));
163     }
164     
165     /** Copy everything from <i>src</i> to <i>addr</i> initializing uninitialized pages if required. 
166        Newly initalized pages will be marked read-only if <i>ro</i> is set */
167     protected final void initPages(int[] src, int addr, boolean ro) {
168         int pageWords = (1<<pageShift)>>>2;
169         int pageMask = (1<<pageShift) - 1;
170         
171         for(int i=0;i<src.length;) {
172             int page = addr >>> pageShift;
173             int start = (addr&pageMask)>>2;
174             int elements = min(pageWords-start,src.length-i);
175             if(readPages[page]==null) {
176                 initPage(page,ro);
177             } else if(!ro) {
178                 if(writePages[page] == null) writePages[page] = readPages[page];
179             }
180             System.arraycopy(src,i,readPages[page],start,elements);
181             i += elements;
182             addr += elements*4;
183         }
184     }
185     
186     /** Initialize <i>words</i> of pages starting at <i>addr</i> to 0 */
187     protected final void clearPages(int addr, int words) {
188         int pageWords = (1<<pageShift)>>>2;
189         int pageMask = (1<<pageShift) - 1;
190
191         for(int i=0;i<words;) {
192             int page = addr >>> pageShift;
193             int start = (addr&pageMask)>>2;
194             int elements = min(pageWords-start,words-i);
195             if(readPages[page]==null) {
196                 readPages[page] = writePages[page] = new int[pageWords];
197             } else {
198                 if(writePages[page] == null) writePages[page] = readPages[page];
199                 for(int j=start;j<start+elements;j++) writePages[page][j] = 0;
200             }
201             i += elements;
202             addr += elements*4;
203         }
204     }
205     
206     /** Copies <i>length</i> bytes from the processes memory space starting at
207         <i>addr</i> INTO a java byte array <i>a</i> */
208     public final void copyin(int addr, byte[] buf, int count) throws ReadFaultException {
209         int pageWords = (1<<pageShift)>>>2;
210         int pageMask = pageWords - 1;
211
212         int x=0;
213         if(count == 0) return;
214         if((addr&3)!=0) {
215             int word = memRead(addr&~3);
216             switch(addr&3) {
217                 case 1: buf[x++] = (byte)((word>>>16)&0xff); if(--count==0) break;
218                 case 2: buf[x++] = (byte)((word>>> 8)&0xff); if(--count==0) break;
219                 case 3: buf[x++] = (byte)((word>>> 0)&0xff); if(--count==0) break;
220             }
221             addr = (addr&~3)+4;
222         }
223         if((count&~3) != 0) {
224             int c = count>>>2;
225             int a = addr>>>2;
226             while(c != 0) {
227                 int[] page = readPages[a >>> (pageShift-2)];
228                 if(page == null) throw new ReadFaultException(a<<2);
229                 int index = a&pageMask;
230                 int n = min(c,pageWords-index);
231                 for(int i=0;i<n;i++,x+=4) {
232                     int word = page[index+i];
233                     buf[x+0] = (byte)((word>>>24)&0xff); buf[x+1] = (byte)((word>>>16)&0xff);
234                     buf[x+2] = (byte)((word>>> 8)&0xff); buf[x+3] = (byte)((word>>> 0)&0xff);                        
235                 }
236                 a += n; c -=n;
237             }
238             addr = a<<2; count &=3;
239         }
240         if(count != 0) {
241             int word = memRead(addr);
242             switch(count) {
243                 case 3: buf[x+2] = (byte)((word>>>8)&0xff);
244                 case 2: buf[x+1] = (byte)((word>>>16)&0xff);
245                 case 1: buf[x+0] = (byte)((word>>>24)&0xff);
246             }
247         }
248     }
249     
250     /** Copies <i>length</i> bytes OUT OF the java array <i>a</i> into the processes memory
251         space at <i>addr</i> */
252     public final void copyout(byte[] buf, int addr, int count) throws FaultException {
253         int pageWords = (1<<pageShift)>>>2;
254         int pageWordMask = pageWords - 1;
255         
256         int x=0;
257         if(count == 0) return;
258         if((addr&3)!=0) {
259             int word = memRead(addr&~3);
260             switch(addr&3) {
261                 case 1: word = (word&0xff00ffff)|((buf[x++]&0xff)<<16); if(--count==0) break;
262                 case 2: word = (word&0xffff00ff)|((buf[x++]&0xff)<< 8); if(--count==0) break;
263                 case 3: word = (word&0xffffff00)|((buf[x++]&0xff)<< 0); if(--count==0) break;
264             }
265             memWrite(addr&~3,word);
266             addr += x;
267         }
268
269         if((count&~3) != 0) {
270             int c = count>>>2;
271             int a = addr>>>2;
272             while(c != 0) {
273                 int[] page = writePages[a >>> (pageShift-2)];
274                 if(page == null) throw new WriteFaultException(a<<2);
275                 int index = a&pageWordMask;
276                 int n = min(c,pageWords-index);
277                 for(int i=0;i<n;i++,x+=4)
278                     page[index+i] = ((buf[x+0]&0xff)<<24)|((buf[x+1]&0xff)<<16)|((buf[x+2]&0xff)<<8)|((buf[x+3]&0xff)<<0);
279                 a += n; c -=n;
280             }
281             addr = a<<2; count&=3;
282         }
283
284         if(count != 0) {
285             int word = memRead(addr);
286             switch(count) {
287                 case 1: word = (word&0x00ffffff)|((buf[x+0]&0xff)<<24); break;
288                 case 2: word = (word&0x0000ffff)|((buf[x+0]&0xff)<<24)|((buf[x+1]&0xff)<<16); break;
289                 case 3: word = (word&0x000000ff)|((buf[x+0]&0xff)<<24)|((buf[x+1]&0xff)<<16)|((buf[x+2]&0xff)<<8); break;
290             }
291             memWrite(addr,word);
292         }
293     }
294     
295     public final void memcpy(int dst, int src, int count) throws FaultException {
296         int pageWords = (1<<pageShift)>>>2;
297         int pageWordMask = pageWords - 1;
298         if((dst&3) == 0 && (src&3)==0) {
299             if((count&~3) != 0) {
300                 int c = count>>2;
301                 int s = src>>>2;
302                 int d = dst>>>2;
303                 while(c != 0) {
304                     int[] srcPage = readPages[s>>>(pageShift-2)];
305                     if(srcPage == null) throw new ReadFaultException(s<<2);
306                     int[] dstPage = writePages[d>>>(pageShift-2)];
307                     if(dstPage == null) throw new WriteFaultException(d<<2);
308                     int srcIndex = s&pageWordMask;
309                     int dstIndex = d&pageWordMask;
310                     int n = min(c,pageWords-max(srcIndex,dstIndex));
311                     System.arraycopy(srcPage,srcIndex,dstPage,dstIndex,n);
312                     s += n; d += n; c -= n;
313                 }
314                 src = s<<2; dst = d<<2; count&=3;
315             }
316             if(count != 0) {
317                 int word1 = memRead(src);
318                 int word2 = memRead(dst);
319                 switch(count) {
320                     case 1: memWrite(dst,(word1&0xff000000)|(word2&0x00ffffff)); break;
321                     case 2: memWrite(dst,(word1&0xffff0000)|(word2&0x0000ffff)); break;
322                     case 3: memWrite(dst,(word1&0xffffff00)|(word2&0x000000ff)); break;
323                 }
324             }
325         } else {
326             while(count > 0) {
327                 int n = min(count,MAX_CHUNK);
328                 byte[] buf = byteBuf(n);
329                 copyin(src,buf,n);
330                 copyout(buf,dst,n);
331                 count -= n; src += n; dst += n;
332             }
333         }
334     }
335     
336     public final void memset(int addr, int ch, int count) throws FaultException {
337         int pageWords = (1<<pageShift)>>>2;
338         int pageWordMask = pageWords - 1;
339         
340         int fourBytes = ((ch&0xff)<<24)|((ch&0xff)<<16)|((ch&0xff)<<8)|((ch&0xff)<<0);
341         if((addr&3)!=0) {
342             int word = memRead(addr&~3);
343             switch(addr&3) {
344                 case 1: word = (word&0xff00ffff)|((ch&0xff)<<16); if(--count==0) break;
345                 case 2: word = (word&0xffff00ff)|((ch&0xff)<< 8); if(--count==0) break;
346                 case 3: word = (word&0xffffff00)|((ch&0xff)<< 0); if(--count==0) break;
347             }
348             memWrite(addr&~3,word);
349             addr = (addr&~3)+4;
350         }
351         if((count&~3) != 0) {
352             int c = count>>2;
353             int a = addr>>>2;
354             while(c != 0) {
355                 int[] page = readPages[a>>>(pageShift-2)];
356                 if(page == null) throw new WriteFaultException(a<<2);
357                 int index = a&pageWordMask;
358                 int n = min(c,pageWords-index);
359                 Arrays.fill(page,index,index+n,fourBytes);
360                 a += n; c -= n;
361             }
362             addr = a<<2; count&=3;
363         }
364         if(count != 0) {
365             int word = memRead(addr);
366             switch(count) {
367                 case 1: word = (word&0x00ffffff)|(fourBytes&0xff000000); break;
368                 case 2: word = (word&0x0000ffff)|(fourBytes&0xffff0000); break;
369                 case 3: word = (word&0x000000ff)|(fourBytes&0xffffff00); break;
370             }
371             memWrite(addr,word);
372         }
373     }
374     
375     /** Read a word from the processes memory at <i>addr</i> */
376     public final int memRead(int addr) throws ReadFaultException  {
377         if((addr & 3) != 0) throw new ReadFaultException(addr);
378         return unsafeMemRead(addr);
379     }
380        
381     protected final int unsafeMemRead(int addr) throws ReadFaultException {
382         int page = addr >>> pageShift;
383         int entry = (addr&(1<<pageShift) - 1)>>2;
384         try {
385             return readPages[page][entry];
386         } catch(ArrayIndexOutOfBoundsException e) {
387             if(page < 0 || page >= readPages.length) throw new ReadFaultException(addr);
388             throw e; // should never happen
389         } catch(NullPointerException e) {
390             throw new ReadFaultException(addr);
391         }
392     }
393     
394     /** Writes a word to the processes memory at <i>addr</i> */
395     public final void memWrite(int addr, int value) throws WriteFaultException  {
396         if((addr & 3) != 0) throw new WriteFaultException(addr);
397         unsafeMemWrite(addr,value);
398     }
399     
400     protected final void unsafeMemWrite(int addr, int value) throws WriteFaultException {
401         int page = addr >>> pageShift;
402         int entry = (addr&(1<<pageShift) - 1)>>2;
403         try {
404             writePages[page][entry] = value;
405         } catch(ArrayIndexOutOfBoundsException e) {
406             if(page < 0 || page >= writePages.length) throw new WriteFaultException(addr);
407             throw e; // should never happen
408         } catch(NullPointerException e) {
409             throw new WriteFaultException(addr);
410         }
411     }
412     
413     /** Created a new non-empty writable page at page number <i>page</i> */
414     private final int[] initPage(int page) { return initPage(page,false); }
415     /** Created a new non-empty page at page number <i>page</i>. If <i>ro</i> is set the page will be read-only */
416     private final int[] initPage(int page, boolean ro) {
417         int[] buf = new int[(1<<pageShift)>>>2];
418         writePages[page] = ro ? null : buf;
419         readPages[page] = buf;
420         return buf;
421     }
422     
423     /** Returns the exit status of the process. (only valid if state == DONE) 
424         @see Runtime#state */
425     public final int exitStatus() {
426         if(state != EXITED) throw new IllegalStateException("exitStatus() called in an inappropriate state");
427         return exitStatus;
428     }
429         
430     private int addStringArray(String[] strings, int topAddr) throws FaultException {
431         int count = strings.length;
432         int total = 0; /* null last table entry  */
433         for(int i=0;i<count;i++) total += strings[i].length() + 1;
434         total += (count+1)*4;
435         int start = (topAddr - total)&~3;
436         int addr = start + (count+1)*4;
437         int[] table = new int[count+1];
438         try {
439             for(int i=0;i<count;i++) {
440                 byte[] a = getBytes(strings[i]);
441                 table[i] = addr;
442                 copyout(a,addr,a.length);
443                 memset(addr+a.length,0,1);
444                 addr += a.length + 1;
445             }
446             addr=start;
447             for(int i=0;i<count+1;i++) {
448                 memWrite(addr,table[i]);
449                 addr += 4;
450             }
451         } catch(FaultException e) {
452             throw new RuntimeException(e.toString());
453         }
454         return start;
455     }
456     
457     String[] createEnv(String[] extra) { if(extra == null) extra = new String[0]; return extra; }
458     
459     /** Sets word number <i>index</i> in the _user_info table to <i>word</i>
460      * The user_info table is a chunk of memory in the program's memory defined by the
461      * symbol "user_info". The compiler/interpreter automatically determine the size
462      * and location of the user_info table from the ELF symbol table. setUserInfo and
463      * getUserInfo are used to modify the words in the user_info table. */
464     public void setUserInfo(int index, int word) {
465         if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
466         try {
467             memWrite(userInfoBase()+index*4,word);
468         } catch(FaultException e) { throw new RuntimeException(e.toString()); }
469     }
470     
471     /** Returns the word in the _user_info table entry <i>index</i>
472         @see Runtime#setUserInfo(int,int) setUserInfo */
473     public int getUserInfo(int index) {
474         if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
475         try {
476             return memRead(userInfoBase()+index*4);
477         } catch(FaultException e) { throw new RuntimeException(e.toString()); }
478     }
479     
480     /** Calls _execute() (subclass's execute()) and catches exceptions */
481     // FEATURE: Have these call kill() so we get a pretty message to stdout
482     private void __execute() {
483         try {
484             _execute();
485         } catch(FaultException e) {
486             if(STDERR_DIAG) e.printStackTrace();
487             sys_exit(128+11); // SIGSEGV
488             exitException = e;
489         } catch(ExecutionException e) {
490             if(STDERR_DIAG) e.printStackTrace();
491             sys_exit(128+4); // SIGILL
492             exitException = e;
493         }
494     }
495     
496     /** Executes the process until the PAUSE syscall is invoked or the process exits. Returns true if the process exited. */
497     public final boolean execute()  {
498         if(state != PAUSED) throw new IllegalStateException("execute() called in inappropriate state");
499         if(startTime == 0) startTime = System.currentTimeMillis();
500         state = RUNNING;
501         __execute();
502         if(state != PAUSED && state != EXITED && state != EXECED)
503             throw new IllegalStateException("execute() ended up in an inappropriate state (" + state + ")");
504         return state != PAUSED;
505     }
506     
507     static String[] concatArgv(String argv0, String[] rest) {
508         String[] argv = new String[rest.length+1];
509         System.arraycopy(rest,0,argv,1,rest.length);
510         argv[0] = argv0;
511         return argv;
512     }
513     
514     public final int run() { return run(null); }
515     public final int run(String argv0, String[] rest) { return run(concatArgv(argv0,rest)); }
516     public final int run(String[] args) { return run(args,null); }
517     
518     /** Runs the process until it exits and returns the exit status.
519         If the process executes the PAUSE syscall execution will be paused for 500ms and a warning will be displayed */
520     public final int run(String[] args, String[] env) {
521         start(args,env);
522         for(;;) {
523             if(execute()) break;
524             if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing run()");
525         }
526         if(state == EXECED && STDERR_DIAG) System.err.println("WARNING: Process exec()ed while being run under run()");
527         return state == EXITED ? exitStatus() : 0;
528     }
529
530     public final void start() { start(null); }
531     public final void start(String[] args) { start(args,null); }
532     
533     /** Initializes the process and prepairs it to be executed with execute() */
534     public final void start(String[] args, String[] environ)  {
535         int top, sp, argsAddr, envAddr;
536         if(state != STOPPED) throw new IllegalStateException("start() called in inappropriate state");
537
538         if(args == null) args = new String[]{getClass().getName()};
539         
540         sp = top = writePages.length*(1<<pageShift);
541         try {
542             sp = argsAddr = addStringArray(args,sp);
543             sp = envAddr = addStringArray(createEnv(environ),sp);
544         } catch(FaultException e) {
545             throw new IllegalArgumentException("args/environ too big");
546         }
547         sp &= ~15;
548         if(top - sp > ARG_MAX) throw new IllegalArgumentException("args/environ too big");
549
550         CPUState cpuState = new CPUState();
551         cpuState.r[A0] = argsAddr;
552         cpuState.r[A1] = envAddr;
553         cpuState.r[SP] = sp;
554         cpuState.r[RA] = 0xdeadbeef;
555         cpuState.r[GP] = gp();
556         cpuState.pc = entryPoint();
557         setCPUState(cpuState);
558         
559         state = PAUSED;
560         
561         _started();        
562     }
563     
564     /** Hook for subclasses to do their own startup */
565     void _started() {  }
566     
567     public final int call(String sym, Object[] args) throws CallException, FaultException {
568         if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
569         if(args.length > 7) throw new IllegalArgumentException("args.length > 7");
570         CPUState state = new CPUState();
571         getCPUState(state);
572         
573         int sp = state.r[SP];
574         int[] ia = new int[args.length];
575         for(int i=0;i<args.length;i++) {
576             Object o = args[i];
577             byte[] buf = null;
578             if(o instanceof String) {
579                 buf = getBytes((String)o);
580             } else if(o instanceof byte[]) {
581                 buf = (byte[]) o;
582             } else if(o instanceof Number) {
583                 ia[i] = ((Number)o).intValue();
584             }
585             if(buf != null) {
586                 sp -= buf.length;
587                 copyout(buf,sp,buf.length);
588                 ia[i] = sp;
589             }
590         }
591         int oldSP = state.r[SP];
592         if(oldSP == sp) return call(sym,ia);
593         
594         state.r[SP] = sp;
595         setCPUState(state);
596         int ret = call(sym,ia);
597         state.r[SP] = oldSP;
598         setCPUState(state);
599         return ret;
600     }
601     
602     public final int call(String sym) throws CallException { return call(sym,new int[]{}); }
603     public final int call(String sym, int a0) throws CallException  { return call(sym,new int[]{a0}); }
604     public final int call(String sym, int a0, int a1) throws CallException  { return call(sym,new int[]{a0,a1}); }
605     
606     /** Calls a function in the process with the given arguments */
607     public final int call(String sym, int[] args) throws CallException {
608         int func = lookupSymbol(sym);
609         if(func == -1) throw new CallException(sym + " not found");
610         int helper = lookupSymbol("_call_helper");
611         if(helper == -1) throw new CallException("_call_helper not found");
612         return call(helper,func,args);
613     }
614     
615     /** Executes the code at <i>addr</i> in the process setting A0-A3 and S0-S3 to the given arguments
616         and returns the contents of V1 when the the pause syscall is invoked */
617     //public final int call(int addr, int a0, int a1, int a2, int a3, int s0, int s1, int s2, int s3) {
618     public final int call(int addr, int a0, int[] rest) throws CallException {
619         if(rest.length > 7) throw new IllegalArgumentException("rest.length > 7");
620         if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
621         int oldState = state;
622         CPUState saved = new CPUState();        
623         getCPUState(saved);
624         CPUState cpustate = saved.dup();
625         
626         cpustate.r[SP] = cpustate.r[SP]&~15;
627         cpustate.r[RA] = 0xdeadbeef;
628         cpustate.r[A0] = a0;
629         switch(rest.length) {            
630             case 7: cpustate.r[S3] = rest[6];
631             case 6: cpustate.r[S2] = rest[5];
632             case 5: cpustate.r[S1] = rest[4];
633             case 4: cpustate.r[S0] = rest[3];
634             case 3: cpustate.r[A3] = rest[2];
635             case 2: cpustate.r[A2] = rest[1];
636             case 1: cpustate.r[A1] = rest[0];
637         }
638         cpustate.pc = addr;
639         
640         state = RUNNING;
641
642         setCPUState(cpustate);
643         __execute();
644         getCPUState(cpustate);
645         setCPUState(saved);
646
647         if(state != PAUSED) throw new CallException("Process exit()ed while servicing a call() request");
648         state = oldState;
649         
650         return cpustate.r[V1];
651     }
652         
653     /** Allocated an entry in the FileDescriptor table for <i>fd</i> and returns the number.
654         Returns -1 if the table is full. This can be used by subclasses to use custom file
655         descriptors */
656     public final int addFD(FD fd) {
657         if(state == EXITED || state == EXECED) throw new IllegalStateException("addFD called in inappropriate state");
658         int i;
659         for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
660         if(i==OPEN_MAX) return -1;
661         fds[i] = fd;
662         closeOnExec[i] = false;
663         return i;
664     }
665
666     /** Closes file descriptor <i>fdn</i> and removes it from the file descriptor table */
667     public final boolean closeFD(int fdn) {
668         if(state == EXITED || state == EXECED) throw new IllegalStateException("closeFD called in inappropriate state");
669         if(fdn < 0 || fdn >= OPEN_MAX) return false;
670         if(fds[fdn] == null) return false;
671         fds[fdn].close();
672         fds[fdn] = null;        
673         return true;
674     }
675     
676     /** Duplicates the file descriptor <i>fdn</i> and returns the new fs */
677     public final int dupFD(int fdn) {
678         int i;
679         if(fdn < 0 || fdn >= OPEN_MAX) return -1;
680         if(fds[fdn] == null) return -1;
681         for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
682         if(i==OPEN_MAX) return -1;
683         fds[i] = fds[fdn].dup();
684         return i;
685     }
686
687     public static final int RD_ONLY = 0;
688     public static final int WR_ONLY = 1;
689     public static final int RDWR = 2;
690     
691     public static final int O_CREAT = 0x0200;
692     public static final int O_EXCL = 0x0800;
693     public static final int O_APPEND = 0x0008;
694     public static final int O_TRUNC = 0x0400;
695     public static final int O_NONBLOCK = 0x4000;
696     public static final int O_NOCTTY = 0x8000;
697     
698     
699     FD hostFSOpen(final File f, int flags, int mode, final Object data) throws ErrnoException {
700         if((flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)) != 0) {
701             if(STDERR_DIAG)
702                 System.err.println("WARNING: Unsupported flags passed to open(\"" + f + "\"): " + toHex(flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)));
703            
704             throw new ErrnoException(ENOTSUP);
705         }
706         boolean write = (flags&3) != RD_ONLY;
707
708         if(sm != null && !(write ? sm.allowWrite(f) : sm.allowRead(f))) throw new ErrnoException(EACCES);
709         
710         if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT)) {
711             try {
712                 // NOTE: createNewFile is a Java2 function
713                 if(!f.createNewFile()) throw new ErrnoException(EEXIST);
714             } catch(IOException e) {
715                 throw new ErrnoException(EIO);
716             }
717         } else if(!f.exists()) {
718             if((flags&O_CREAT)==0) return null;
719         } else if(f.isDirectory()) {
720             return hostFSDirFD(f,data);
721         }
722         
723         final Seekable.File sf;
724         try {
725             sf = new Seekable.File(f,write);
726         } catch(FileNotFoundException e) {
727             if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) throw new ErrnoException(EACCES);
728             return null;
729         } catch(IOException e) { throw new ErrnoException(EIO); }
730         
731         return new SeekableFD(sf,flags) { protected FStat _fstat() { return hostFStat(f,data); } };
732     }
733     
734     FStat hostFStat(File f, Object data) { return new HostFStat(f); }
735     
736     FD hostFSDirFD(File f, Object data) { return null; }
737     
738     FD _open(String path, int flags, int mode) throws ErrnoException {
739         return hostFSOpen(new File(path),flags,mode,null);
740     }
741     
742     /** The open syscall */
743     private int sys_open(int addr, int flags, int mode) throws ErrnoException, FaultException {
744         flags &= ~O_NOCTTY; // this is meaningless under nestedvm
745         FD fd = _open(cstring(addr),flags,mode);
746         if(fd == null) return -ENOENT;
747         int fdn = addFD(fd);
748         if(fdn == -1) { fd.close(); return -ENFILE; }
749         return fdn;
750     }
751
752     /** The write syscall */
753     
754     private int sys_write(int fdn, int addr, int count) throws FaultException, ErrnoException {
755         count = Math.min(count,MAX_CHUNK);
756         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
757         if(fds[fdn] == null) return -EBADFD;
758         byte[] buf = byteBuf(count);
759         copyin(addr,buf,count);
760         try {
761             return fds[fdn].write(buf,0,count);
762         } catch(ErrnoException e) {
763             if(e.errno == EPIPE) sys_exit(128+13);
764             throw e;
765         }
766     }
767
768     /** The read syscall */
769     private int sys_read(int fdn, int addr, int count) throws FaultException, ErrnoException {
770         count = Math.min(count,MAX_CHUNK);
771         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
772         if(fds[fdn] == null) return -EBADFD;
773         byte[] buf = byteBuf(count);
774         int n = fds[fdn].read(buf,0,count);
775         copyout(buf,addr,n);
776         return n;
777     }
778     
779     /** The close syscall */
780     private int sys_close(int fdn) {
781         return closeFD(fdn) ? 0 : -EBADFD;
782     }
783
784     
785     /** The seek syscall */
786     private int sys_lseek(int fdn, int offset, int whence) throws ErrnoException {
787         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
788         if(fds[fdn] == null) return -EBADFD;
789         if(whence != SEEK_SET && whence !=  SEEK_CUR && whence !=  SEEK_END) return -EINVAL;
790         int n = fds[fdn].seek(offset,whence);
791         return n < 0 ? -ESPIPE : n;
792     }
793     
794     /** The stat/fstat syscall helper */
795     int stat(FStat fs, int addr) throws FaultException {
796         memWrite(addr+0,(fs.dev()<<16)|(fs.inode()&0xffff)); // st_dev (top 16), // st_ino (bottom 16)
797         memWrite(addr+4,((fs.type()&0xf000))|(fs.mode()&0xfff)); // st_mode
798         memWrite(addr+8,1<<16); // st_nlink (top 16) // st_uid (bottom 16)
799         memWrite(addr+12,0); // st_gid (top 16) // st_rdev (bottom 16)
800         memWrite(addr+16,fs.size()); // st_size
801         memWrite(addr+20,fs.atime()); // st_atime
802         // memWrite(addr+24,0) // st_spare1
803         memWrite(addr+28,fs.mtime()); // st_mtime
804         // memWrite(addr+32,0) // st_spare2
805         memWrite(addr+36,fs.ctime()); // st_ctime
806         // memWrite(addr+40,0) // st_spare3
807         memWrite(addr+44,fs.blksize()); // st_bklsize;
808         memWrite(addr+48,fs.blocks()); // st_blocks
809         // memWrite(addr+52,0) // st_spare4[0]
810         // memWrite(addr+56,0) // st_spare4[1]
811         return 0;
812     }
813     
814     /** The fstat syscall */
815     private int sys_fstat(int fdn, int addr) throws FaultException {
816         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
817         if(fds[fdn] == null) return -EBADFD;
818         return stat(fds[fdn].fstat(),addr);
819     }
820     
821     /*
822     struct timeval {
823     long tv_sec;
824     long tv_usec;
825     };
826     */
827     private int sys_gettimeofday(int timevalAddr, int timezoneAddr) throws FaultException {
828         long now = System.currentTimeMillis();
829         int tv_sec = (int)(now / 1000);
830         int tv_usec = (int)((now%1000)*1000);
831         memWrite(timevalAddr+0,tv_sec);
832         memWrite(timevalAddr+4,tv_usec);
833         return 0;
834     }
835     
836     private int sys_sleep(int sec) {
837         if(sec < 0) sec = Integer.MAX_VALUE;
838         try {
839             Thread.sleep((long)sec*1000);
840             return 0;
841         } catch(InterruptedException e) {
842             return -1;
843         }
844     }
845     
846     /*
847       #define _CLOCKS_PER_SEC_ 1000
848       #define    _CLOCK_T_    unsigned long
849     struct tms {
850       clock_t   tms_utime;
851       clock_t   tms_stime;
852       clock_t   tms_cutime;    
853       clock_t   tms_cstime;
854     };*/
855    
856     private int sys_times(int tms) {
857         long now = System.currentTimeMillis();
858         int userTime = (int)((now - startTime)/16);
859         int sysTime = (int)((now - startTime)/16);
860         
861         try {
862             if(tms!=0) {
863                 memWrite(tms+0,userTime);
864                 memWrite(tms+4,sysTime);
865                 memWrite(tms+8,userTime);
866                 memWrite(tms+12,sysTime);
867             }
868         } catch(FaultException e) {
869             return -EFAULT;
870         }
871         return (int)now;
872     }
873     
874     private int sys_sysconf(int n) {
875         switch(n) {
876             case _SC_CLK_TCK: return 1000;
877             case _SC_PAGESIZE: return  writePages.length == 1 ? 4096 : (1<<pageShift);
878             case _SC_PHYS_PAGES: return writePages.length == 1 ? (1<<pageShift)/4096 : writePages.length;
879             default:
880                 if(STDERR_DIAG) System.err.println("WARNING: Attempted to use unknown sysconf key: " + n);
881                 return -EINVAL;
882         }
883     }
884     
885     /** The sbrk syscall. This can also be used by subclasses to allocate memory.
886         <i>incr</i> is how much to increase the break by */
887     public final int sbrk(int incr) {
888         if(incr < 0) return -ENOMEM;
889         if(incr==0) return heapEnd;
890         incr = (incr+3)&~3;
891         int oldEnd = heapEnd;
892         int newEnd = oldEnd + incr;
893         if(newEnd >= stackBottom) return -ENOMEM;
894         
895         if(writePages.length > 1) {
896             int pageMask = (1<<pageShift) - 1;
897             int pageWords = (1<<pageShift) >>> 2;
898             int start = (oldEnd + pageMask) >>> pageShift;
899             int end = (newEnd + pageMask) >>> pageShift;
900             try {
901                 for(int i=start;i<end;i++) readPages[i] = writePages[i] = new int[pageWords];
902             } catch(OutOfMemoryError e) {
903                 if(STDERR_DIAG) System.err.println("WARNING: Caught OOM Exception in sbrk: " + e);
904                 return -ENOMEM;
905             }
906         }
907         heapEnd = newEnd;
908         return oldEnd;
909     }
910
911     /** The getpid syscall */
912     private int sys_getpid() { return getPid(); }
913     int getPid() { return 1; }
914     
915     public static interface CallJavaCB { public int call(int a, int b, int c, int d); }
916     
917     private int sys_calljava(int a, int b, int c, int d) {
918         if(state != RUNNING) throw new IllegalStateException("wound up calling sys_calljava while not in RUNNING");
919         if(callJavaCB != null) {
920             state = CALLJAVA;
921             int ret;
922             try {
923                 ret = callJavaCB.call(a,b,c,d);
924             } catch(RuntimeException e) {
925                 System.err.println("Error while executing callJavaCB");
926                     e.printStackTrace();
927                 ret = 0;
928             }
929             state = RUNNING;
930             return ret;
931         } else {
932             if(STDERR_DIAG) System.err.println("WARNING: calljava syscall invoked without a calljava callback set");
933             return 0;
934         }
935     }
936         
937     private int sys_pause() {
938         state = PAUSED;
939         return 0;
940     }
941     
942     private int sys_getpagesize() { return writePages.length == 1 ? 4096 : (1<<pageShift); }
943     
944     /** Hook for subclasses to do something when the process exits  */
945     void _exited() {  }
946     
947     private int sys_exit(int status) {
948         exitStatus = status;
949         for(int i=0;i<fds.length;i++) if(fds[i] != null) closeFD(i);
950         state = EXITED;
951         _exited();
952         return 0;
953     }
954        
955     private int sys_fcntl(int fdn, int cmd, int arg) {
956         int i;
957             
958         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
959         if(fds[fdn] == null) return -EBADFD;
960         FD fd = fds[fdn];
961         
962         switch(cmd) {
963             case F_DUPFD:
964                 if(arg < 0 || arg >= OPEN_MAX) return -EINVAL;
965                 for(i=arg;i<OPEN_MAX;i++) if(fds[i]==null) break;
966                 if(i==OPEN_MAX) return -EMFILE;
967                 fds[i] = fd.dup();
968                 return 0;
969             case F_GETFL:
970                 return fd.flags();
971             case F_SETFD:
972                 closeOnExec[fdn] = arg != 0;
973                 return 0;
974             case F_GETFD:
975                 return closeOnExec[fdn] ? 1 : 0;
976             default:
977                 if(STDERR_DIAG) System.err.println("WARNING: Unknown fcntl command: " + cmd);
978                 return -ENOSYS;
979         }
980     }
981             
982     /** The syscall dispatcher.
983         The should be called by subclasses when the syscall instruction is invoked.
984         <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 
985         the contenst of A0, A1, A2, and A3. The call MAY change the state
986         @see Runtime#state state */
987     protected final int syscall(int syscall, int a, int b, int c, int d) {
988         try {
989             return _syscall(syscall,a,b,c,d);
990         } catch(ErrnoException e) {
991             return -e.errno;
992         } catch(FaultException e) {
993             return -EFAULT;
994         } catch(RuntimeException e) {
995             e.printStackTrace();
996             throw new Error("Internal Error in _syscall()");
997         }
998     }
999     
1000     int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
1001         switch(syscall) {
1002             case SYS_null: return 0;
1003             case SYS_exit: return sys_exit(a);
1004             case SYS_pause: return sys_pause();
1005             case SYS_write: return sys_write(a,b,c);
1006             case SYS_fstat: return sys_fstat(a,b);
1007             case SYS_sbrk: return sbrk(a);
1008             case SYS_open: return sys_open(a,b,c);
1009             case SYS_close: return sys_close(a);
1010             case SYS_read: return sys_read(a,b,c);
1011             case SYS_lseek: return sys_lseek(a,b,c);
1012             case SYS_getpid: return sys_getpid();
1013             case SYS_calljava: return sys_calljava(a,b,c,d);
1014             case SYS_gettimeofday: return sys_gettimeofday(a,b);
1015             case SYS_sleep: return sys_sleep(a);
1016             case SYS_times: return sys_times(a);
1017             case SYS_getpagesize: return sys_getpagesize();
1018             case SYS_fcntl: return sys_fcntl(a,b,c);
1019             case SYS_sysconf: return sys_sysconf(a);
1020             
1021             case SYS_memcpy: memcpy(a,b,c); return a;
1022             case SYS_memset: memset(a,b,c); return a;
1023
1024             case SYS_kill:
1025             case SYS_fork:
1026             case SYS_pipe:
1027             case SYS_dup2:
1028             case SYS_waitpid:
1029             case SYS_stat:
1030             case SYS_mkdir:
1031             case SYS_getcwd:
1032             case SYS_chdir:
1033                 if(STDERR_DIAG) System.err.println("Attempted to use a UnixRuntime syscall in Runtime (" + syscall + ")");
1034                 return -ENOSYS;
1035             default:
1036                 if(STDERR_DIAG) System.err.println("Attempted to use unknown syscall: " + syscall);
1037                 return -ENOSYS;
1038         }
1039     }
1040     
1041     public int xmalloc(int size) { int p=malloc(size); if(p==0) throw new RuntimeException("malloc() failed"); return p; }
1042     public int xrealloc(int addr,int newsize) { int p=realloc(addr,newsize); if(p==0) throw new RuntimeException("realloc() failed"); return p; }
1043     public int realloc(int addr, int newsize) { try { return call("realloc",addr,newsize); } catch(CallException e) { return 0; } }
1044     public int malloc(int size) { try { return call("malloc",size); } catch(CallException e) { return 0; } }
1045     public void free(int p) { try { if(p!=0) call("free",p); } catch(CallException e) { /*noop*/ } }
1046     
1047     /** Helper function to create a cstring in main memory */
1048     public int strdup(String s) {
1049         byte[] a;
1050         if(s == null) s = "(null)";
1051         byte[] a2 = getBytes(s);
1052         a = new byte[a2.length+1];
1053         System.arraycopy(a2,0,a,0,a2.length);
1054         int addr = malloc(a.length);
1055         if(addr == 0) return 0;
1056         try {
1057             copyout(a,addr,a.length);
1058         } catch(FaultException e) {
1059             free(addr);
1060             return 0;
1061         }
1062         return addr;
1063     }
1064     
1065     /** Helper function to read a cstring from main memory */
1066     public final String cstring(int addr) throws ReadFaultException {
1067         StringBuffer sb = new StringBuffer();
1068         for(;;) {
1069             int word = memRead(addr&~3);
1070             switch(addr&3) {
1071                 case 0: if(((word>>>24)&0xff)==0) return sb.toString(); sb.append((char)((word>>>24)&0xff)); addr++;
1072                 case 1: if(((word>>>16)&0xff)==0) return sb.toString(); sb.append((char)((word>>>16)&0xff)); addr++;
1073                 case 2: if(((word>>> 8)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 8)&0xff)); addr++;
1074                 case 3: if(((word>>> 0)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 0)&0xff)); addr++;
1075             }
1076         }
1077     }
1078     
1079     /** File Descriptor class */
1080     public static abstract class FD {
1081         private int refCount = 1;
1082         
1083         /** Read some bytes. Should return the number of bytes read, 0 on EOF, or throw an IOException on error */
1084         public int read(byte[] a, int off, int length) throws ErrnoException { throw new ErrnoException(EBADFD); }
1085         /** Write. Should return the number of bytes written or throw an IOException on error */
1086         public int write(byte[] a, int off, int length) throws ErrnoException { throw new ErrnoException(EBADFD); }
1087
1088         /** Seek in the filedescriptor. Whence is SEEK_SET, SEEK_CUR, or SEEK_END. Should return -1 on error or the new position. */
1089         public int seek(int n, int whence)  throws ErrnoException  { return -1; }
1090         
1091         public int getdents(byte[] a, int off, int length) throws ErrnoException { throw new ErrnoException(EBADFD); }
1092         
1093         public int flags() { return O_RDONLY; }
1094         
1095         /** Return a Seekable object representing this file descriptor (can be read only) 
1096             This is required for exec() */
1097         Seekable seekable() { return null; }
1098         
1099         private FStat cachedFStat = null;
1100         public final FStat fstat() {
1101             if(cachedFStat == null) cachedFStat = _fstat(); 
1102             return cachedFStat;
1103         }
1104         
1105         protected abstract FStat _fstat();
1106         
1107         /** Closes the fd */
1108         public final void close() { if(--refCount==0) _close(); }
1109         protected void _close() { /* noop*/ }
1110         
1111         FD dup() { refCount++; return this; }
1112     }
1113         
1114     /** FileDescriptor class for normal files */
1115     public abstract static class SeekableFD extends FD {
1116         private final int flags;
1117         private final Seekable data;
1118         
1119         SeekableFD(Seekable data, int flags) { this.data = data; this.flags = flags; }
1120         
1121         protected abstract FStat _fstat();
1122         public int flags() { return flags; }
1123
1124         Seekable seekable() { return data; }
1125         
1126         public int seek(int n, int whence) throws ErrnoException {
1127             try {
1128                 switch(whence) {
1129                         case SEEK_SET: break;
1130                         case SEEK_CUR: n += data.pos(); break;
1131                         case SEEK_END: n += data.length(); break;
1132                         default: return -1;
1133                 }
1134                 data.seek(n);
1135                 return n;
1136             } catch(IOException e) {
1137                 throw new ErrnoException(ESPIPE);
1138             }
1139         }
1140         
1141         public int write(byte[] a, int off, int length) throws ErrnoException {
1142             if((flags&3) == RD_ONLY) throw new ErrnoException(EBADFD);
1143             // NOTE: There is race condition here but we can't fix it in pure java
1144             if((flags&O_APPEND) != 0) seek(0,SEEK_END);
1145             try {
1146                 return data.write(a,off,length);
1147             } catch(IOException e) {
1148                 throw new ErrnoException(EIO);
1149             }
1150         }
1151         
1152         public int read(byte[] a, int off, int length) throws ErrnoException {
1153             if((flags&3) == WR_ONLY) throw new ErrnoException(EBADFD);
1154             try {
1155                 int n = data.read(a,off,length);
1156                 return n < 0 ? 0 : n;
1157             } catch(IOException e) {
1158                 throw new ErrnoException(EIO);
1159             }
1160         }
1161         
1162         protected void _close() { try { data.close(); } catch(IOException e) { /*ignore*/ } }        
1163     }
1164     
1165     public static class OutputStreamFD extends FD {
1166         private OutputStream os;
1167         public int flags() { return O_WRONLY; }
1168         public OutputStreamFD(OutputStream os) { this.os = os; }
1169         public int write(byte[] a, int off, int length) throws ErrnoException {
1170             try {
1171                 os.write(a,off,length);
1172                 return length;
1173             } catch(IOException e) {
1174                 throw new ErrnoException(EIO);
1175             }
1176         }
1177         public void _close() { try { os.close(); } catch(IOException e) { /*ignore*/ }  }
1178         public FStat _fstat() { return new FStat(); }
1179     }
1180     
1181     public static class InputStreamFD extends FD {
1182         private InputStream is;
1183         public int flags() { return O_RDONLY; }
1184         public InputStreamFD(InputStream is) { this.is = is; }
1185         public int read(byte[] a, int off, int length) throws ErrnoException {
1186             try {
1187                 int n = is.read(a,off,length);
1188                 return n < 0 ? 0 : n;
1189             } catch(IOException e) {
1190                 throw new ErrnoException(EIO);
1191             }
1192         }
1193         public void _close() { try { is.close(); } catch(IOException e) { /*ignore*/ } }
1194         public FStat _fstat() { return new FStat(); }
1195     }
1196     
1197     static class StdinFD extends InputStreamFD {
1198         public StdinFD(InputStream is) { super(is); }
1199         public void _close() { /* noop */ }
1200         public FStat _fstat() { return new FStat() { public int type() { return S_IFCHR; } }; }
1201     }
1202     
1203     static class StdoutFD extends OutputStreamFD {
1204         public StdoutFD(OutputStream os) { super(os); }
1205         public void _close() { /* noop */ }
1206         public FStat _fstat() { return new FStat() { public int type() { return S_IFCHR; } }; }
1207     }
1208     
1209     public static class FStat {
1210         public static final int S_IFIFO = 0010000;
1211         public static final int S_IFCHR = 0020000;
1212         public static final int S_IFDIR = 0040000;
1213         public static final int S_IFREG = 0100000;
1214         
1215         public int dev() { return 1; }
1216         public int inode() { return hashCode() & 0x7fff; }
1217         public int mode() { return 0; }
1218         public int type() { return S_IFIFO; }
1219         public int nlink() { return 0; }
1220         public int uid() { return 0; }
1221         public int gid() { return 0; }
1222         public int size() { return 0; }
1223         public int atime() { return 0; }
1224         public int mtime() { return 0; }
1225         public int ctime() { return 0; }
1226         public int blksize() { return 512; }
1227         public int blocks() { return (size()+blksize()-1)/blksize(); }        
1228     }
1229     
1230     static class HostFStat extends FStat {
1231         private final File f;
1232         private final boolean executable; 
1233         public HostFStat(File f) { this(f,false); }
1234         public HostFStat(File f, boolean executable) {
1235             this.f = f;
1236             this.executable = executable;
1237         }
1238         public int dev() { return 1; }
1239         public int inode() { return f.getName().hashCode() & 0xffff; }
1240         public int type() { return f.isDirectory() ? S_IFDIR : S_IFREG; }
1241         public int nlink() { return 1; }
1242         public int mode() {
1243             int mode = 0;
1244             boolean canread = f.canRead();
1245             if(canread && (executable || f.isDirectory())) mode |= 0111;
1246             if(canread) mode |= 0444;
1247             if(f.canWrite()) mode |= 0222;
1248             return mode;
1249         }
1250         public int size() { return (int) f.length(); }
1251         public int mtime() { return (int)(f.lastModified()/1000); }        
1252     }
1253     
1254     // Exceptions
1255     public static class ReadFaultException extends FaultException {
1256         public ReadFaultException(int addr) { super(addr); }
1257     }
1258     public static class WriteFaultException extends FaultException {
1259         public WriteFaultException(int addr) { super(addr); }
1260     }
1261     public static class FaultException extends ExecutionException {
1262         public final int addr;
1263         public final RuntimeException cause;
1264         public FaultException(int addr) { super("fault at: " + toHex(addr)); this.addr = addr; cause = null; }
1265         public FaultException(RuntimeException e) { super(e.toString()); addr = -1; cause = e; }
1266     }
1267     public static class ExecutionException extends Exception {
1268         private String message = "(null)";
1269         private String location = "(unknown)";
1270         public ExecutionException() { /* noop */ }
1271         public ExecutionException(String s) { if(s != null) message = s; }
1272         void setLocation(String s) { location = s == null ? "(unknown)" : s; }
1273         public final String getMessage() { return message + " at " + location; }
1274     }
1275     public static class CallException extends Exception {
1276         public CallException(String s) { super(s); }
1277     }
1278     
1279     protected static class ErrnoException extends Exception {
1280         public int errno;
1281         public ErrnoException(int errno) { super("Errno: " + errno); this.errno = errno; }
1282     }
1283     
1284     // CPU State
1285     protected static class CPUState {
1286         public CPUState() { /* noop */ }
1287         /* GPRs */
1288         public int[] r = new int[32];
1289         /* Floating point regs */
1290         public int[] f = new int[32];
1291         public int hi, lo;
1292         public int fcsr;
1293         public int pc;
1294         
1295         public CPUState dup() {
1296                 CPUState c = new CPUState();
1297             c.hi = hi;
1298             c.lo = lo;
1299             c.fcsr = fcsr;
1300             c.pc = pc;
1301             for(int i=0;i<32;i++) {
1302                     c.r[i] = r[i];
1303                 c.f[i] = f[i];
1304             }
1305             return c;
1306         }
1307     }
1308     
1309     public static class SecurityManager {
1310         public boolean allowRead(File f) { return true; }
1311         public boolean allowWrite(File f) { return true; }
1312         public boolean allowStat(File f) { return true; }
1313     }
1314     
1315     // Null pointer check helper function
1316     protected final void nullPointerCheck(int addr) throws ExecutionException {
1317         if(addr < 65536)
1318             throw new ExecutionException("Attempted to dereference a null pointer " + toHex(addr));
1319     }
1320     
1321     // Utility functions
1322     byte[] byteBuf(int size) {
1323         if(_byteBuf==null) _byteBuf = new byte[size];
1324         else if(_byteBuf.length < size)
1325             _byteBuf = new byte[min(max(_byteBuf.length*2,size),MAX_CHUNK)];
1326         return _byteBuf;
1327     }
1328     
1329     static String getSystemProperty(String key) {
1330         try {
1331             return System.getProperty(key);
1332         } catch(SecurityException e) {
1333             return null;
1334         }
1335     }
1336     
1337     /** Decode a packed string */
1338     protected static final int[] decodeData(String s, int words) {
1339         if(s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
1340         if((s.length() / 8) * 7 < words*4) throw new IllegalArgumentException("string isn't big enough");
1341         int[] buf = new int[words];
1342         int prev = 0, left=0;
1343         for(int i=0,n=0;n<words;i+=8) {
1344             long l = 0;
1345             for(int j=0;j<8;j++) { l <<= 7; l |= s.charAt(i+j) & 0x7f; }
1346             if(left > 0) buf[n++] = prev | (int)(l>>>(56-left));
1347             if(n < words) buf[n++] = (int) (l >>> (24-left));
1348             left = (left + 8) & 0x1f;
1349             prev = (int)(l << left);
1350         }
1351         return buf;
1352     }
1353     
1354     static byte[] getBytes(String s) {
1355         try {
1356             return s.getBytes("ISO-8859-1");
1357         } catch(UnsupportedEncodingException e) {
1358             return null; // should never happen
1359         }
1360     }
1361     
1362     final static String toHex(int n) { return "0x" + Long.toString(n & 0xffffffffL, 16); }
1363     final static int min(int a, int b) { return a < b ? a : b; }
1364     final static int max(int a, int b) { return a > b ? a : b; }
1365 }