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