nextedvm typo
[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 SingleClassLoader singleClassLoader;
10     private static int nextID;
11     
12     public static Class compile(Seekable data) throws IOException, Compiler.Exn { return compile(data,null); }
13     public static Class compile(Seekable data, String extraoptions) throws IOException, Compiler.Exn {
14         int id;
15         synchronized(RuntimeCompiler.class) {
16             if(nextID == 32 || singleClassLoader == null) {
17                 singleClassLoader = new SingleClassLoader();
18                 nextID = 0;
19             }
20             id = nextID++;
21         }
22         String className = "nestedvm.runtimecompiled_" + id;
23         System.err.println("RuntimeCompiler: Building " + className);
24         String options = "nosupportcall";
25         if(extraoptions != null) options += "," + extraoptions;
26         ByteArrayOutputStream baos = new ByteArrayOutputStream();
27         ClassFileCompiler c = new ClassFileCompiler(data,className,baos);
28         c.parseOptions(options);
29         c.go();
30         baos.close();
31         byte[] bytecode = baos.toByteArray();
32         return singleClassLoader.fromBytes(className,bytecode);
33     }
34     
35     private static class SingleClassLoader extends ClassLoader {
36         public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
37             //System.err.println(this + ": loadClass(\"" + name + "," + resolve + ");");
38             return super.loadClass(name,resolve);
39         }
40         public Class fromBytes(String name, byte[] b) { return fromBytes(name,b,0,b.length); }
41         public Class fromBytes(String name, byte[] b, int off, int len) {
42             Class c = super.defineClass(name,b,off,len);
43             resolveClass(c);
44             return c;
45         }
46     }
47     
48     public static void main(String[] args) throws Exception {
49         if(args.length == 0) {
50             System.err.println("Usage: RuntimeCompiler mipsbinary");
51             System.exit(1);
52         }
53         UnixRuntime r = (UnixRuntime) compile(new Seekable.File(args[0]),"unixruntime").newInstance();
54         System.err.println("Instansiated: "+ r);
55         System.exit(UnixRuntime.runAndExec(r,args));
56     }
57     
58     private RuntimeCompiler() { }
59 }