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