78b4e9adf142da1a57d9e27847365d0c8881ea00
[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     // FEATURE: Do we need to periodicly create a new classloader to allow old clases to be GCed?
10     private static SingleClassLoader singleClassLoader = new SingleClassLoader();
11     // FEATURE: Is it ok if this overflows?
12     private static long nextID = 1;
13     private static synchronized String uniqueID() { return Long.toString(nextID++); }
14     
15     public static Class compile(Seekable data) throws IOException, Compiler.Exn {
16         String className = "nextedvm.runtimecompiled_" + uniqueID();
17         System.err.println("RuntimeCompiler: Building " + className);
18         ByteArrayOutputStream baos = new ByteArrayOutputStream();
19         ClassFileCompiler c = new ClassFileCompiler(data,className,baos);
20         // FEATURE: make this Optional, pass options on compile arguments
21         c.parseOptions("unixruntime");
22         c.go();
23         baos.close();
24         byte[] bytecode = baos.toByteArray();
25         return singleClassLoader.fromBytes(className,bytecode);
26     }
27     
28     private static class SingleClassLoader extends ClassLoader {
29         public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
30                 System.err.println(this + ": loadClass(\"" + name + "," + resolve + ");");
31             return super.loadClass(name,resolve);
32         }
33         public Class fromBytes(String name, byte[] b) { return fromBytes(name,b,0,b.length); }
34         public Class fromBytes(String name, byte[] b, int off, int len) {
35             Class c = super.defineClass(name,b,off,len);
36             resolveClass(c);
37             return c;
38         }
39     }
40     
41     public static void main(String[] args) throws Exception {
42             if(args.length == 0) {
43                     System.err.println("Usage: RuntimeCompiler mipsbinary");
44             System.exit(1);
45         }
46         UnixRuntime r = (UnixRuntime) compile(new Seekable.File(args[0])).newInstance();
47         System.err.println("Instansiated: "+ r);
48         System.exit(r.run(args));
49     }
50     
51     private RuntimeCompiler() { }
52 }