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