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