a745084176b0c32375ca143ec6263686f2b57894
[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 // FEATURE: Look over the public API, make sure we're exposing a bare minimum
12 // (we might make this an interface in the future)
13
14 public abstract class Runtime implements UsermodeConstants,Registers,Cloneable {
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     protected 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     protected 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     private 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         
299         if((dst&3) == 0 && (src&3)==0) {
300             if((count&~3) != 0) {
301                 int c = count>>2;
302                 int s = src>>>2;
303                 int d = dst>>>2;
304                 while(c != 0) {
305                     int[] srcPage = readPages[s>>>(pageShift-2)];
306                     if(srcPage == null) throw new ReadFaultException(s<<2);
307                     int[] dstPage = writePages[d>>>(pageShift-2)];
308                     if(dstPage == null) throw new WriteFaultException(d<<2);
309                     int srcIndex = s&pageWordMask;
310                     int dstIndex = d&pageWordMask;
311                     int n = min(c,pageWords-max(srcIndex,dstIndex));
312                     System.arraycopy(srcPage,srcIndex,dstPage,dstIndex,n);
313                     s += n; d += n; c -= n;
314                 }
315                 src = s<<2; dst = d<<2; count&=3;
316             }
317             if(count != 0) {
318                 int word1 = memRead(src);
319                 int word2 = memRead(dst);
320                 switch(count) {
321                     case 1: memWrite(dst,(word1&0xff000000)|(word2&0x00ffffff)); break;
322                     case 2: memWrite(dst,(word1&0xffff0000)|(word2&0x0000ffff)); break;
323                     case 3: memWrite(dst,(word1&0xffffff00)|(word2&0x000000ff)); break;
324                 }
325             }
326         } else {
327             while(count > 0) {
328                 int n = min(count,MAX_CHUNK);
329                 byte[] buf = byteBuf(n);
330                 copyin(src,buf,n);
331                 copyout(buf,dst,n);
332                 count -= n; src += n; dst += n;
333             }
334         }
335     }
336     
337     public final void memset(int addr, int ch, int count) throws FaultException {
338         int pageWords = (1<<pageShift)>>>2;
339         int pageWordMask = pageWords - 1;
340         
341         int fourBytes = ((ch&0xff)<<24)|((ch&0xff)<<16)|((ch&0xff)<<8)|((ch&0xff)<<0);
342         if((addr&3)!=0) {
343             int word = memRead(addr&~3);
344             switch(addr&3) {
345                 case 1: word = (word&0xff00ffff)|((ch&0xff)<<16); if(--count==0) break;
346                 case 2: word = (word&0xffff00ff)|((ch&0xff)<< 8); if(--count==0) break;
347                 case 3: word = (word&0xffffff00)|((ch&0xff)<< 0); if(--count==0) break;
348             }
349             memWrite(addr&~3,word);
350             addr = (addr&~3)+4;
351         }
352         if((count&~3) != 0) {
353             int c = count>>2;
354             int a = addr>>>2;
355             while(c != 0) {
356                 int[] page = readPages[a>>>(pageShift-2)];
357                 if(page == null) throw new WriteFaultException(a<<2);
358                 int index = a&pageWordMask;
359                 int n = min(c,pageWords-index);
360                 Arrays.fill(page,index,index+n,fourBytes);
361                 a += n; c -= n;
362             }
363             addr = a<<2; count&=3;
364         }
365         if(count != 0) {
366             int word = memRead(addr);
367             switch(count) {
368                 case 1: word = (word&0x00ffffff)|(fourBytes&0xff000000); break;
369                 case 2: word = (word&0x0000ffff)|(fourBytes&0xffff0000); break;
370                 case 3: word = (word&0x000000ff)|(fourBytes&0xffffff00); break;
371             }
372             memWrite(addr,word);
373         }
374     }
375     
376     /** Read a word from the processes memory at <i>addr</i> */
377     public final int memRead(int addr) throws ReadFaultException  {
378         if((addr & 3) != 0) throw new ReadFaultException(addr);
379         return unsafeMemRead(addr);
380     }
381        
382     protected final int unsafeMemRead(int addr) throws ReadFaultException {
383         int page = addr >>> pageShift;
384         int entry = (addr&(1<<pageShift) - 1)>>2;
385         try {
386             return readPages[page][entry];
387         } catch(ArrayIndexOutOfBoundsException e) {
388             if(page < 0 || page >= readPages.length) throw new ReadFaultException(addr);
389             throw e; // should never happen
390         } catch(NullPointerException e) {
391             throw new ReadFaultException(addr);
392         }
393     }
394     
395     /** Writes a word to the processes memory at <i>addr</i> */
396     public final void memWrite(int addr, int value) throws WriteFaultException  {
397         if((addr & 3) != 0) throw new WriteFaultException(addr);
398         unsafeMemWrite(addr,value);
399     }
400     
401     protected final void unsafeMemWrite(int addr, int value) throws WriteFaultException {
402         int page = addr >>> pageShift;
403         int entry = (addr&(1<<pageShift) - 1)>>2;
404         try {
405             writePages[page][entry] = value;
406         } catch(ArrayIndexOutOfBoundsException e) {
407             if(page < 0 || page >= writePages.length) throw new WriteFaultException(addr);
408             throw e; // should never happen
409         } catch(NullPointerException e) {
410             throw new WriteFaultException(addr);
411         }
412     }
413     
414     /** Created a new non-empty writable page at page number <i>page</i> */
415     private final int[] initPage(int page) { return initPage(page,false); }
416     /** Created a new non-empty page at page number <i>page</i>. If <i>ro</i> is set the page will be read-only */
417     private final int[] initPage(int page, boolean ro) {
418         int[] buf = new int[(1<<pageShift)>>>2];
419         writePages[page] = ro ? null : buf;
420         readPages[page] = buf;
421         return buf;
422     }
423     
424     /** Returns the exit status of the process. (only valid if state == DONE) 
425         @see Runtime#state */
426     public final int exitStatus() {
427         if(state != EXITED) throw new IllegalStateException("exitStatus() called in an inappropriate state");
428         return exitStatus;
429     }
430         
431     private int addStringArray(String[] strings, int topAddr) throws FaultException {
432         int count = strings.length;
433         int total = 0; /* null last table entry  */
434         for(int i=0;i<count;i++) total += strings[i].length() + 1;
435         total += (count+1)*4;
436         int start = (topAddr - total)&~3;
437         int addr = start + (count+1)*4;
438         int[] table = new int[count+1];
439         try {
440             for(int i=0;i<count;i++) {
441                 byte[] a = getBytes(strings[i]);
442                 table[i] = addr;
443                 copyout(a,addr,a.length);
444                 memset(addr+a.length,0,1);
445                 addr += a.length + 1;
446             }
447             addr=start;
448             for(int i=0;i<count+1;i++) {
449                 memWrite(addr,table[i]);
450                 addr += 4;
451             }
452         } catch(FaultException e) {
453             // should never happen
454             throw new Error(e.toString());
455         }
456         return start;
457     }
458     
459     protected String[] createEnv(String[] extra) { if(extra == null) extra = new String[0]; return extra; }
460     
461     /** Sets word number <i>index</i> in the _user_info table to <i>word</i>
462      * The user_info table is a chunk of memory in the program's memory defined by the
463      * symbol "user_info". The compiler/interpreter automatically determine the size
464      * and location of the user_info table from the ELF symbol table. setUserInfo and
465      * getUserInfo are used to modify the words in the user_info table. */
466     public void setUserInfo(int index, int word) {
467         if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
468         try {
469             memWrite(userInfoBase()+index*4,word);
470         } catch(FaultException e) { throw new RuntimeException(e.toString()); }
471     }
472     
473     /** Returns the word in the _user_info table entry <i>index</i>
474         @see Runtime#setUserInfo(int,int) setUserInfo */
475     public int getUserInfo(int index) {
476         if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
477         try {
478             return memRead(userInfoBase()+index*4);
479         } catch(FaultException e) { throw new RuntimeException(e.toString()); }
480     }
481     
482     /** Calls _execute() (subclass's execute()) and catches exceptions */
483     private void __execute() {
484         try {
485             _execute();
486         } catch(FaultException e) {
487             e.printStackTrace();
488             sys_exit(128+11); // SIGSEGV
489             exitException = e;
490         } catch(ExecutionException e) {
491             e.printStackTrace();
492             System.err.println(e);
493             sys_exit(128+4); // SIGILL
494             exitException = e;
495         }
496     }
497     
498     /** Executes the process until the PAUSE syscall is invoked or the process exits. Returns true if the process exited. */
499     public final boolean execute()  {
500         if(state != PAUSED) throw new IllegalStateException("execute() called in inappropriate state");
501         if(startTime == 0) startTime = System.currentTimeMillis();
502         state = RUNNING;
503         __execute();
504         if(state != PAUSED && state != EXITED && state != EXECED)
505             throw new IllegalStateException("execute() ended up in an inappropriate state (" + state + ")");
506         return state != PAUSED;
507     }
508     
509     protected static String[] concatArgv(String argv0, String[] rest) {
510             String[] argv = new String[rest.length+1];
511             System.arraycopy(rest,0,argv,1,rest.length);
512         argv[0] = argv0;
513         return argv;
514     }
515     
516     public final int run() { return run(null); }
517     public final int run(String argv0, String[] rest) { return run(concatArgv(argv0,rest)); }
518     public final int run(String[] args) { return run(args,null); }
519     
520     /** Runs the process until it exits and returns the exit status.
521         If the process executes the PAUSE syscall execution will be paused for 500ms and a warning will be displayed */
522     public final int run(String[] args, String[] env) {
523         start(args,env);
524         for(;;) {
525             if(execute()) break;
526             System.err.println("WARNING: Pause requested while executing run()");
527         }
528         if(state == EXECED) System.err.println("WARNING: Process exec()ed while being run under run()");
529         return state == EXITED ? exitStatus() : 0;
530     }
531
532     public final void start() { start(null); }
533     public final void start(String[] args) { start(args,null); }
534     
535     /** Initializes the process and prepairs it to be executed with execute() */
536     public final void start(String[] args, String[] environ)  {
537         int top, sp, argsAddr, envAddr;
538         if(state != STOPPED) throw new IllegalStateException("start() called in inappropriate state");
539
540         if(args == null) args = new String[]{getClass().getName()};
541         
542         sp = top = writePages.length*(1<<pageShift);
543         try {
544                     sp = argsAddr = addStringArray(args,sp);
545                     sp = envAddr = addStringArray(createEnv(environ),sp);
546         } catch(FaultException e) {
547             throw new IllegalArgumentException("args/environ too big");
548         }
549         sp &= ~15;
550         if(top - sp > ARG_MAX) throw new IllegalArgumentException("args/environ too big");
551
552         CPUState cpuState = new CPUState();
553         cpuState.r[A0] = argsAddr;
554         cpuState.r[A1] = envAddr;
555         cpuState.r[SP] = sp;
556         cpuState.r[RA] = 0xdeadbeef;
557         cpuState.r[GP] = gp();
558         cpuState.pc = entryPoint();
559         setCPUState(cpuState);
560         
561         state = PAUSED;
562         
563         _started();        
564     }
565     
566     /** Hook for subclasses to do their own startup */
567     protected void _started() {  }
568     
569     public final int call(String sym, Object[] args) throws CallException, FaultException {
570         if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
571         if(args.length > 7) throw new IllegalArgumentException("args.length > 7");
572         CPUState state = new CPUState();
573         getCPUState(state);
574         
575         int sp = state.r[SP];
576         int[] ia = new int[args.length];
577         for(int i=0;i<args.length;i++) {
578                     Object o = args[i];
579             byte[] buf = null;
580             if(o instanceof String) {
581                     buf = getBytes((String)o);
582             } else if(o instanceof byte[]) {
583                     buf = (byte[]) o;
584             } else if(o instanceof Number) {
585                     ia[i] = ((Number)o).intValue();
586             }
587             if(buf != null) {
588                     sp -= buf.length;
589                 copyout(buf,sp,buf.length);
590                 ia[i] = sp;
591             }
592         }
593         int oldSP = state.r[SP];
594         if(oldSP == sp) return call(sym,ia);
595         
596         state.r[SP] = sp;
597         setCPUState(state);
598         int ret = call(sym,ia);
599         state.r[SP] = oldSP;
600         setCPUState(state);
601         return ret;
602     }
603     
604     public final int call(String sym) throws CallException { return call(sym,new int[]{}); }
605     public final int call(String sym, int a0) throws CallException  { return call(sym,new int[]{a0}); }
606     public final int call(String sym, int a0, int a1) throws CallException  { return call(sym,new int[]{a0,a1}); }
607     
608     /** Calls a function in the process with the given arguments */
609     public final int call(String sym, int[] args) throws CallException {
610         int func = lookupSymbol(sym);
611         if(func == -1) throw new CallException(sym + " not found");
612         int helper = lookupSymbol("_call_helper");
613         if(helper == -1) throw new CallException("_call_helper not found");
614         return call(helper,func,args);
615     }
616     
617     /** Executes the code at <i>addr</i> in the process setting A0-A3 and S0-S3 to the given arguments
618         and returns the contents of V1 when the the pause syscall is invoked */
619     //public final int call(int addr, int a0, int a1, int a2, int a3, int s0, int s1, int s2, int s3) {
620     public final int call(int addr, int a0, int[] rest) throws CallException {
621         if(rest.length > 7) throw new IllegalArgumentException("rest.length > 7");
622         if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
623         int oldState = state;
624         CPUState saved = new CPUState();        
625         getCPUState(saved);
626         CPUState cpustate = saved.dup();
627         
628         cpustate.r[SP] = cpustate.r[SP]&~15;
629         cpustate.r[RA] = 0xdeadbeef;
630         cpustate.r[A0] = a0;
631         switch(rest.length) {            
632             case 7: cpustate.r[S3] = rest[6];
633             case 6: cpustate.r[S2] = rest[5];
634             case 5: cpustate.r[S1] = rest[4];
635             case 4: cpustate.r[S0] = rest[3];
636             case 3: cpustate.r[A3] = rest[2];
637             case 2: cpustate.r[A2] = rest[1];
638             case 1: cpustate.r[A1] = rest[0];
639         }
640         cpustate.pc = addr;
641         
642         state = RUNNING;
643
644         setCPUState(cpustate);
645         __execute();
646         getCPUState(cpustate);
647         setCPUState(saved);
648
649         if(state != PAUSED) throw new CallException("Process exit()ed while servicing a call() request");
650         state = oldState;
651         
652         return cpustate.r[V1];
653     }
654     
655     /** Determines if the process can access <i>fileName</i>. The default implementation simply logs 
656         the request and allows it */
657     protected boolean allowFileAccess(String fileName, boolean write) {
658         //System.err.println("Allowing " + (write?"write":"read-only") + " access to " + fileName);
659         return true;
660     }
661     
662     /** Allocated an entry in the FileDescriptor table for <i>fd</i> and returns the number.
663         Returns -1 if the table is full. This can be used by subclasses to use custom file
664         descriptors */
665     public int addFD(FD fd) {
666         if(state == EXITED || state == EXECED) throw new IllegalStateException("addFD called in inappropriate state");
667         int i;
668         for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
669         if(i==OPEN_MAX) return -1;
670         fds[i] = fd;
671         closeOnExec[i] = false;
672         return i;
673     }
674
675     /** Closes file descriptor <i>fdn</i> and removes it from the file descriptor table */
676     public boolean closeFD(int fdn) {
677         if(state == EXITED || state == EXECED) throw new IllegalStateException("closeFD called in inappropriate state");
678         if(fdn < 0 || fdn >= OPEN_MAX) return false;
679         if(fds[fdn] == null) return false;
680         fds[fdn].close();
681         fds[fdn] = null;        
682         return true;
683     }
684     
685     /** Duplicates the file descriptor <i>fdn</i> and returns the new fs */
686     public int dupFD(int fdn) {
687                 int i;
688                 if(fdn < 0 || fdn >= OPEN_MAX) return -1;
689                 if(fds[fdn] == null) return -1;
690                 for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
691         if(i==OPEN_MAX) return -1;
692         fds[i] = fds[fdn].dup();
693         return i;
694     }
695
696     public static final int RD_ONLY = 0;
697     public static final int WR_ONLY = 1;
698     public static final int RDWR = 2;
699     
700     public static final int O_CREAT = 0x0200;
701     public static final int O_EXCL = 0x0800;
702     public static final int O_APPEND = 0x0008;
703     public static final int O_TRUNC = 0x0400;
704     public static final int O_NONBLOCK = 0x4000;
705     
706     FD hostFSOpen(final File f, int flags, int mode) throws ErrnoException {
707         if((flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)) != 0) {
708             System.err.println("WARNING: Unsupported flags passed to open(): " + toHex(flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)));
709             throw new ErrnoException(ENOTSUP);
710         }
711         boolean write = mode!=RD_ONLY;
712
713         if(sm != null && !(write ? sm.allowWrite(f) : sm.allowRead(f))) throw new ErrnoException(EACCES);
714         
715         if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT)) {
716             try {
717                 // NOTE: createNewFile is a Java2 function
718                 if(!f.createNewFile()) throw new ErrnoException(EEXIST);
719             } catch(IOException e) {
720                 throw new ErrnoException(EIO);
721             }
722         } else if(!f.exists()) {
723             if((flags&O_CREAT)==0) return null;
724         } else if(f.isDirectory()) {
725             return hostFSDirFD(f);
726         }
727         
728         final Seekable.File sf;
729         try {
730             sf = new Seekable.File(f,write);
731         } catch(FileNotFoundException e) {
732             if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) throw new ErrnoException(EACCES);
733             return null;
734         } catch(IOException e) { throw new ErrnoException(EIO); }
735         
736         return new SeekableFD(sf,flags) { protected FStat _fstat() { return hostFStat(f); } };
737     }
738     
739     FStat hostFStat(File f) { return new HostFStat(f); }
740     FD hostFSDirFD(File f) { return null; }
741     
742     FD _open(String path, int flags, int mode) throws ErrnoException {
743         return hostFSOpen(new File(path),flags,mode);
744     }
745     
746     /** The open syscall */
747     private int sys_open(int addr, int flags, int mode) throws ErrnoException, FaultException {
748         FD fd = _open(cstring(addr),flags,mode);
749         if(fd == null) return -ENOENT;
750         int fdn = addFD(fd);
751         if(fdn == -1) { fd.close(); return -ENFILE; }
752         return fdn;
753     }
754
755     /** The write syscall */
756     private int sys_write(int fdn, int addr, int count) throws FaultException {
757         count = Math.min(count,MAX_CHUNK);
758         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
759         if(fds[fdn] == null || !fds[fdn].writable()) return -EBADFD;
760         try {
761             byte[] buf = byteBuf(count);
762             copyin(addr,buf,count);
763             return fds[fdn].write(buf,0,count);
764         } catch(IOException e) {
765             // NOTE: This should really send a SIGPIPE
766             if(e.getMessage().equals("Pipe closed")) return sys_exit(128+13);
767             return -EIO;
768         }
769     }
770
771     /** The read syscall */
772     private int sys_read(int fdn, int addr, int count) throws FaultException {
773         count = Math.min(count,MAX_CHUNK);
774         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
775         if(fds[fdn] == null || !fds[fdn].readable()) return -EBADFD;
776         try {
777             byte[] buf = byteBuf(count);
778             int n = fds[fdn].read(buf,0,count);
779             copyout(buf,addr,n);
780             return n;
781         } catch(IOException e) {
782             return -EIO;
783         }
784     }
785     
786     /** The close syscall */
787     private int sys_close(int fdn) {
788         return closeFD(fdn) ? 0 : -EBADFD;
789     }
790
791     
792     /** The seek syscall */
793     private int sys_lseek(int fdn, int offset, int whence) {
794         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
795         if(fds[fdn] == null) return -EBADFD;
796         if(whence != SEEK_SET && whence !=  SEEK_CUR && whence !=  SEEK_END) return -EINVAL;
797         try {
798             int n = fds[fdn].seek(offset,whence);
799             return n < 0 ? -ESPIPE : n;
800         } catch(IOException e) {
801             return -ESPIPE;
802         }
803     }
804     
805     /** The stat/fstat syscall helper */
806     int stat(FStat fs, int addr) throws FaultException {
807         memWrite(addr+0,(fs.dev()<<16)|(fs.inode()&0xffff)); // st_dev (top 16), // st_ino (bottom 16)
808         memWrite(addr+4,((fs.type()&0xf000))|(fs.mode()&0xfff)); // st_mode
809         memWrite(addr+8,1<<16); // st_nlink (top 16) // st_uid (bottom 16)
810         memWrite(addr+12,0); // st_gid (top 16) // st_rdev (bottom 16)
811         memWrite(addr+16,fs.size()); // st_size
812         memWrite(addr+20,fs.atime()); // st_atime
813         // memWrite(addr+24,0) // st_spare1
814         memWrite(addr+28,fs.mtime()); // st_mtime
815         // memWrite(addr+32,0) // st_spare2
816         memWrite(addr+36,fs.ctime()); // st_ctime
817         // memWrite(addr+40,0) // st_spare3
818         memWrite(addr+44,fs.blksize()); // st_bklsize;
819         memWrite(addr+48,fs.blocks()); // st_blocks
820         // memWrite(addr+52,0) // st_spare4[0]
821         // memWrite(addr+56,0) // st_spare4[1]
822         return 0;
823     }
824     
825     /** The fstat syscall */
826     private int sys_fstat(int fdn, int addr) throws FaultException {
827         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
828         if(fds[fdn] == null) return -EBADFD;
829         return stat(fds[fdn].fstat(),addr);
830     }
831     
832     /*
833     struct timeval {
834     long tv_sec;
835     long tv_usec;
836     };
837     */
838     private int sys_gettimeofday(int timevalAddr, int timezoneAddr) throws FaultException {
839         long now = System.currentTimeMillis();
840         int tv_sec = (int)(now / 1000);
841         int tv_usec = (int)((now%1000)*1000);
842         memWrite(timevalAddr+0,tv_sec);
843         memWrite(timevalAddr+4,tv_usec);
844         return 0;
845     }
846     
847     private int sys_sleep(int sec) {
848         if(sec < 0) sec = Integer.MAX_VALUE;
849         try {
850             Thread.sleep((long)sec*1000);
851             return 0;
852         } catch(InterruptedException e) {
853             return -1;
854         }
855     }
856     
857     /*
858       #define _CLOCKS_PER_SEC_ 1000
859       #define    _CLOCK_T_    unsigned long
860     struct tms {
861       clock_t   tms_utime;
862       clock_t   tms_stime;
863       clock_t   tms_cutime;    
864       clock_t   tms_cstime;
865     };*/
866    
867     private int sys_times(int tms) {
868         long now = System.currentTimeMillis();
869         int userTime = (int)((now - startTime)/16);
870         int sysTime = (int)((now - startTime)/16);
871         
872         try {
873             if(tms!=0) {
874                 memWrite(tms+0,userTime);
875                 memWrite(tms+4,sysTime);
876                 memWrite(tms+8,userTime);
877                 memWrite(tms+12,sysTime);
878             }
879         } catch(FaultException e) {
880             return -EFAULT;
881         }
882         return (int)now;
883     }
884     
885     private int sys_sysconf(int n) {
886         switch(n) {
887             case _SC_CLK_TCK: return 1000;
888             default:
889                 System.err.println("WARNING: Attempted to use unknown sysconf key: " + n);
890                 return -EINVAL;
891         }
892     }
893     
894     /** The sbrk syscall. This can also be used by subclasses to allocate memory.
895         <i>incr</i> is how much to increase the break by */
896     public int sbrk(int incr) {
897         if(incr < 0) return -ENOMEM;
898         if(incr==0) return heapEnd;
899         incr = (incr+3)&~3;
900         int oldEnd = heapEnd;
901         int newEnd = oldEnd + incr;
902         if(newEnd >= stackBottom) return -ENOMEM;
903         
904         if(writePages.length > 1) {
905             int pageMask = (1<<pageShift) - 1;
906             int pageWords = (1<<pageShift) >>> 2;
907             int start = (oldEnd + pageMask) >>> pageShift;
908             int end = (newEnd + pageMask) >>> pageShift;
909             try {
910                 for(int i=start;i<end;i++) readPages[i] = writePages[i] = new int[pageWords];
911             } catch(OutOfMemoryError e) {
912                 System.err.println("WARNING: Caught OOM Exception in sbrk: " + e);
913                 return -ENOMEM;
914             }
915         }
916         heapEnd = newEnd;
917         return oldEnd;
918     }
919
920     /** The getpid syscall */
921     private int sys_getpid() { return getPid(); }
922     protected int getPid() { return 1; }
923     
924     public static interface CallJavaCB { public int call(int a, int b, int c, int d); }
925     
926     private int sys_calljava(int a, int b, int c, int d) {
927         if(state != RUNNING) throw new IllegalStateException("wound up calling sys_calljava while not in RUNNING");
928         if(callJavaCB != null) {
929             state = CALLJAVA;
930             int ret;
931             try {
932                 ret = callJavaCB.call(a,b,c,d);
933             } catch(RuntimeException e) {
934                 System.err.println("Error while executing callJavaCB");
935                     e.printStackTrace();
936                 ret = 0;
937             }
938             state = RUNNING;
939             return ret;
940         } else {
941                         System.err.println("WARNING: calljava syscall invoked without a calljava callback set");
942                         return 0;
943         }
944     }
945         
946     private int sys_pause() {
947         state = PAUSED;
948         return 0;
949     }
950     
951     private int sys_getpagesize() { return writePages.length == 1 ? 4096 : (1<<pageShift); }
952     
953     private int sys_isatty(int fdn) {
954         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
955         if(fds[fdn] == null) return -EBADFD;
956         return fds[fdn].isatty() ? 1 : 0;
957     }
958
959     
960     /** Hook for subclasses to do something when the process exits  */
961     protected void _exited() {  }
962     
963     private int sys_exit(int status) {
964         exitStatus = status;
965         for(int i=0;i<fds.length;i++) if(fds[i] != null) closeFD(i);
966         state = EXITED;
967         _exited();
968         return 0;
969     }
970        
971     private int sys_fcntl(int fdn, int cmd, int arg) {
972         int i;
973             
974         if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
975         if(fds[fdn] == null) return -EBADFD;
976         FD fd = fds[fdn];
977         
978         switch(cmd) {
979             case F_DUPFD:
980                 if(arg < 0 || arg >= OPEN_MAX) return -EINVAL;
981                 for(i=arg;i<OPEN_MAX;i++) if(fds[i]==null) break;
982                 if(i==OPEN_MAX) return -EMFILE;
983                 fds[i] = fd.dup();
984                 return 0;
985             case F_GETFL:
986                 int flags = 0;
987                 if(fd.writable() && fd.readable())  flags = 2;
988                 else if(fd.writable()) flags = 1;
989                 return flags;
990             case F_SETFD:
991                     closeOnExec[fdn] = arg != 0;
992                 return 0;
993             case F_GETFD:
994                 return closeOnExec[fdn] ? 1 : 0;
995             default:
996                 System.err.println("WARNING: Unknown fcntl command: " + cmd);
997                 return -ENOSYS;
998         }
999     }
1000             
1001     /** The syscall dispatcher.
1002         The should be called by subclasses when the syscall instruction is invoked.
1003         <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 
1004         the contenst of A0, A1, A2, and A3. The call MAY change the state
1005         @see Runtime#state state */
1006     protected final int syscall(int syscall, int a, int b, int c, int d) {
1007         try {
1008                     return _syscall(syscall,a,b,c,d);
1009         } catch(ErrnoException e) {
1010             e.printStackTrace();
1011                     return -e.errno;
1012         } catch(FaultException e) {
1013                     return -EFAULT;
1014         } catch(RuntimeException e) {
1015             e.printStackTrace();
1016                     throw new Error("Internal Error in _syscall()");
1017         }
1018     }
1019     
1020     int _syscall(int syscall, int a, int b, int c, int d) throws ErrnoException, FaultException {
1021         switch(syscall) {
1022             case SYS_null: return 0;
1023             case SYS_exit: return sys_exit(a);
1024             case SYS_pause: return sys_pause();
1025             case SYS_write: return sys_write(a,b,c);
1026             case SYS_fstat: return sys_fstat(a,b);
1027             case SYS_sbrk: return sbrk(a);
1028             case SYS_open: return sys_open(a,b,c);
1029             case SYS_close: return sys_close(a);
1030             case SYS_read: return sys_read(a,b,c);
1031             case SYS_lseek: return sys_lseek(a,b,c);
1032             case SYS_getpid: return sys_getpid();
1033             case SYS_calljava: return sys_calljava(a,b,c,d);
1034             case SYS_gettimeofday: return sys_gettimeofday(a,b);
1035             case SYS_sleep: return sys_sleep(a);
1036             case SYS_times: return sys_times(a);
1037             case SYS_getpagesize: return sys_getpagesize();
1038             case SYS_isatty: return sys_isatty(a);
1039             case SYS_fcntl: return sys_fcntl(a,b,c);
1040             case SYS_sysconf: return sys_sysconf(a);
1041
1042             case SYS_kill:
1043             case SYS_fork:
1044             case SYS_pipe:
1045             case SYS_dup2:
1046             case SYS_waitpid:
1047             case SYS_stat:
1048             case SYS_mkdir:
1049             case SYS_getcwd:
1050             case SYS_chdir:
1051                 System.err.println("Attempted to use a UnixRuntime syscall in Runtime (" + syscall + ")");
1052                 return -ENOSYS;
1053             default:
1054                 System.err.println("Attempted to use unknown syscall: " + syscall);
1055                 return -ENOSYS;
1056         }
1057     }
1058     
1059     public int xmalloc(int size) { int p=malloc(size); if(p==0) throw new RuntimeException("malloc() failed"); return p; }
1060     public int xrealloc(int addr,int newsize) { int p=realloc(addr,newsize); if(p==0) throw new RuntimeException("realloc() failed"); return p; }
1061     public int realloc(int addr, int newsize) { try { return call("realloc",addr,newsize); } catch(CallException e) { return 0; } }
1062     public int malloc(int size) { try { return call("malloc",size); } catch(CallException e) { return 0; } }
1063     public void free(int p) { try { if(p!=0) call("free",p); } catch(CallException e) { /*noop*/ } }
1064     
1065     /** Helper function to create a cstring in main memory */
1066     public int strdup(String s) {
1067         byte[] a;
1068         if(s == null) s = "(null)";
1069         byte[] a2 = getBytes(s);
1070         a = new byte[a2.length+1];
1071         System.arraycopy(a2,0,a,0,a2.length);
1072         int addr = malloc(a.length);
1073         if(addr == 0) return 0;
1074         try {
1075             copyout(a,addr,a.length);
1076         } catch(FaultException e) {
1077             free(addr);
1078             return 0;
1079         }
1080         return addr;
1081     }
1082     
1083     /** Helper function to read a cstring from main memory */
1084     public String cstring(int addr) throws ReadFaultException {
1085         StringBuffer sb = new StringBuffer();
1086         for(;;) {
1087             int word = memRead(addr&~3);
1088             switch(addr&3) {
1089                 case 0: if(((word>>>24)&0xff)==0) return sb.toString(); sb.append((char)((word>>>24)&0xff)); addr++;
1090                 case 1: if(((word>>>16)&0xff)==0) return sb.toString(); sb.append((char)((word>>>16)&0xff)); addr++;
1091                 case 2: if(((word>>> 8)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 8)&0xff)); addr++;
1092                 case 3: if(((word>>> 0)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 0)&0xff)); addr++;
1093             }
1094         }
1095     }
1096     
1097     /** File Descriptor class */
1098     public static abstract class FD {
1099         private int refCount = 1;
1100     
1101         /** returns true if the fd is readable */
1102         public boolean readable() { return false; }
1103         /** returns true if the fd is writable */
1104         public boolean writable() { return false; }
1105         
1106         /** Read some bytes. Should return the number of bytes read, 0 on EOF, or throw an IOException on error */
1107         public int read(byte[] a, int off, int length) throws IOException { throw new IOException("no definition"); }
1108         /** Write. Should return the number of bytes written or throw an IOException on error */
1109         public int write(byte[] a, int off, int length) throws IOException { throw new IOException("no definition"); }
1110
1111         /** Seek in the filedescriptor. Whence is SEEK_SET, SEEK_CUR, or SEEK_END. Should return -1 on error or the new position. */
1112         public int seek(int n, int whence)  throws IOException  { return -1; }
1113         
1114         /** Return a Seekable object representing this file descriptor (can be read only) 
1115             This is required for exec() */
1116         Seekable seekable() { return null; }
1117         
1118         /** Should return true if this is a tty */
1119         // FEATURE: get rid of the isatty syscall and just do with newlib's dumb isatty.c
1120         public boolean isatty() { return false; }
1121         
1122         private FStat cachedFStat = null;
1123         public final FStat fstat() {
1124             if(cachedFStat == null) cachedFStat = _fstat(); 
1125             return cachedFStat;
1126         }
1127         
1128         protected abstract FStat _fstat();
1129         
1130         /** Closes the fd */
1131         public final void close() { if(--refCount==0) _close(); }
1132         protected void _close() { /* noop*/ }
1133         
1134         FD dup() { refCount++; return this; }
1135     }
1136         
1137     /** FileDescriptor class for normal files */
1138     public abstract static class SeekableFD extends FD {
1139         private final int flags;
1140         private final Seekable data;
1141         public boolean readable() { return (flags&3) != WR_ONLY; }
1142         public boolean writable() { return (flags&3) != RD_ONLY; }
1143         
1144         SeekableFD(Seekable data, int flags) { this.data = data; this.flags = flags; }
1145         
1146         protected abstract FStat _fstat();
1147
1148         Seekable seekable() { return data; }
1149         
1150         public int seek(int n, int whence) throws IOException {
1151             switch(whence) {
1152                 case SEEK_SET: break;
1153                 case SEEK_CUR: n += data.pos(); break;
1154                 case SEEK_END: n += data.length(); break;
1155                 default: return -1;
1156             }
1157             data.seek(n);
1158             return n;
1159         }
1160         
1161         public int write(byte[] a, int off, int length) throws IOException {
1162             // NOTE: There is race condition here but we can't fix it in pure java
1163             if((flags&O_APPEND) != 0) seek(0,SEEK_END);
1164             return data.write(a,off,length);
1165         }
1166         
1167         public int read(byte[] a, int off, int length) throws IOException {
1168             int n = data.read(a,off,length);
1169             return n < 0 ? 0 : n;
1170         }
1171         
1172         protected void _close() { try { data.close(); } catch(IOException e) { /*ignore*/ } }        
1173     }
1174     
1175     public static class OutputStreamFD extends FD {
1176         private OutputStream os;
1177         public boolean writable() { return true; }
1178         public OutputStreamFD(OutputStream os) { this.os = os; }
1179         public int write(byte[] a, int off, int length) throws IOException { os.write(a,off,length); return length; }
1180         public void _close() { try { os.close(); } catch(IOException e) { /*ignore*/ }  }
1181         public FStat _fstat() { return new FStat(); }
1182     }
1183     
1184     public static class InputStreamFD extends FD {
1185         private InputStream is;
1186         public boolean readable() { return true; }
1187         public InputStreamFD(InputStream is) { this.is = is; }
1188         public int read(byte[] a, int off, int length) throws IOException { int n = is.read(a,off,length); return n < 0 ? 0 : n; }
1189         public void _close() { try { is.close(); } catch(IOException e) { /*ignore*/ } }
1190         public FStat _fstat() { return new FStat(); }
1191     }
1192     
1193     protected static class StdinFD extends InputStreamFD {
1194         public StdinFD(InputStream is) { super(is); }
1195         public void _close() { /* noop */ }
1196         public FStat _fstat() { return new FStat() { public int type() { return S_IFCHR; } }; }
1197         public boolean isatty() { return true; }
1198     }
1199     protected static class StdoutFD extends OutputStreamFD {
1200         public StdoutFD(OutputStream os) { super(os); }
1201         public void _close() { /* noop */ }
1202         public FStat _fstat() { return new FStat() { public int type() { return S_IFCHR; } }; }
1203         public boolean isatty() { return true; }
1204     }
1205     
1206     public static class FStat {
1207         public static final int S_IFIFO = 0010000;
1208         public static final int S_IFCHR = 0020000;
1209         public static final int S_IFDIR = 0040000;
1210         public static final int S_IFREG = 0100000;
1211         
1212         public int dev() { return -1; }
1213         // FEATURE: inode numbers are calculated inconsistently throught the runtime
1214         public int inode() { return hashCode() & 0xfffff; }
1215         public int mode() { return 0; }
1216         public int type() { return S_IFIFO; }
1217         public int nlink() { return 0; }
1218         public int uid() { return 0; }
1219         public int gid() { return 0; }
1220         public int size() { return 0; }
1221         public int atime() { return 0; }
1222         public int mtime() { return 0; }
1223         public int ctime() { return 0; }
1224         public int blksize() { return 512; }
1225         public int blocks() { return (size()+blksize()-1)/blksize(); }        
1226     }
1227     
1228     protected static class HostFStat extends FStat {
1229         private final File f;
1230         private final boolean executable; 
1231         public HostFStat(File f) {
1232             this.f = f;
1233             executable = executable();
1234         }
1235         public int dev() { return 1; }
1236         public int inode() { return f.getName().hashCode() & 0xffff; }
1237         public int type() { return f.isDirectory() ? S_IFDIR : S_IFREG; }
1238         public int nlink() { return 1; }
1239         public int mode() {
1240             int mode = 0;
1241             boolean canread = f.canRead();
1242             if(canread && (executable || f.isDirectory())) mode |= 0111;
1243             if(canread) mode |= 0444;
1244             if(f.canWrite()) mode |= 0222;
1245             return mode;
1246         }
1247         public int size() { return (int) f.length(); }
1248         public int mtime() { return (int)(f.lastModified()/1000); }
1249         
1250         boolean executable() { return false; }
1251     }
1252     
1253     // Exceptions
1254     public class ReadFaultException extends FaultException {
1255         public ReadFaultException(int addr) { super(addr); }
1256     }
1257     public class WriteFaultException extends FaultException {
1258         public WriteFaultException(int addr) { super(addr); }
1259     }
1260     public abstract class FaultException extends ExecutionException {
1261         public int addr;
1262         public FaultException(int addr) { super("fault at: " + toHex(addr)); this.addr = addr; }
1263     }
1264     public static class ExecutionException extends Exception {
1265         private String message = "(null)";
1266         private String location = "(unknown)";
1267         public ExecutionException() { /* noop */ }
1268         public ExecutionException(String s) { if(s != null) message = s; }
1269         void setLocation(String s) { location = s == null ? "(unknown)" : s; }
1270         public final String getMessage() { return message + " at " + location; }
1271     }
1272     public static class CallException extends Exception {
1273         public CallException(String s) { super(s); }
1274     }
1275     
1276     protected static class ErrnoException extends Exception {
1277         public int errno;
1278         public ErrnoException(int errno) { super("Errno: " + errno); this.errno = errno; }
1279     }
1280     
1281     // CPU State
1282     protected static class CPUState {
1283         public CPUState() { /* noop */ }
1284         /* GPRs */
1285         public int[] r = new int[32];
1286         /* Floating point regs */
1287         public int[] f = new int[32];
1288         public int hi, lo;
1289         public int fcsr;
1290         public int pc;
1291         
1292         public CPUState dup() {
1293                     CPUState c = new CPUState();
1294             c.hi = hi;
1295             c.lo = lo;
1296             c.fcsr = fcsr;
1297             c.pc = pc;
1298             for(int i=0;i<32;i++) {
1299                     c.r[i] = r[i];
1300                 c.f[i] = f[i];
1301             }
1302             return c;
1303         }
1304     }
1305     
1306     public static class SecurityManager {
1307             public boolean allowRead(File f) { return true; }
1308         public boolean allowWrite(File f) { return true; }
1309         public boolean allowStat(File f) { return true; }
1310     }
1311     
1312     // Null pointer check helper function
1313     protected final void nullPointerCheck(int addr) throws ExecutionException {
1314         if(addr < 65536)
1315             throw new ExecutionException("Attempted to dereference a null pointer " + toHex(addr));
1316     }
1317     
1318     // Utility functions
1319     private byte[] byteBuf(int size) {
1320         if(_byteBuf==null) _byteBuf = new byte[size];
1321         else if(_byteBuf.length < size)
1322             _byteBuf = new byte[min(max(_byteBuf.length*2,size),MAX_CHUNK)];
1323         return _byteBuf;
1324     }
1325     
1326     protected static String getSystemProperty(String key) {
1327         try {
1328             return System.getProperty(key);
1329         } catch(SecurityException e) {
1330             return null;
1331         }
1332     }
1333     
1334     /** Decode a packed string */
1335     protected static final int[] decodeData(String s, int words) {
1336         if(s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
1337         if((s.length() / 8) * 7 < words*4) throw new IllegalArgumentException("string isn't big enough");
1338         int[] buf = new int[words];
1339         int prev = 0, left=0;
1340         for(int i=0,n=0;n<words;i+=8) {
1341             long l = 0;
1342             for(int j=0;j<8;j++) { l <<= 7; l |= s.charAt(i+j) & 0x7f; }
1343             if(left > 0) buf[n++] = prev | (int)(l>>>(56-left));
1344             if(n < words) buf[n++] = (int) (l >>> (24-left));
1345             left = (left + 8) & 0x1f;
1346             prev = (int)(l << left);
1347         }
1348         return buf;
1349     }
1350     
1351     protected static byte[] getBytes(String s) {
1352         try {
1353             return s.getBytes("ISO-8859-1");
1354         } catch(UnsupportedEncodingException e) {
1355             return null; // should never happen
1356         }
1357     }
1358     
1359     protected final static String toHex(int n) { return "0x" + Long.toString(n & 0xffffffffL, 16); }
1360     protected final static int min(int a, int b) { return a < b ? a : b; }
1361     protected final static int max(int a, int b) { return a > b ? a : b; }
1362 }