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