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