native builds are fixed
[org.ibex.core.git] / src / org / ibex / util / NanoGoat.java
1 package org.ibex.util;
2 import java.util.*;
3 import java.io.*;
4 import java.util.zip.*;
5 import org.apache.bcel.*;
6 import org.apache.bcel.generic.*;
7 import org.apache.bcel.classfile.*;
8 import org.apache.bcel.util.*;
9
10 public class NanoGoat {
11
12     public static final boolean deleteMethods = false;
13     public static SyntheticRepository repo = null;
14     public static HashSet dest = new HashSet();
15     public static HashSet constructed = new HashSet();
16     public static String outdir = ".";
17     public static Hashtable subclasses = new Hashtable();
18     public static Hashtable uponconstruction = new Hashtable();
19     public static Hashtable mark_if_constructed = new Hashtable();
20     public static int level = 0;
21
22     public NanoGoat() { }
23
24     public void loadAllMethods(String classname) throws Exception {
25         visitJavaClass(repo.loadClass(classname));
26         Method[] meths = getMethods(repo.loadClass(classname));
27         for(int i=0; i<meths.length; i++)
28             visitJavaMethod(repo.loadClass(classname), meths[i]);
29     }
30
31     public void loadAllStaticMethods(String classname) throws Exception {
32         visitJavaClass(repo.loadClass(classname));
33         Method[] meths = getMethods(repo.loadClass(classname));
34         for(int i=0; i<meths.length; i++)
35             if (meths[i].isStatic())
36                 visitJavaMethod(repo.loadClass(classname), meths[i]);
37     }
38
39     public void loadMethod(String classAndMethodName) throws Exception {
40         String classname = classAndMethodName.substring(0, classAndMethodName.lastIndexOf('.'));
41         String methodname = classAndMethodName.substring(classAndMethodName.lastIndexOf('.') + 1);
42         if (classname.endsWith("." + methodname)) methodname = "<init>";
43         visitJavaClass(repo.loadClass(classname));
44         Method[] meths = getMethods(repo.loadClass(classname));
45         for(int i=0; i<meths.length; i++)
46             if (meths[i].getName().equals(methodname))
47                 visitJavaMethod(repo.loadClass(classname), meths[i]);
48     }
49     public static void main(String[] args) throws Exception {
50         int start = 1;
51         repo = SyntheticRepository.getInstance(new ClassPath(args[0]));
52
53         NanoGoat bcp = new NanoGoat();
54         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
55         for(String s = br.readLine(); s != null; s = br.readLine()) {
56             try {
57                 if (s.endsWith(".class")) {
58                     bcp.visitJavaClass(repo.loadClass(s.substring(0, s.length() - 6)));
59                 } else {
60                     JavaClass cl = repo.loadClass(s.substring(0, s.lastIndexOf('.')));;
61                     bcp.visitJavaClass(cl);
62                     bcp.loadMethod(s);
63                     Field[] fields = cl.getFields();
64                     for(int j=0; j<fields.length; j++) {
65                         if (fields[j].getName().equals(s.substring(s.lastIndexOf('.') + 1)))
66                             bcp.visitJavaField(fields[j], cl);
67                     }
68                 }
69             } catch (Exception e) {
70                 System.out.println("WARNING: couldn't load class for " + s);
71                 e.printStackTrace();
72             }
73         }
74
75         System.out.println("\n\n======================================================================\n");
76
77         // we call start(), but the VM calls run()...
78         bcp.loadMethod("java.lang.Thread.run");
79         bcp.loadAllMethods("java.lang.SecurityContext");
80         bcp.loadAllMethods("java.lang.ThreadDeath");
81         bcp.loadMethod("java.lang.Thread.run");                  // we call start(), but the VM calls run()...
82         bcp.loadMethod("java.lang.ref.Reference.enqueue");       // the GC calls this directly
83         bcp.loadAllMethods("gnu.gcj.runtime.StringBuffer");      // the compiler emits calls directly to this class
84         bcp.loadAllMethods("gnu.gcj.convert.Input_UTF8");        // retrieved via reflection
85         bcp.loadAllMethods("gnu.gcj.convert.Output_UTF8");       // retrieved via reflection
86         bcp.loadMethod("gnu.gcj.convert.BytesToUnicode.done");   // called by natString
87         bcp.loadAllStaticMethods("java.lang.reflect.Modifier");        // used all over natClass...
88
89         // the Interpreter.run() method's switchblock is too complex...
90         bcp.loadAllMethods("org.ibex.js.Interpreter$TryMarker");
91         bcp.loadAllMethods("org.ibex.js.Interpreter$CatchMarker");
92         bcp.loadAllMethods("org.ibex.js.Interpreter$LoopMarker");
93         bcp.loadAllMethods("org.ibex.js.Interpreter$FinallyData");
94         bcp.loadAllMethods("org.ibex.js.Interpreter$CallMarker");
95         bcp.loadAllMethods("org.ibex.js.Interpreter");
96         bcp.loadAllMethods("org.ibex.js.Interpreter$1");
97         bcp.loadAllMethods("org.ibex.js.Interpreter$Stub");
98         bcp.loadAllMethods("org.ibex.js.Trap$TrapScope");
99         bcp.loadMethod("org.ibex.js.JSScope.top");
100         bcp.loadAllMethods("org.ibex.Picture$1");
101         bcp.loadAllMethods("org.ibex.Ibex$Blessing");
102         bcp.loadAllMethods("org.ibex.util.SSL$entropySpinner");
103         bcp.loadAllMethods("org.ibex.HTTP$HTTPInputStream");
104         bcp.visitJavaClass(repo.loadClass("org.ibex.util.SSL"));
105
106         bcp.loadAllMethods("java.util.Hashtable$HashIterator");
107         bcp.loadMethod("java.util.SimpleTimeZone.useDaylightTime");
108         bcp.visitJavaClass(repo.loadClass("gnu.gcj.runtime.FinalizerThread"));
109         bcp.visitJavaClass(repo.loadClass("gnu.gcj.runtime.FirstThread"));
110
111         // to ensure we get all the stuff that might be called from CNI
112         bcp.loadAllMethods("org.ibex.plat.Linux");
113         bcp.loadAllMethods("org.ibex.plat.X11");
114         bcp.loadAllMethods("org.ibex.plat.GCJ");
115         bcp.loadAllMethods("org.ibex.plat.POSIX");
116         bcp.loadAllMethods("org.ibex.plat.X11$X11Surface");
117         bcp.loadAllMethods("org.ibex.plat.X11$X11PixelBuffer");
118         bcp.loadAllMethods("org.ibex.plat.X11$X11Picture");
119         bcp.loadAllMethods("org.ibex.Surface");
120         bcp.loadAllMethods("org.ibex.Picture");
121         bcp.loadAllMethods("org.ibex.PixelBuffer");
122
123         // primary entry point
124         bcp.loadMethod("org.ibex.plat.Linux.main");
125         System.out.println();
126
127         System.out.println("Dumping...");
128         ZipFile zf = new ZipFile(args[0]);
129         ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(args[0] + ".tmp"));
130         Enumeration e = zf.entries();
131         while(e.hasMoreElements()) {
132             ZipEntry ze = ((ZipEntry)e.nextElement());
133             String ss = ze.getName();
134             if (!ss.endsWith(".class")) continue;
135             ss = ss.substring(0, ss.length() - 6);
136             ss = ss.replace('/', '.');
137             dump(repo.loadClass(ss), zos);
138         }
139         zos.close();
140         zf.close();
141         new File(args[0] + ".tmp").renameTo(new File(args[0] + ".pruned"));
142     }
143
144     public static void dump(JavaClass clazz, ZipOutputStream zos) throws Exception {
145         if (!dest.contains(clazz)) return;
146
147         ConstantPoolGen newcpg = new ConstantPoolGen(clazz.getConstantPool());
148         ClassGen cg = new ClassGen(clazz);
149         InstructionFactory factory = new InstructionFactory(cg, newcpg);
150         cg.setMajor(46);
151         cg.setMinor(0);
152         cg.setConstantPool(newcpg);
153
154         boolean isconstructed = false;
155         Method[] methods = getMethods(clazz);
156         for(int i=0; i<methods.length; i++)
157             if (dest.contains(methods[i]) && methods[i].getName().equals("<init>"))
158                 isconstructed = true;
159
160         // we can only prune static fields (to avoid altering object layout, which is hardcoded into
161         // CNI code), but that's okay since instance fields don't contribute to binary size
162         Field[] fields = clazz.getFields();
163         for(int i=0; i<fields.length; i++) {
164             if ((!dest.contains(fields[i]) && fields[i].isStatic()) ||
165                 ((!(constructed.contains(clazz))) && !fields[i].isStatic())) { 
166                 System.out.println("  pruning field " + clazz.getClassName() + "." + fields[i].getName());
167                 // FIXME this confuses gcj in jar-at-a-time mode
168                 //cg.removeField(fields[i]);
169             }
170         }
171
172         int numMethods = 0;
173         boolean good = false;
174         for(int i=0; i<methods.length; i++) {
175             if (dest.contains(methods[i]) && (isconstructed || methods[i].isStatic())) {
176                 good = true;
177             } else {
178                 if (methods[i].getCode() == null) {
179                     System.out.println("  empty codeblock: " + clazz.getClassName() + "." + methods[i].getName());
180                 } else {
181                     System.out.println("  pruning " +(isconstructed?"":"unconstructed")+ " method " +
182                                        clazz.getClassName() + "." + methods[i].getName());
183                     if (deleteMethods) { cg.removeMethod(methods[i]); continue; }
184                     MethodGen mg = new MethodGen(methods[i], clazz.getClassName(), newcpg);
185                     mg.removeExceptions();
186                     InstructionList il = new InstructionList();
187                     mg.setInstructionList(il);
188                     InstructionHandle ih_0 = il.append(factory.createNew("java.lang.UnsatisfiedLinkError"));
189                     il.append(InstructionConstants.DUP);
190                     il.append(factory.createInvoke("java.lang.UnsatisfiedLinkError",
191                                                    "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
192                     il.append(InstructionConstants.ATHROW);
193                     mg.setMaxStack();
194                     mg.setMaxLocals();
195                     mg.removeExceptions();
196                     mg.removeLocalVariables();
197                     mg.removeExceptionHandlers();
198                     mg.removeLineNumbers();
199                     cg.replaceMethod(methods[i], mg.getMethod());
200                     il.dispose();
201                 }
202             }
203         }
204
205         // FIXME: chain up to superclass' <clinit>... that might remove the need for this hack
206         // FIXME: gcj compiling in jar-at-a-time mode can't be convinced to let classes outside the jar override
207         //        the ones inside the jar
208         good = true;
209
210         if (!good && !clazz.isAbstract() && !clazz.isInterface()) {
211             System.out.println("DROPPING " + clazz.getClassName());
212             JavaClass[] ifaces = clazz.getInterfaces();
213             String[] ifacestrings = new String[ifaces.length];
214             for(int i=0; i<ifaces.length; i++) ifacestrings[i] = ifaces[i].getClassName();
215             cg = new ClassGen(clazz.getClassName(),
216                               clazz.getSuperClass().getClassName(),
217                               clazz.getFileName(),
218                               clazz.getAccessFlags(),
219                               ifacestrings,
220                               newcpg);
221         } else {
222             System.out.println("dumping " + clazz.getClassName());
223         }
224         FilterOutputStream noclose = new FilterOutputStream(zos) { public void close() throws IOException { flush(); } };
225         zos.putNextEntry(new ZipEntry(clazz.getClassName().replace('.', '/')+".class"));
226         cg.getJavaClass().dump(noclose);
227         noclose.flush();
228     }
229
230     public JavaClass sig2class(String sig) throws Exception {
231         if (sig == null) return null;
232         while (sig.length() > 0 && (sig.charAt(0) == 'L' || sig.charAt(0) == '[')) {
233             if (sig.charAt(0) == 'L') sig = sig.substring(1, sig.length() - 1);
234             else if (sig.charAt(0) == '[') sig = sig.substring(1, sig.length());
235         }
236         if (sig.length() <= 1) return null;
237         if (sig.equals("<null object>")) return null;
238         if (sig.startsWith("<return address")) return null;
239         return repo.loadClass(sig);
240     }
241     public void load(String sig) throws Exception {
242         if (sig == null) return;
243         while (sig.length() > 0 && (sig.charAt(0) == 'L' || sig.charAt(0) == '[')) {
244             if (sig.charAt(0) == 'L') sig = sig.substring(1, sig.length() - 1);
245             else if (sig.charAt(0) == '[') sig = sig.substring(1, sig.length());
246         }
247         if (sig.length() <= 1) return;
248         if (sig.equals("<null object>")) return;
249         if (sig.startsWith("<return address")) return;
250         visitJavaClass(repo.loadClass(sig));
251     }
252     public void load(Type t) throws Exception {
253         if (t == null) return;
254         if (t instanceof ArrayType) load(((ArrayType)t).getElementType());
255         if (!(t instanceof ObjectType)) return;
256         load(((ObjectType)t).getClassName());
257     }
258
259     public String getMethodSignature(Method m, ConstantPoolGen cpg) throws Exception { return m.getName() + m.getSignature(); }
260     public String getMethodSignature(InvokeInstruction ii, ConstantPoolGen cpg) throws Exception {
261         String sig = "";
262         Type[] argtypes = ii.getArgumentTypes(cpg);
263         for(int j=0; j<argtypes.length; j++) sig += argtypes[j].getSignature();
264         return ii.getMethodName(cpg) + "(" + sig + ")" + ii.getReturnType(cpg).getSignature();
265     }
266
267     public void visitJavaMethod(JavaClass jc, Method method) throws Exception {
268         visitJavaClass(jc);
269         if (jc.getClassName().indexOf("SharedLib") != -1) return;
270         if (jc.getClassName().indexOf("Datagram") != -1) return;
271         if (jc.getClassName().startsWith("java.io.Object")) return;
272         if (jc.getClassName().startsWith("java.util.jar.")) return;
273         if (jc.getClassName().startsWith("java.net.Inet6")) return;
274
275         // gcj bug; gcj can't compile this method from a .class file input; I have no idea why
276         if (jc.getClassName().equals("java.lang.System") && method.getName().equals("runFinalizersOnExit")) return;
277
278         // we know these can't be constructed
279         if (method.getName().equals("<init>") && jc.getClassName().startsWith("java.lang.reflect.")) return;
280
281         if (dest.contains(method)) return;
282         dest.add(method);
283
284         if (method.getName().equals("<clinit>") && jc.getSuperClass() != null)
285             loadMethod(jc.getSuperClass().getClassName() + ".<clinit>");
286
287         if (method.isStatic() || method.getName().equals("<init>")) loadMethod(jc.getClassName() + ".<clinit>");
288         if (method.getName().equals("<init>")) {
289             // FIXME: generalize to all perinstancemethods
290             constructed.add(jc);
291             HashSet hs = (HashSet)uponconstruction.get(jc);
292             if (hs != null) {
293                 Iterator it = hs.iterator();
294                 while(it.hasNext()) visitJavaMethod(jc, (Method)it.next());
295             }
296             loadMethod(jc.getClassName() + ".equals");
297             loadMethod(jc.getClassName() + ".hashCode");
298             loadMethod(jc.getClassName() + ".toString");
299             loadMethod(jc.getClassName() + ".finalize");
300             loadMethod(jc.getClassName() + ".clone");
301         }
302
303         ConstantPoolGen cpg = new ConstantPoolGen(method.getConstantPool());
304         if (!method.isStatic() && !constructed.contains(jc)) {
305             HashSet hs = (HashSet)uponconstruction.get(jc);
306             if (hs == null) uponconstruction.put(jc, hs = new HashSet());
307             hs.add(method);
308             markMethodInSubclasses(jc, method, cpg);
309             dest.remove(method);
310             return;
311         }
312
313         level += 2;
314         for(int i=0; i<level; i++) System.out.print(" ");
315         System.out.print(jc.getClassName() + "." + getMethodSignature(method, cpg));
316         markMethodInSubclasses(jc, method, cpg);
317         if (method.getCode() == null) { System.out.println(); level -= 2; return; }
318         byte[] code = method.getCode().getCode();
319         InstructionList il = new InstructionList(code);
320         InstructionHandle[] instructions = il.getInstructionHandles();
321         System.out.println(" [" + instructions.length + " instructions]");
322         for(int i=0; i<instructions.length; i++){ 
323             Instruction instr = instructions[i].getInstruction();;
324             if (instr instanceof Select) {
325                 InstructionHandle[] ih2 = ((Select)instr).getTargets();
326                 InstructionHandle[] ih3 = new InstructionHandle[instructions.length + ih2.length];
327                 System.arraycopy(instructions, 0, ih3, 0, instructions.length);
328                 System.arraycopy(ih2, 0, ih3, instructions.length, ih2.length);
329                 instructions = ih3;
330             }
331             if (instr instanceof LoadClass) {
332                 ObjectType ot = (ObjectType)((LoadClass)instr).getLoadClassType(cpg);
333                 if (ot != null) loadMethod(ot.getClassName() + ".<clinit>");
334             }
335             if (instr instanceof CPInstruction) load(((CPInstruction)instr).getType(cpg));
336             if (instr instanceof TypedInstruction) load(((TypedInstruction)instr).getType(cpg));
337             if (instr instanceof NEW) loadMethod(((NEW)instr).getLoadClassType(cpg).getClassName() + ".<init>");
338             if (instr instanceof org.apache.bcel.generic.FieldOrMethod)
339                 load(((org.apache.bcel.generic.FieldOrMethod)instr).getClassType(cpg));
340             if (instr instanceof org.apache.bcel.generic.FieldInstruction) {
341                 load(((org.apache.bcel.generic.FieldInstruction)instr).getFieldType(cpg));
342                 load(((org.apache.bcel.generic.FieldInstruction)instr).getType(cpg));
343                 String fieldName = ((org.apache.bcel.generic.FieldInstruction)instr).getFieldName(cpg);
344                 JavaClass jc2 = repo.loadClass(((ObjectType)((org.apache.bcel.generic.FieldInstruction)instr).
345                                                 getLoadClassType(cpg)).getClassName());
346                 Field[] fields = jc2.getFields();
347                 for(int j=0; j<fields.length; j++) if (fields[j].getName().equals(fieldName)) visitJavaField(fields[j], jc2);
348             }
349             if (instr instanceof InvokeInstruction) {
350                 InvokeInstruction ii = (InvokeInstruction)instr;
351                 String ii_sig = getMethodSignature(ii, cpg);
352                 JavaClass c = sig2class(ii.getLoadClassType(cpg).getSignature());
353
354                 load(ii.getType(cpg));
355                 Method[] meths = getMethods(c);
356                 boolean good = false;
357                 for(int i2=0; i2<meths.length; i2++) {
358                     if (getMethodSignature(meths[i2], cpg).equals(ii_sig)) {
359                         visitJavaMethod(c, meths[i2]);
360                         good = true;
361                         break;
362                     }
363                 } 
364                 if (!good) throw new Exception("couldn't find method " + getMethodSignature(ii, cpg) + " in " + c.getClassName());
365             }
366         }
367         Type[] argtypes = method.getArgumentTypes();
368         for(int i=0; i<argtypes.length; i++) load(argtypes[i]);
369         if (method.getExceptionTable() != null) {
370             String[] exntypes = method.getExceptionTable().getExceptionNames();
371             for(int i=0; i<exntypes.length; i++) load(exntypes[i]);
372         }
373         level -= 2;
374     }
375
376     public void visitJavaField(Field field, JavaClass clazz) throws Exception {
377         if (dest.contains(field)) return;
378         dest.add(field);
379         if (field.isStatic()) loadMethod(clazz.getClassName() + ".<clinit>");
380     }
381
382     public void visitJavaClass(JavaClass clazz) throws Exception {
383         if (dest.contains(clazz)) return;
384         dest.add(clazz);
385
386         ConstantPoolGen cpg = new ConstantPoolGen(clazz.getConstantPool());
387         level += 2;
388         for(int i=0; i<level; i++) System.out.print(" ");
389         System.out.println(clazz.getClassName() + ".class");
390
391         JavaClass superclass = clazz.getSuperClass();
392         for(JavaClass sup = superclass; sup != null; sup = sup.getSuperClass()) {
393             if (subclasses.get(sup) == null) subclasses.put(sup, new HashSet());
394             ((HashSet)subclasses.get(sup)).add(clazz);
395         }
396         JavaClass[] interfaces = clazz.getAllInterfaces();
397         for(int i=0; i<interfaces.length; i++) {
398             if (subclasses.get(interfaces[i]) == null) subclasses.put(interfaces[i], new HashSet());
399             ((HashSet)subclasses.get(interfaces[i])).add(clazz);
400         }
401
402         for(JavaClass sup = superclass; sup != null; sup = sup.getSuperClass()) {
403             visitJavaClass(sup);
404             remarkMethods(sup, clazz, cpg);
405         }
406         for(int i=0; i<interfaces.length; i++) {
407             visitJavaClass(interfaces[i]);
408             remarkMethods(interfaces[i], clazz, cpg);
409         }
410
411         Field[] fields = clazz.getFields();
412         for(int i=0; i<fields.length; i++) {
413             if (!fields[i].isStatic()) visitJavaField(fields[i], clazz);
414             else {
415                 Type t = fields[i].getType();
416                 if (t instanceof ObjectType) load(t);
417             }
418         }
419         level -= 2;
420     }
421
422     public void markMethodInSubclasses(JavaClass c, Method m, JavaClass subclass, ConstantPoolGen cpg) throws Exception {
423         if (m.isStatic()) return;
424         if (m.getName().equals("<init>")) return;
425         if (m.getName().equals("equals")) return;
426         if (m.getName().equals("hashCode")) return;
427         if (m.getName().equals("clone")) return;
428         if (m.getName().equals("finalize")) return;
429         if (m.getName().equals("toString")) return;
430         String sig = getMethodSignature(m, cpg);
431         Method[] submethods = getMethods(subclass);
432         for(int j=0; j<submethods.length; j++)
433             if (getMethodSignature(submethods[j], cpg).equals(sig))
434                 visitJavaMethod(subclass, submethods[j]);
435     }
436     public void markMethodInSubclasses(JavaClass c, Method m, ConstantPoolGen cpg) throws Exception {
437         if (m.isStatic()) return;
438         if (m.getName().equals("<init>")) return;
439         HashSet s = (HashSet)subclasses.get(c);
440         if (s == null) return;
441         Object[] subclasses = s.toArray();
442         for(int i=0; i<subclasses.length; i++) {
443             JavaClass subclass = (JavaClass)subclasses[i];
444             if (subclass == c) continue;
445             markMethodInSubclasses(c, m, subclass, cpg);
446         }
447     }
448         
449     public void remarkMethods(JavaClass c, ConstantPoolGen cpg) throws Exception {
450         Method[] meths =getMethods(c);
451         for(int j=0; j<meths.length; j++)
452             if (dest.contains(meths[j]) ||
453                 (uponconstruction.get(c) != null && ((HashSet)uponconstruction.get(c)).contains(meths[j])))
454                 markMethodInSubclasses(c, meths[j], cpg);
455     }
456
457     public void remarkMethods(JavaClass c, JavaClass target, ConstantPoolGen cpg) throws Exception {
458         Method[] meths = getMethods(c);
459         for(int j=0; j<meths.length; j++)
460             if (dest.contains(meths[j]) ||
461                 (uponconstruction.get(c) != null && ((HashSet)uponconstruction.get(c)).contains(meths[j])))
462                 markMethodInSubclasses(c, meths[j], target, cpg);
463     }
464
465     public static Hashtable methodsHashtable = new Hashtable();
466     public static Method[] getMethods(JavaClass c) {
467         Method[] ret = (Method[])methodsHashtable.get(c);
468         if (ret == null) methodsHashtable.put(c, ret = c.getMethods());
469         return ret;
470     }
471
472 }