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