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