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