1 // Copyright 2003 Brian Alliet
2 // Based on org.xwt.imp.MIPS by Adam Megacz
3 // Portions Copyright 2003 Adam Megacz
5 // FEATURE: Add a patch to gcc that enabled -Wall -Werror by default
6 // FIXME: Get a hotel for IVME :)
8 package org.ibex.nestedvm;
10 import org.ibex.nestedvm.util.*;
13 public abstract class Runtime implements UsermodeConstants,Registers,Cloneable {
14 public static final String VERSION = "1.0";
16 /** True to write useful diagnostic information to stderr when things go wrong */
17 final static boolean STDERR_DIAG = true;
19 /** Number of bits to shift to get the page number (1<<<pageShift == pageSize) */
20 protected final int pageShift;
21 /** Bottom of region of memory allocated to the stack */
22 private final int stackBottom;
24 /** Readable main memory pages */
25 protected int[][] readPages;
26 /** Writable main memory pages.
27 If the page is writable writePages[x] == readPages[x]; if not writePages[x] == null. */
28 protected int[][] writePages;
30 /** The address of the end of the heap */
33 /** Number of guard pages to keep between the stack and the heap */
34 private static final int STACK_GUARD_PAGES = 4;
36 /** The last address the executable uses (other than the heap/stack) */
37 protected abstract int heapStart();
39 /** The program's entry point */
40 protected abstract int entryPoint();
42 /** The location of the _user_info block (or 0 is there is none) */
43 protected int userInfoBase() { return 0; }
44 protected int userInfoSize() { return 0; }
46 /** The location of the global pointer */
47 protected abstract int gp();
49 /** When the process started */
50 private long startTime;
52 /** Program is executing instructions */
53 public final static int RUNNING = 0; // Horrible things will happen if this isn't 0
54 /** Text/Data loaded in memory */
55 public final static int STOPPED = 1;
56 /** Prgram has been started but is paused */
57 public final static int PAUSED = 2;
58 /** Program is executing a callJava() method */
59 public final static int CALLJAVA = 3;
60 /** Program has exited (it cannot currently be restarted) */
61 public final static int EXITED = 4;
62 /** Program has executed a successful exec(), a new Runtime needs to be run (used by UnixRuntime) */
63 public final static int EXECED = 5;
65 /** The current state */
66 protected int state = STOPPED;
67 /** @see Runtime#state state */
68 public final int getState() { return state; }
70 /** The exit status if the process (only valid if state==DONE)
72 private int exitStatus;
73 public ExecutionException exitException;
75 /** Table containing all open file descriptors. (Entries are null if the fd is not in use */
76 FD[] fds = new FD[OPEN_MAX]; // package-private for UnixRuntime
77 boolean closeOnExec[] = new boolean[OPEN_MAX];
79 /** Pointer to a SecurityManager for this process */
81 public void setSecurityManager(SecurityManager sm) { this.sm = sm; }
83 /** Pointer to a callback for the call_java syscall */
84 private CallJavaCB callJavaCB;
85 public void setCallJavaCB(CallJavaCB callJavaCB) { this.callJavaCB = callJavaCB; }
87 /** Temporary buffer for read/write operations */
88 private byte[] _byteBuf;
89 /** Max size of temporary buffer
90 @see Runtime#_byteBuf */
91 final static int MAX_CHUNK = 16*1024*1024 - 1024;
93 /** Subclasses should actually execute program in this method. They should continue
94 executing until state != RUNNING. Only syscall() can modify state. It is safe
95 to only check the state attribute after a call to syscall() */
96 protected abstract void _execute() throws ExecutionException;
98 /** Subclasses should return the address of the symbol <i>symbol</i> or -1 it it doesn't exits in this method
99 This method is only required if the call() function is used */
100 protected int lookupSymbol(String symbol) { return -1; }
102 /** Subclasses should populate a CPUState object representing the cpu state */
103 protected abstract void getCPUState(CPUState state);
105 /** Subclasses should set the CPUState to the state held in <i>state</i> */
106 protected abstract void setCPUState(CPUState state);
108 protected Object clone() throws CloneNotSupportedException {
109 Runtime r = (Runtime) super.clone();
112 r.fds = new FD[OPEN_MAX];
113 for(int i=0;i<OPEN_MAX;i++) if(fds[i] != null) r.fds[i] = fds[i].dup();
114 int totalPages = writePages.length;
115 r.readPages = new int[totalPages][];
116 r.writePages = new int[totalPages][];
117 for(int i=0;i<totalPages;i++) {
118 if(readPages[i] == null) continue;
119 if(writePages[i] == null) r.readPages[i] = readPages[i];
120 else r.readPages[i] = r.writePages[i] = (int[])writePages[i].clone();
125 protected Runtime(int pageSize, int totalPages) {
126 if(pageSize <= 0) throw new IllegalArgumentException("pageSize <= 0");
127 if(totalPages <= 0) throw new IllegalArgumentException("totalPages <= 0");
128 if((pageSize&(pageSize-1)) != 0) throw new IllegalArgumentException("pageSize not a power of two");
131 while(pageSize>>>_pageShift != 1) _pageShift++;
132 pageShift = _pageShift;
134 int heapStart = heapStart();
135 int totalMemory = totalPages * pageSize;
136 int stackSize = max(totalMemory/512,ARG_MAX+65536);
139 stackSize = max(stackSize,pageSize);
140 stackSize = (stackSize + pageSize - 1) & ~(pageSize-1);
141 stackPages = stackSize >>> pageShift;
142 heapStart = (heapStart + pageSize - 1) & ~(pageSize-1);
143 if(stackPages + STACK_GUARD_PAGES + (heapStart >>> pageShift) >= totalPages)
144 throw new IllegalArgumentException("total pages too small");
146 if(pageSize < heapStart + stackSize) throw new IllegalArgumentException("total memory too small");
147 heapStart = (heapStart + 4095) & ~4096;
150 stackBottom = totalMemory - stackSize;
153 readPages = new int[totalPages][];
154 writePages = new int[totalPages][];
156 if(totalPages == 1) {
157 readPages[0] = writePages[0] = new int[pageSize>>2];
159 for(int i=(stackBottom >>> pageShift);i<writePages.length;i++) {
160 readPages[i] = writePages[i] = new int[pageSize>>2];
164 InputStream stdin = Boolean.valueOf(getSystemProperty("nestedvm.textstdin")).booleanValue() ? new TextInputStream(System.in) : System.in;
165 addFD(new TerminalFD(stdin));
166 addFD(new TerminalFD(System.out));
167 addFD(new TerminalFD(System.err));
170 /** Copy everything from <i>src</i> to <i>addr</i> initializing uninitialized pages if required.
171 Newly initalized pages will be marked read-only if <i>ro</i> is set */
172 protected final void initPages(int[] src, int addr, boolean ro) {
173 int pageWords = (1<<pageShift)>>>2;
174 int pageMask = (1<<pageShift) - 1;
176 for(int i=0;i<src.length;) {
177 int page = addr >>> pageShift;
178 int start = (addr&pageMask)>>2;
179 int elements = min(pageWords-start,src.length-i);
180 if(readPages[page]==null) {
183 if(writePages[page] == null) writePages[page] = readPages[page];
185 System.arraycopy(src,i,readPages[page],start,elements);
191 /** Initialize <i>words</i> of pages starting at <i>addr</i> to 0 */
192 protected final void clearPages(int addr, int words) {
193 int pageWords = (1<<pageShift)>>>2;
194 int pageMask = (1<<pageShift) - 1;
196 for(int i=0;i<words;) {
197 int page = addr >>> pageShift;
198 int start = (addr&pageMask)>>2;
199 int elements = min(pageWords-start,words-i);
200 if(readPages[page]==null) {
201 readPages[page] = writePages[page] = new int[pageWords];
203 if(writePages[page] == null) writePages[page] = readPages[page];
204 for(int j=start;j<start+elements;j++) writePages[page][j] = 0;
211 /** Copies <i>length</i> bytes from the processes memory space starting at
212 <i>addr</i> INTO a java byte array <i>a</i> */
213 public final void copyin(int addr, byte[] buf, int count) throws ReadFaultException {
214 int pageWords = (1<<pageShift)>>>2;
215 int pageMask = pageWords - 1;
218 if(count == 0) return;
220 int word = memRead(addr&~3);
222 case 1: buf[x++] = (byte)((word>>>16)&0xff); if(--count==0) break;
223 case 2: buf[x++] = (byte)((word>>> 8)&0xff); if(--count==0) break;
224 case 3: buf[x++] = (byte)((word>>> 0)&0xff); if(--count==0) break;
228 if((count&~3) != 0) {
232 int[] page = readPages[a >>> (pageShift-2)];
233 if(page == null) throw new ReadFaultException(a<<2);
234 int index = a&pageMask;
235 int n = min(c,pageWords-index);
236 for(int i=0;i<n;i++,x+=4) {
237 int word = page[index+i];
238 buf[x+0] = (byte)((word>>>24)&0xff); buf[x+1] = (byte)((word>>>16)&0xff);
239 buf[x+2] = (byte)((word>>> 8)&0xff); buf[x+3] = (byte)((word>>> 0)&0xff);
243 addr = a<<2; count &=3;
246 int word = memRead(addr);
248 case 3: buf[x+2] = (byte)((word>>>8)&0xff);
249 case 2: buf[x+1] = (byte)((word>>>16)&0xff);
250 case 1: buf[x+0] = (byte)((word>>>24)&0xff);
255 /** Copies <i>length</i> bytes OUT OF the java array <i>a</i> into the processes memory
256 space at <i>addr</i> */
257 public final void copyout(byte[] buf, int addr, int count) throws FaultException {
258 int pageWords = (1<<pageShift)>>>2;
259 int pageWordMask = pageWords - 1;
262 if(count == 0) return;
264 int word = memRead(addr&~3);
266 case 1: word = (word&0xff00ffff)|((buf[x++]&0xff)<<16); if(--count==0) break;
267 case 2: word = (word&0xffff00ff)|((buf[x++]&0xff)<< 8); if(--count==0) break;
268 case 3: word = (word&0xffffff00)|((buf[x++]&0xff)<< 0); if(--count==0) break;
270 memWrite(addr&~3,word);
274 if((count&~3) != 0) {
278 int[] page = writePages[a >>> (pageShift-2)];
279 if(page == null) throw new WriteFaultException(a<<2);
280 int index = a&pageWordMask;
281 int n = min(c,pageWords-index);
282 for(int i=0;i<n;i++,x+=4)
283 page[index+i] = ((buf[x+0]&0xff)<<24)|((buf[x+1]&0xff)<<16)|((buf[x+2]&0xff)<<8)|((buf[x+3]&0xff)<<0);
286 addr = a<<2; count&=3;
290 int word = memRead(addr);
292 case 1: word = (word&0x00ffffff)|((buf[x+0]&0xff)<<24); break;
293 case 2: word = (word&0x0000ffff)|((buf[x+0]&0xff)<<24)|((buf[x+1]&0xff)<<16); break;
294 case 3: word = (word&0x000000ff)|((buf[x+0]&0xff)<<24)|((buf[x+1]&0xff)<<16)|((buf[x+2]&0xff)<<8); break;
300 public final void memcpy(int dst, int src, int count) throws FaultException {
301 int pageWords = (1<<pageShift)>>>2;
302 int pageWordMask = pageWords - 1;
303 if((dst&3) == 0 && (src&3)==0) {
304 if((count&~3) != 0) {
309 int[] srcPage = readPages[s>>>(pageShift-2)];
310 if(srcPage == null) throw new ReadFaultException(s<<2);
311 int[] dstPage = writePages[d>>>(pageShift-2)];
312 if(dstPage == null) throw new WriteFaultException(d<<2);
313 int srcIndex = s&pageWordMask;
314 int dstIndex = d&pageWordMask;
315 int n = min(c,pageWords-max(srcIndex,dstIndex));
316 System.arraycopy(srcPage,srcIndex,dstPage,dstIndex,n);
317 s += n; d += n; c -= n;
319 src = s<<2; dst = d<<2; count&=3;
322 int word1 = memRead(src);
323 int word2 = memRead(dst);
325 case 1: memWrite(dst,(word1&0xff000000)|(word2&0x00ffffff)); break;
326 case 2: memWrite(dst,(word1&0xffff0000)|(word2&0x0000ffff)); break;
327 case 3: memWrite(dst,(word1&0xffffff00)|(word2&0x000000ff)); break;
332 int n = min(count,MAX_CHUNK);
333 byte[] buf = byteBuf(n);
336 count -= n; src += n; dst += n;
341 public final void memset(int addr, int ch, int count) throws FaultException {
342 int pageWords = (1<<pageShift)>>>2;
343 int pageWordMask = pageWords - 1;
345 int fourBytes = ((ch&0xff)<<24)|((ch&0xff)<<16)|((ch&0xff)<<8)|((ch&0xff)<<0);
347 int word = memRead(addr&~3);
349 case 1: word = (word&0xff00ffff)|((ch&0xff)<<16); if(--count==0) break;
350 case 2: word = (word&0xffff00ff)|((ch&0xff)<< 8); if(--count==0) break;
351 case 3: word = (word&0xffffff00)|((ch&0xff)<< 0); if(--count==0) break;
353 memWrite(addr&~3,word);
356 if((count&~3) != 0) {
360 int[] page = readPages[a>>>(pageShift-2)];
361 if(page == null) throw new WriteFaultException(a<<2);
362 int index = a&pageWordMask;
363 int n = min(c,pageWords-index);
364 /* Arrays.fill(page,index,index+n,fourBytes);*/
365 for(int i=index;i<index+n;i++) page[i] = fourBytes;
368 addr = a<<2; count&=3;
371 int word = memRead(addr);
373 case 1: word = (word&0x00ffffff)|(fourBytes&0xff000000); break;
374 case 2: word = (word&0x0000ffff)|(fourBytes&0xffff0000); break;
375 case 3: word = (word&0x000000ff)|(fourBytes&0xffffff00); break;
381 /** Read a word from the processes memory at <i>addr</i> */
382 public final int memRead(int addr) throws ReadFaultException {
383 if((addr & 3) != 0) throw new ReadFaultException(addr);
384 return unsafeMemRead(addr);
387 protected final int unsafeMemRead(int addr) throws ReadFaultException {
388 int page = addr >>> pageShift;
389 int entry = (addr&(1<<pageShift) - 1)>>2;
391 return readPages[page][entry];
392 } catch(ArrayIndexOutOfBoundsException e) {
393 if(page < 0 || page >= readPages.length) throw new ReadFaultException(addr);
394 throw e; // should never happen
395 } catch(NullPointerException e) {
396 throw new ReadFaultException(addr);
400 /** Writes a word to the processes memory at <i>addr</i> */
401 public final void memWrite(int addr, int value) throws WriteFaultException {
402 if((addr & 3) != 0) throw new WriteFaultException(addr);
403 unsafeMemWrite(addr,value);
406 protected final void unsafeMemWrite(int addr, int value) throws WriteFaultException {
407 int page = addr >>> pageShift;
408 int entry = (addr&(1<<pageShift) - 1)>>2;
410 writePages[page][entry] = value;
411 } catch(ArrayIndexOutOfBoundsException e) {
412 if(page < 0 || page >= writePages.length) throw new WriteFaultException(addr);
413 throw e; // should never happen
414 } catch(NullPointerException e) {
415 throw new WriteFaultException(addr);
419 /** Created a new non-empty writable page at page number <i>page</i> */
420 private final int[] initPage(int page) { return initPage(page,false); }
421 /** Created a new non-empty page at page number <i>page</i>. If <i>ro</i> is set the page will be read-only */
422 private final int[] initPage(int page, boolean ro) {
423 int[] buf = new int[(1<<pageShift)>>>2];
424 writePages[page] = ro ? null : buf;
425 readPages[page] = buf;
429 /** Returns the exit status of the process. (only valid if state == DONE)
430 @see Runtime#state */
431 public final int exitStatus() {
432 if(state != EXITED) throw new IllegalStateException("exitStatus() called in an inappropriate state");
436 private int addStringArray(String[] strings, int topAddr) throws FaultException {
437 int count = strings.length;
438 int total = 0; /* null last table entry */
439 for(int i=0;i<count;i++) total += strings[i].length() + 1;
440 total += (count+1)*4;
441 int start = (topAddr - total)&~3;
442 int addr = start + (count+1)*4;
443 int[] table = new int[count+1];
445 for(int i=0;i<count;i++) {
446 byte[] a = getBytes(strings[i]);
448 copyout(a,addr,a.length);
449 memset(addr+a.length,0,1);
450 addr += a.length + 1;
453 for(int i=0;i<count+1;i++) {
454 memWrite(addr,table[i]);
457 } catch(FaultException e) {
458 throw new RuntimeException(e.toString());
463 String[] createEnv(String[] extra) { if(extra == null) extra = new String[0]; return extra; }
465 /** Sets word number <i>index</i> in the _user_info table to <i>word</i>
466 * The user_info table is a chunk of memory in the program's memory defined by the
467 * symbol "user_info". The compiler/interpreter automatically determine the size
468 * and location of the user_info table from the ELF symbol table. setUserInfo and
469 * getUserInfo are used to modify the words in the user_info table. */
470 public void setUserInfo(int index, int word) {
471 if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
473 memWrite(userInfoBase()+index*4,word);
474 } catch(FaultException e) { throw new RuntimeException(e.toString()); }
477 /** Returns the word in the _user_info table entry <i>index</i>
478 @see Runtime#setUserInfo(int,int) setUserInfo */
479 public int getUserInfo(int index) {
480 if(index < 0 || index >= userInfoSize()/4) throw new IndexOutOfBoundsException("setUserInfo called with index >= " + (userInfoSize()/4));
482 return memRead(userInfoBase()+index*4);
483 } catch(FaultException e) { throw new RuntimeException(e.toString()); }
486 /** Calls _execute() (subclass's execute()) and catches exceptions */
487 // FEATURE: Have these call kill() so we get a pretty message to stdout
488 private void __execute() {
491 } catch(FaultException e) {
492 if(STDERR_DIAG) e.printStackTrace();
493 sys_exit(128+11); // SIGSEGV
495 } catch(ExecutionException e) {
496 if(STDERR_DIAG) e.printStackTrace();
497 sys_exit(128+4); // SIGILL
502 /** Executes the process until the PAUSE syscall is invoked or the process exits. Returns true if the process exited. */
503 public final boolean execute() {
504 if(state != PAUSED) throw new IllegalStateException("execute() called in inappropriate state");
505 if(startTime == 0) startTime = System.currentTimeMillis();
508 if(state != PAUSED && state != EXITED && state != EXECED)
509 throw new IllegalStateException("execute() ended up in an inappropriate state (" + state + ")");
510 return state != PAUSED;
513 static String[] concatArgv(String argv0, String[] rest) {
514 String[] argv = new String[rest.length+1];
515 System.arraycopy(rest,0,argv,1,rest.length);
520 public final int run() { return run(null); }
521 public final int run(String argv0, String[] rest) { return run(concatArgv(argv0,rest)); }
522 public final int run(String[] args) { return run(args,null); }
524 /** Runs the process until it exits and returns the exit status.
525 If the process executes the PAUSE syscall execution will be paused for 500ms and a warning will be displayed */
526 public final int run(String[] args, String[] env) {
530 if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing run()");
532 if(state == EXECED && STDERR_DIAG) System.err.println("WARNING: Process exec()ed while being run under run()");
533 return state == EXITED ? exitStatus() : 0;
536 public final void start() { start(null); }
537 public final void start(String[] args) { start(args,null); }
539 /** Initializes the process and prepairs it to be executed with execute() */
540 public final void start(String[] args, String[] environ) {
541 int top, sp, argsAddr, envAddr;
542 if(state != STOPPED) throw new IllegalStateException("start() called in inappropriate state");
544 if(args == null) args = new String[]{getClass().getName()};
546 sp = top = writePages.length*(1<<pageShift);
548 sp = argsAddr = addStringArray(args,sp);
549 sp = envAddr = addStringArray(createEnv(environ),sp);
550 } catch(FaultException e) {
551 throw new IllegalArgumentException("args/environ too big");
554 if(top - sp > ARG_MAX) throw new IllegalArgumentException("args/environ too big");
556 // HACK: heapStart() isn't always available when the constructor
557 // is run and this sometimes doesn't get initialized
559 heapEnd = heapStart();
560 if(heapEnd == 0) throw new Error("heapEnd == 0");
561 int pageSize = writePages.length == 1 ? 4096 : (1<<pageShift);
562 heapEnd = (heapEnd + pageSize - 1) & ~(pageSize-1);
565 CPUState cpuState = new CPUState();
566 cpuState.r[A0] = argsAddr;
567 cpuState.r[A1] = envAddr;
569 cpuState.r[RA] = 0xdeadbeef;
570 cpuState.r[GP] = gp();
571 cpuState.pc = entryPoint();
572 setCPUState(cpuState);
579 /** Hook for subclasses to do their own startup */
582 public final int call(String sym, Object[] args) throws CallException, FaultException {
583 if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
584 if(args.length > 7) throw new IllegalArgumentException("args.length > 7");
585 CPUState state = new CPUState();
588 int sp = state.r[SP];
589 int[] ia = new int[args.length];
590 for(int i=0;i<args.length;i++) {
593 if(o instanceof String) {
594 buf = getBytes((String)o);
595 } else if(o instanceof byte[]) {
597 } else if(o instanceof Number) {
598 ia[i] = ((Number)o).intValue();
602 copyout(buf,sp,buf.length);
606 int oldSP = state.r[SP];
607 if(oldSP == sp) return call(sym,ia);
611 int ret = call(sym,ia);
617 public final int call(String sym) throws CallException { return call(sym,new int[]{}); }
618 public final int call(String sym, int a0) throws CallException { return call(sym,new int[]{a0}); }
619 public final int call(String sym, int a0, int a1) throws CallException { return call(sym,new int[]{a0,a1}); }
621 /** Calls a function in the process with the given arguments */
622 public final int call(String sym, int[] args) throws CallException {
623 int func = lookupSymbol(sym);
624 if(func == -1) throw new CallException(sym + " not found");
625 int helper = lookupSymbol("_call_helper");
626 if(helper == -1) throw new CallException("_call_helper not found");
627 return call(helper,func,args);
630 /** Executes the code at <i>addr</i> in the process setting A0-A3 and S0-S3 to the given arguments
631 and returns the contents of V1 when the the pause syscall is invoked */
632 //public final int call(int addr, int a0, int a1, int a2, int a3, int s0, int s1, int s2, int s3) {
633 public final int call(int addr, int a0, int[] rest) throws CallException {
634 if(rest.length > 7) throw new IllegalArgumentException("rest.length > 7");
635 if(state != PAUSED && state != CALLJAVA) throw new IllegalStateException("call() called in inappropriate state");
636 int oldState = state;
637 CPUState saved = new CPUState();
639 CPUState cpustate = saved.dup();
641 cpustate.r[SP] = cpustate.r[SP]&~15;
642 cpustate.r[RA] = 0xdeadbeef;
644 switch(rest.length) {
645 case 7: cpustate.r[S3] = rest[6];
646 case 6: cpustate.r[S2] = rest[5];
647 case 5: cpustate.r[S1] = rest[4];
648 case 4: cpustate.r[S0] = rest[3];
649 case 3: cpustate.r[A3] = rest[2];
650 case 2: cpustate.r[A2] = rest[1];
651 case 1: cpustate.r[A1] = rest[0];
657 setCPUState(cpustate);
659 getCPUState(cpustate);
662 if(state != PAUSED) throw new CallException("Process exit()ed while servicing a call() request");
665 return cpustate.r[V1];
668 /** Allocated an entry in the FileDescriptor table for <i>fd</i> and returns the number.
669 Returns -1 if the table is full. This can be used by subclasses to use custom file
671 public final int addFD(FD fd) {
672 if(state == EXITED || state == EXECED) throw new IllegalStateException("addFD called in inappropriate state");
674 for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
675 if(i==OPEN_MAX) return -1;
677 closeOnExec[i] = false;
681 /** Closes file descriptor <i>fdn</i> and removes it from the file descriptor table */
682 public final boolean closeFD(int fdn) {
683 if(state == EXITED || state == EXECED) throw new IllegalStateException("closeFD called in inappropriate state");
684 if(fdn < 0 || fdn >= OPEN_MAX) return false;
685 if(fds[fdn] == null) return false;
691 /** Duplicates the file descriptor <i>fdn</i> and returns the new fs */
692 public final int dupFD(int fdn) {
694 if(fdn < 0 || fdn >= OPEN_MAX) return -1;
695 if(fds[fdn] == null) return -1;
696 for(i=0;i<OPEN_MAX;i++) if(fds[i] == null) break;
697 if(i==OPEN_MAX) return -1;
698 fds[i] = fds[fdn].dup();
702 public static final int RD_ONLY = 0;
703 public static final int WR_ONLY = 1;
704 public static final int RDWR = 2;
706 public static final int O_CREAT = 0x0200;
707 public static final int O_EXCL = 0x0800;
708 public static final int O_APPEND = 0x0008;
709 public static final int O_TRUNC = 0x0400;
710 public static final int O_NONBLOCK = 0x4000;
711 public static final int O_NOCTTY = 0x8000;
714 FD hostFSOpen(final File f, int flags, int mode, final Object data) throws ErrnoException {
715 if((flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)) != 0) {
717 System.err.println("WARNING: Unsupported flags passed to open(\"" + f + "\"): " + toHex(flags & ~(3|O_CREAT|O_EXCL|O_APPEND|O_TRUNC)));
719 throw new ErrnoException(ENOTSUP);
721 boolean write = (flags&3) != RD_ONLY;
723 if(sm != null && !(write ? sm.allowWrite(f) : sm.allowRead(f))) throw new ErrnoException(EACCES);
725 if((flags & (O_EXCL|O_CREAT)) == (O_EXCL|O_CREAT)) {
727 if(Platform.atomicCreateFile(f)) throw new ErrnoException(EEXIST);
728 } catch(IOException e) {
729 throw new ErrnoException(EIO);
731 } else if(!f.exists()) {
732 if((flags&O_CREAT)==0) return null;
733 } else if(f.isDirectory()) {
734 return hostFSDirFD(f,data);
737 final Seekable.File sf;
739 sf = new Seekable.File(f,write,(flags & O_TRUNC) != 0);
740 } catch(FileNotFoundException e) {
741 if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) throw new ErrnoException(EACCES);
743 } catch(IOException e) { throw new ErrnoException(EIO); }
745 return new SeekableFD(sf,flags) { protected FStat _fstat() { return hostFStat(f,data); } };
748 FStat hostFStat(File f, Object data) { return new HostFStat(f); }
750 FD hostFSDirFD(File f, Object data) { return null; }
752 FD _open(String path, int flags, int mode) throws ErrnoException {
753 return hostFSOpen(new File(path),flags,mode,null);
756 /** The open syscall */
757 private int sys_open(int addr, int flags, int mode) throws ErrnoException, FaultException {
758 String name = cstring(addr);
760 // HACK: TeX, or GPC, or something really sucks
761 if(name.length() == 1024 && getClass().getName().equals("tests.TeX")) name = name.trim();
763 flags &= ~O_NOCTTY; // this is meaningless under nestedvm
764 FD fd = _open(name,flags,mode);
765 if(fd == null) return -ENOENT;
767 if(fdn == -1) { fd.close(); return -ENFILE; }
771 /** The write syscall */
773 private int sys_write(int fdn, int addr, int count) throws FaultException, ErrnoException {
774 count = Math.min(count,MAX_CHUNK);
775 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
776 if(fds[fdn] == null) return -EBADFD;
777 byte[] buf = byteBuf(count);
778 copyin(addr,buf,count);
780 return fds[fdn].write(buf,0,count);
781 } catch(ErrnoException e) {
782 if(e.errno == EPIPE) sys_exit(128+13);
787 /** The read syscall */
788 private int sys_read(int fdn, int addr, int count) throws FaultException, ErrnoException {
789 count = Math.min(count,MAX_CHUNK);
790 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
791 if(fds[fdn] == null) return -EBADFD;
792 byte[] buf = byteBuf(count);
793 int n = fds[fdn].read(buf,0,count);
798 /** The close syscall */
799 private int sys_close(int fdn) {
800 return closeFD(fdn) ? 0 : -EBADFD;
804 /** The seek syscall */
805 private int sys_lseek(int fdn, int offset, int whence) throws ErrnoException {
806 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
807 if(fds[fdn] == null) return -EBADFD;
808 if(whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) return -EINVAL;
809 int n = fds[fdn].seek(offset,whence);
810 return n < 0 ? -ESPIPE : n;
813 /** The stat/fstat syscall helper */
814 int stat(FStat fs, int addr) throws FaultException {
815 memWrite(addr+0,(fs.dev()<<16)|(fs.inode()&0xffff)); // st_dev (top 16), // st_ino (bottom 16)
816 memWrite(addr+4,((fs.type()&0xf000))|(fs.mode()&0xfff)); // st_mode
817 memWrite(addr+8,fs.nlink()<<16|fs.uid()&0xffff); // st_nlink (top 16) // st_uid (bottom 16)
818 memWrite(addr+12,fs.gid()<<16|0); // st_gid (top 16) // st_rdev (bottom 16)
819 memWrite(addr+16,fs.size()); // st_size
820 memWrite(addr+20,fs.atime()); // st_atime
821 // memWrite(addr+24,0) // st_spare1
822 memWrite(addr+28,fs.mtime()); // st_mtime
823 // memWrite(addr+32,0) // st_spare2
824 memWrite(addr+36,fs.ctime()); // st_ctime
825 // memWrite(addr+40,0) // st_spare3
826 memWrite(addr+44,fs.blksize()); // st_bklsize;
827 memWrite(addr+48,fs.blocks()); // st_blocks
828 // memWrite(addr+52,0) // st_spare4[0]
829 // memWrite(addr+56,0) // st_spare4[1]
833 /** The fstat syscall */
834 private int sys_fstat(int fdn, int addr) throws FaultException {
835 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
836 if(fds[fdn] == null) return -EBADFD;
837 return stat(fds[fdn].fstat(),addr);
846 private int sys_gettimeofday(int timevalAddr, int timezoneAddr) throws FaultException {
847 long now = System.currentTimeMillis();
848 int tv_sec = (int)(now / 1000);
849 int tv_usec = (int)((now%1000)*1000);
850 memWrite(timevalAddr+0,tv_sec);
851 memWrite(timevalAddr+4,tv_usec);
855 private int sys_sleep(int sec) {
856 if(sec < 0) sec = Integer.MAX_VALUE;
858 Thread.sleep((long)sec*1000);
860 } catch(InterruptedException e) {
866 #define _CLOCKS_PER_SEC_ 1000
867 #define _CLOCK_T_ unsigned long
875 private int sys_times(int tms) {
876 long now = System.currentTimeMillis();
877 int userTime = (int)((now - startTime)/16);
878 int sysTime = (int)((now - startTime)/16);
882 memWrite(tms+0,userTime);
883 memWrite(tms+4,sysTime);
884 memWrite(tms+8,userTime);
885 memWrite(tms+12,sysTime);
887 } catch(FaultException e) {
893 private int sys_sysconf(int n) {
895 case _SC_CLK_TCK: return 1000;
896 case _SC_PAGESIZE: return writePages.length == 1 ? 4096 : (1<<pageShift);
897 case _SC_PHYS_PAGES: return writePages.length == 1 ? (1<<pageShift)/4096 : writePages.length;
899 if(STDERR_DIAG) System.err.println("WARNING: Attempted to use unknown sysconf key: " + n);
904 /** The sbrk syscall. This can also be used by subclasses to allocate memory.
905 <i>incr</i> is how much to increase the break by */
906 public final int sbrk(int incr) {
907 if(incr < 0) return -ENOMEM;
908 if(incr==0) return heapEnd;
910 int oldEnd = heapEnd;
911 int newEnd = oldEnd + incr;
912 if(newEnd >= stackBottom) return -ENOMEM;
914 if(writePages.length > 1) {
915 int pageMask = (1<<pageShift) - 1;
916 int pageWords = (1<<pageShift) >>> 2;
917 int start = (oldEnd + pageMask) >>> pageShift;
918 int end = (newEnd + pageMask) >>> pageShift;
920 for(int i=start;i<end;i++) readPages[i] = writePages[i] = new int[pageWords];
921 } catch(OutOfMemoryError e) {
922 if(STDERR_DIAG) System.err.println("WARNING: Caught OOM Exception in sbrk: " + e);
930 /** The getpid syscall */
931 private int sys_getpid() { return getPid(); }
932 int getPid() { return 1; }
934 public static interface CallJavaCB { public int call(int a, int b, int c, int d); }
936 private int sys_calljava(int a, int b, int c, int d) {
937 if(state != RUNNING) throw new IllegalStateException("wound up calling sys_calljava while not in RUNNING");
938 if(callJavaCB != null) {
942 ret = callJavaCB.call(a,b,c,d);
943 } catch(RuntimeException e) {
944 System.err.println("Error while executing callJavaCB");
951 if(STDERR_DIAG) System.err.println("WARNING: calljava syscall invoked without a calljava callback set");
956 private int sys_pause() {
961 private int sys_getpagesize() { return writePages.length == 1 ? 4096 : (1<<pageShift); }
963 /** Hook for subclasses to do something when the process exits */
966 private int sys_exit(int status) {
968 for(int i=0;i<fds.length;i++) if(fds[i] != null) closeFD(i);
974 private int sys_fcntl(int fdn, int cmd, int arg) {
977 if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD;
978 if(fds[fdn] == null) return -EBADFD;
983 if(arg < 0 || arg >= OPEN_MAX) return -EINVAL;
984 for(i=arg;i<OPEN_MAX;i++) if(fds[i]==null) break;
985 if(i==OPEN_MAX) return -EMFILE;
991 closeOnExec[fdn] = arg != 0;
994 return closeOnExec[fdn] ? 1 : 0;
996 if(STDERR_DIAG) System.err.println("WARNING: Unknown fcntl command: " + cmd);
1001 /** The syscall dispatcher.
1002 The should be called by subclasses when the syscall instruction is invoked.
1003 <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
1004 the contenst of A0, A1, A2, and A3. The call MAY change the state
1005 @see Runtime#state state */
1006 protected final int syscall(int syscall, int a, int b, int c, int d, int e, int f) {
1008 int n = _syscall(syscall,a,b,c,d,e,f);
1009 //if(n < 0) System.err.println("syscall: " + syscall + " returned " + n);
1011 } catch(ErrnoException ex) {
1012 //ex.printStackTrace();
1014 } catch(FaultException ex) {
1016 } catch(RuntimeException ex) {
1017 ex.printStackTrace();
1018 throw new Error("Internal Error in _syscall()");
1022 int _syscall(int syscall, int a, int b, int c, int d, int e, int f) throws ErrnoException, FaultException {
1024 case SYS_null: return 0;
1025 case SYS_exit: return sys_exit(a);
1026 case SYS_pause: return sys_pause();
1027 case SYS_write: return sys_write(a,b,c);
1028 case SYS_fstat: return sys_fstat(a,b);
1029 case SYS_sbrk: return sbrk(a);
1030 case SYS_open: return sys_open(a,b,c);
1031 case SYS_close: return sys_close(a);
1032 case SYS_read: return sys_read(a,b,c);
1033 case SYS_lseek: return sys_lseek(a,b,c);
1034 case SYS_getpid: return sys_getpid();
1035 case SYS_calljava: return sys_calljava(a,b,c,d);
1036 case SYS_gettimeofday: return sys_gettimeofday(a,b);
1037 case SYS_sleep: return sys_sleep(a);
1038 case SYS_times: return sys_times(a);
1039 case SYS_getpagesize: return sys_getpagesize();
1040 case SYS_fcntl: return sys_fcntl(a,b,c);
1041 case SYS_sysconf: return sys_sysconf(a);
1043 case SYS_memcpy: memcpy(a,b,c); return a;
1044 case SYS_memset: memset(a,b,c); return a;
1055 if(STDERR_DIAG) System.err.println("Attempted to use a UnixRuntime syscall in Runtime (" + syscall + ")");
1058 if(STDERR_DIAG) System.err.println("Attempted to use unknown syscall: " + syscall);
1063 public int xmalloc(int size) { int p=malloc(size); if(p==0) throw new RuntimeException("malloc() failed"); return p; }
1064 public int xrealloc(int addr,int newsize) { int p=realloc(addr,newsize); if(p==0) throw new RuntimeException("realloc() failed"); return p; }
1065 public int realloc(int addr, int newsize) { try { return call("realloc",addr,newsize); } catch(CallException e) { return 0; } }
1066 public int malloc(int size) { try { return call("malloc",size); } catch(CallException e) { return 0; } }
1067 public void free(int p) { try { if(p!=0) call("free",p); } catch(CallException e) { /*noop*/ } }
1069 /** Helper function to create a cstring in main memory */
1070 public int strdup(String s) {
1072 if(s == null) s = "(null)";
1073 byte[] a2 = getBytes(s);
1074 a = new byte[a2.length+1];
1075 System.arraycopy(a2,0,a,0,a2.length);
1076 int addr = malloc(a.length);
1077 if(addr == 0) return 0;
1079 copyout(a,addr,a.length);
1080 } catch(FaultException e) {
1087 /** Helper function to read a cstring from main memory */
1088 public final String cstring(int addr) throws ReadFaultException {
1089 StringBuffer sb = new StringBuffer();
1091 int word = memRead(addr&~3);
1093 case 0: if(((word>>>24)&0xff)==0) return sb.toString(); sb.append((char)((word>>>24)&0xff)); addr++;
1094 case 1: if(((word>>>16)&0xff)==0) return sb.toString(); sb.append((char)((word>>>16)&0xff)); addr++;
1095 case 2: if(((word>>> 8)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 8)&0xff)); addr++;
1096 case 3: if(((word>>> 0)&0xff)==0) return sb.toString(); sb.append((char)((word>>> 0)&0xff)); addr++;
1101 /** File Descriptor class */
1102 public static abstract class FD {
1103 private int refCount = 1;
1105 /** Read some bytes. Should return the number of bytes read, 0 on EOF, or throw an IOException on error */
1106 public int read(byte[] a, int off, int length) throws ErrnoException { throw new ErrnoException(EBADFD); }
1107 /** Write. Should return the number of bytes written or throw an IOException on error */
1108 public int write(byte[] a, int off, int length) throws ErrnoException { throw new ErrnoException(EBADFD); }
1110 /** Seek in the filedescriptor. Whence is SEEK_SET, SEEK_CUR, or SEEK_END. Should return -1 on error or the new position. */
1111 public int seek(int n, int whence) throws ErrnoException { return -1; }
1113 public int getdents(byte[] a, int off, int length) throws ErrnoException { throw new ErrnoException(EBADFD); }
1115 public int flags() { return O_RDONLY; }
1117 /** Return a Seekable object representing this file descriptor (can be read only)
1118 This is required for exec() */
1119 Seekable seekable() { return null; }
1121 private FStat cachedFStat = null;
1122 public final FStat fstat() {
1123 if(cachedFStat == null) cachedFStat = _fstat();
1127 protected abstract FStat _fstat();
1129 /** Closes the fd */
1130 public final void close() { if(--refCount==0) _close(); }
1131 protected void _close() { /* noop*/ }
1133 FD dup() { refCount++; return this; }
1136 /** FileDescriptor class for normal files */
1137 public abstract static class SeekableFD extends FD {
1138 private final int flags;
1139 private final Seekable data;
1141 SeekableFD(Seekable data, int flags) { this.data = data; this.flags = flags; }
1143 protected abstract FStat _fstat();
1144 public int flags() { return flags; }
1146 Seekable seekable() { return data; }
1148 public int seek(int n, int whence) throws ErrnoException {
1151 case SEEK_SET: break;
1152 case SEEK_CUR: n += data.pos(); break;
1153 case SEEK_END: n += data.length(); break;
1158 } catch(IOException e) {
1159 throw new ErrnoException(ESPIPE);
1163 public int write(byte[] a, int off, int length) throws ErrnoException {
1164 if((flags&3) == RD_ONLY) throw new ErrnoException(EBADFD);
1165 // NOTE: There is race condition here but we can't fix it in pure java
1166 if((flags&O_APPEND) != 0) seek(0,SEEK_END);
1168 return data.write(a,off,length);
1169 } catch(IOException e) {
1170 throw new ErrnoException(EIO);
1174 public int read(byte[] a, int off, int length) throws ErrnoException {
1175 if((flags&3) == WR_ONLY) throw new ErrnoException(EBADFD);
1177 int n = data.read(a,off,length);
1178 return n < 0 ? 0 : n;
1179 } catch(IOException e) {
1180 throw new ErrnoException(EIO);
1184 protected void _close() { try { data.close(); } catch(IOException e) { /*ignore*/ } }
1187 public static class InputOutputStreamFD extends FD {
1188 private final InputStream is;
1189 private final OutputStream os;
1191 public InputOutputStreamFD(InputStream is) { this(is,null); }
1192 public InputOutputStreamFD(OutputStream os) { this(null,os); }
1193 public InputOutputStreamFD(InputStream is, OutputStream os) {
1196 if(is == null && os == null) throw new IllegalArgumentException("at least one stream must be supplied");
1199 public int flags() {
1200 if(is != null && os != null) return O_RDWR;
1201 if(is != null) return O_RDONLY;
1202 if(os != null) return O_WRONLY;
1203 throw new Error("should never happen");
1206 public void _close() {
1207 if(is != null) try { is.close(); } catch(IOException e) { /*ignore*/ }
1208 if(os != null) try { os.close(); } catch(IOException e) { /*ignore*/ }
1211 public int read(byte[] a, int off, int length) throws ErrnoException {
1212 if(is == null) return super.read(a,off,length);
1214 int n = is.read(a,off,length);
1215 return n < 0 ? 0 : n;
1216 } catch(IOException e) {
1217 throw new ErrnoException(EIO);
1221 public int write(byte[] a, int off, int length) throws ErrnoException {
1222 if(os == null) return super.write(a,off,length);
1224 os.write(a,off,length);
1226 } catch(IOException e) {
1227 throw new ErrnoException(EIO);
1231 public FStat _fstat() { return new FStat(); }
1234 static class TerminalFD extends InputOutputStreamFD {
1235 public TerminalFD(InputStream is) { this(is,null); }
1236 public TerminalFD(OutputStream os) { this(null,os); }
1237 public TerminalFD(InputStream is, OutputStream os) { super(is,os); }
1238 public void _close() { /* noop */ }
1239 public FStat _fstat() { return new FStat() { public int type() { return S_IFCHR; } public int mode() { return 0600; } }; }
1242 // This is pretty inefficient but it is only used for reading from the console on win32
1243 static class TextInputStream extends InputStream {
1244 private int pushedBack = -1;
1245 private final InputStream parent;
1246 public TextInputStream(InputStream parent) { this.parent = parent; }
1247 public int read() throws IOException {
1248 if(pushedBack != -1) { int c = pushedBack; pushedBack = -1; return c; }
1249 int c = parent.read();
1250 if(c == '\r' && (c = parent.read()) != '\n') { pushedBack = c; return '\r'; }
1253 public int read(byte[] buf, int pos, int len) throws IOException {
1255 if(pushedBack != -1 && len > 0) {
1256 buf[0] = (byte) pushedBack;
1258 pos++; len--; pb = true;
1260 int n = parent.read(buf,pos,len);
1261 if(n == -1) return -1;
1262 for(int i=0;i<n;i++) {
1263 if(buf[pos+i] == '\r') {
1265 int c = parent.read();
1266 if(c == '\n') buf[pos+i] = '\n';
1267 else pushedBack = c;
1268 } else if(buf[pos+i+1] == '\n') {
1269 System.arraycopy(buf,pos+i+1,buf,pos+i,len-i-1);
1274 return n + (pb ? 1 : 0);
1278 public static class FStat {
1279 public static final int S_IFIFO = 0010000;
1280 public static final int S_IFCHR = 0020000;
1281 public static final int S_IFDIR = 0040000;
1282 public static final int S_IFREG = 0100000;
1284 public int dev() { return 1; }
1285 public int inode() { return hashCode() & 0x7fff; }
1286 public int mode() { return 0; }
1287 public int type() { return S_IFIFO; }
1288 public int nlink() { return 0; }
1289 public int uid() { return 0; }
1290 public int gid() { return 0; }
1291 public int size() { return 0; }
1292 public int atime() { return 0; }
1293 public int mtime() { return 0; }
1294 public int ctime() { return 0; }
1295 public int blksize() { return 512; }
1296 public int blocks() { return (size()+blksize()-1)/blksize(); }
1299 static class HostFStat extends FStat {
1300 private final File f;
1301 private final boolean executable;
1302 public HostFStat(File f) { this(f,false); }
1303 public HostFStat(File f, boolean executable) {
1305 this.executable = executable;
1307 public int dev() { return 1; }
1308 public int inode() { return f.getName().hashCode() & 0xffff; }
1309 public int type() { return f.isDirectory() ? S_IFDIR : S_IFREG; }
1310 public int nlink() { return 1; }
1313 boolean canread = f.canRead();
1314 if(canread && (executable || f.isDirectory())) mode |= 0111;
1315 if(canread) mode |= 0444;
1316 if(f.canWrite()) mode |= 0222;
1319 public int size() { return (int) f.length(); }
1320 public int mtime() { return (int)(f.lastModified()/1000); }
1324 public static class ReadFaultException extends FaultException {
1325 public ReadFaultException(int addr) { super(addr); }
1327 public static class WriteFaultException extends FaultException {
1328 public WriteFaultException(int addr) { super(addr); }
1330 public static class FaultException extends ExecutionException {
1331 public final int addr;
1332 public final RuntimeException cause;
1333 public FaultException(int addr) { super("fault at: " + toHex(addr)); this.addr = addr; cause = null; }
1334 public FaultException(RuntimeException e) { super(e.toString()); addr = -1; cause = e; }
1336 public static class ExecutionException extends Exception {
1337 private String message = "(null)";
1338 private String location = "(unknown)";
1339 public ExecutionException() { /* noop */ }
1340 public ExecutionException(String s) { if(s != null) message = s; }
1341 void setLocation(String s) { location = s == null ? "(unknown)" : s; }
1342 public final String getMessage() { return message + " at " + location; }
1344 public static class CallException extends Exception {
1345 public CallException(String s) { super(s); }
1348 protected static class ErrnoException extends Exception {
1350 public ErrnoException(int errno) { super("Errno: " + errno); this.errno = errno; }
1354 protected static class CPUState {
1355 public CPUState() { /* noop */ }
1357 public int[] r = new int[32];
1358 /* Floating point regs */
1359 public int[] f = new int[32];
1364 public CPUState dup() {
1365 CPUState c = new CPUState();
1370 for(int i=0;i<32;i++) {
1378 public static class SecurityManager {
1379 public boolean allowRead(File f) { return true; }
1380 public boolean allowWrite(File f) { return true; }
1381 public boolean allowStat(File f) { return true; }
1382 public boolean allowUnlink(File f) { return true; }
1385 // Null pointer check helper function
1386 protected final void nullPointerCheck(int addr) throws ExecutionException {
1388 throw new ExecutionException("Attempted to dereference a null pointer " + toHex(addr));
1391 // Utility functions
1392 byte[] byteBuf(int size) {
1393 if(_byteBuf==null) _byteBuf = new byte[size];
1394 else if(_byteBuf.length < size)
1395 _byteBuf = new byte[min(max(_byteBuf.length*2,size),MAX_CHUNK)];
1399 static String getSystemProperty(String key) {
1401 return System.getProperty(key);
1402 } catch(SecurityException e) {
1407 /** Decode a packed string */
1408 protected static final int[] decodeData(String s, int words) {
1409 if(s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
1410 if((s.length() / 8) * 7 < words*4) throw new IllegalArgumentException("string isn't big enough");
1411 int[] buf = new int[words];
1412 int prev = 0, left=0;
1413 for(int i=0,n=0;n<words;i+=8) {
1415 for(int j=0;j<8;j++) { l <<= 7; l |= s.charAt(i+j) & 0x7f; }
1416 if(left > 0) buf[n++] = prev | (int)(l>>>(56-left));
1417 if(n < words) buf[n++] = (int) (l >>> (24-left));
1418 left = (left + 8) & 0x1f;
1419 prev = (int)(l << left);
1424 static byte[] getBytes(String s) {
1426 return s.getBytes("ISO-8859-1");
1427 } catch(UnsupportedEncodingException e) {
1428 return null; // should never happen
1432 static byte[] getNullTerminatedBytes(String s) {
1433 byte[] buf1 = getBytes(s);
1434 byte[] buf2 = new byte[buf1.length+1];
1435 System.arraycopy(buf1,0,buf2,0,buf1.length);
1439 final static String toHex(int n) { return "0x" + Long.toString(n & 0xffffffffL, 16); }
1440 final static int min(int a, int b) { return a < b ? a : b; }
1441 final static int max(int a, int b) { return a > b ? a : b; }