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