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