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