runtimecompiler
[nestedvm.git] / src / org / ibex / nestedvm / RuntimeCompiler.java
1 package org.ibex.nestedvm;
2
3 import java.io.*;
4
5 import org.ibex.nestedvm.util.*;
6
7 // FEATURE: This need a lot of work to support binaries spanned across many classes
8 public class RuntimeCompiler {          
9     private static final SingleClassLoader singleClassLoader = new SingleClassLoader();
10     // FEATURE: Is it ok if this overflows?
11     private static long nextID = 1;
12     private static synchronized String uniqueID() { return Long.toString(nextID++); }
13     
14     public static Class compile(Seekable data) throws IOException, Compiler.Exn {
15         String className = "nextedvm.runtimecompiled_" + uniqueID();
16         System.err.println("RuntimeCompiler: Building " + className);
17         ByteArrayOutputStream baos = new ByteArrayOutputStream();
18         ClassFileCompiler c = new ClassFileCompiler(data,className,baos);
19         // FEATURE: make this Optional, pass options on compile arguments
20         c.parseOptions("unixruntime");
21         c.go();
22         baos.close();
23         byte[] bytecode = baos.toByteArray();
24         return singleClassLoader.fromBytes(className,bytecode);
25     }
26     
27     private static class SingleClassLoader extends ClassLoader {
28         public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
29                     System.err.println(this + ": loadClass(\"" + name + "," + resolve + ");");
30             return super.loadClass(name,resolve);
31         }
32         public Class fromBytes(String name, byte[] b) { return fromBytes(name,b,0,b.length); }
33         public Class fromBytes(String name, byte[] b, int off, int len) {
34             Class c = super.defineClass(name,b,off,len);
35             resolveClass(c);
36             return c;
37         }
38     }
39     
40     public static void main(String[] args) throws Exception {
41             if(args.length == 0) {
42                     System.err.println("Usage: RuntimeCompiler mipsbinary");
43             System.exit(1);
44         }
45         UnixRuntime r = (UnixRuntime) compile(new Seekable.File(args[0])).newInstance();
46         System.err.println("Instansiated: "+ r);
47         System.exit(r.run(args));
48     }
49     
50     private RuntimeCompiler() { }
51 }