this does not work
[org.ibex.core.git] / src / org / ibex / util / BytecodePruner.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 BytecodePruner {
11
12     public static final boolean deleteMethods = false;
13     public static SyntheticRepository repo = null;
14     public static HashSet dest = new HashSet();
15     public static String outdir = ".";
16     public static Hashtable subclasses = new Hashtable();
17     public static int level = 0;
18
19     public BytecodePruner() { }
20
21     public void loadAllMethods(String classname) throws Exception {
22         visitJavaClass(repo.loadClass(classname));
23         Method[] meths = getMethods(repo.loadClass(classname));
24         for(int i=0; i<meths.length; i++)
25             visitJavaMethod(repo.loadClass(classname), meths[i]);
26     }
27
28     public void loadField(String classAndMethodName) throws Exception {
29         String classname = classAndMethodName.substring(0, classAndMethodName.lastIndexOf('.'));
30         String methodname = classAndMethodName.substring(classAndMethodName.lastIndexOf('.') + 1);
31         visitJavaClass(repo.loadClass(classname));
32         Field[] meths = repo.loadClass(classname).getFields();
33         for(int i=0; i<meths.length; i++)
34             if (meths[i].getName().equals(methodname))
35                 visitJavaField(meths[i]);
36     }
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         if (s.length >= 3 && s[1].equals("-o")) { outdir = s[2]; start += 2; }
52         repo = SyntheticRepository.getInstance(new ClassPath(s[0]));
53
54         BytecodePruner bcp = new BytecodePruner();
55         for(int i=start; i<s.length; i++) {
56             try {
57                 if (s[i].endsWith(".class")) {
58                     bcp.visitJavaClass(repo.loadClass(s[i].substring(0, s[i].length() - 6)));
59                 } else {
60                     JavaClass cl = repo.loadClass(s[i].substring(0, s[i].lastIndexOf('.')));;
61                     bcp.visitJavaClass(cl);
62                     bcp.loadMethod(s[i]);
63                 }
64             } catch (Exception e) {
65                 System.out.println("WARNING: couldn't load class for " + s[i]);
66             }
67         }
68
69         System.out.println("\n\n======================================================================\n");
70
71         // we call start(), but the VM calls run()...
72         bcp.loadMethod("java.lang.Thread.run");
73         bcp.loadAllMethods("java.lang.SecurityContext");
74         bcp.loadAllMethods("java.lang.ThreadDeath");
75
76         bcp.loadAllMethods("java.util.Hashtable$HashIterator");
77         bcp.loadMethod("java.util.SimpleTimeZone.useDaylightTime");
78         bcp.visitJavaClass(repo.loadClass("gnu.gcj.runtime.FinalizerThread"));
79         bcp.visitJavaClass(repo.loadClass("gnu.gcj.runtime.FirstThread"));
80
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
87         bcp.loadAllMethods("gnu.gcj.protocol.http.Handler");
88         bcp.loadAllMethods("gnu.gcj.protocol.file.Handler");
89         bcp.loadAllMethods("gnu.gcj.protocol.core.Handler");
90         bcp.loadAllMethods("gnu.gcj.protocol.jar.Handler");
91
92         // to ensure we get all the stuff that might be called from CNI
93         bcp.loadAllMethods("org.ibex.plat.Linux");
94         bcp.loadAllMethods("org.ibex.plat.X11");
95         bcp.loadAllMethods("org.ibex.plat.GCJ");
96         bcp.loadAllMethods("org.ibex.plat.POSIX");
97         bcp.loadAllMethods("org.ibex.plat.X11$X11Surface");
98         bcp.loadAllMethods("org.ibex.plat.X11$X11PixelBuffer");
99         bcp.loadAllMethods("org.ibex.plat.X11$X11Picture");
100         bcp.loadAllMethods("org.ibex.Surface");
101         bcp.loadAllMethods("org.ibex.Picture");
102         bcp.loadAllMethods("org.ibex.PixelBuffer");
103
104         // primary entry point
105         bcp.loadMethod("org.ibex.plat.Linux.main");
106         System.out.println();
107
108         System.out.println("Dumping...");
109         StringTokenizer st = new StringTokenizer(s[0], ":");
110         while(st.hasMoreTokens()) {
111             ZipFile zf = new ZipFile(st.nextToken());
112             Enumeration e = zf.entries();
113             while(e.hasMoreElements()) {
114                 String ss = ((ZipEntry)e.nextElement()).getName();
115                 if (!ss.endsWith(".class")) continue;
116                 ss = ss.substring(0, ss.length() - 6);
117                 ss = ss.replace('/', '.');
118                 dump(repo.loadClass(ss));
119             }
120         }
121     }
122
123     public static void dump(JavaClass clazz) throws Exception {
124         if (!dest.contains(clazz)) return;
125
126         ConstantPoolGen newcpg = new ConstantPoolGen(clazz.getConstantPool());
127         ClassGen cg = new ClassGen(clazz);
128         InstructionFactory factory = new InstructionFactory(cg, newcpg);
129         cg.setMajor(46);
130         cg.setMinor(0);
131         cg.setConstantPool(newcpg);
132
133         boolean constructed = false;
134         Method[] methods = getMethods(clazz);
135         for(int i=0; i<methods.length; i++)
136             if (dest.contains(methods[i]) && methods[i].getName().equals("<init>"))
137                 constructed = true;
138
139         // we can only prune static fields (to avoid altering object layout, which is hardcoded into
140         // CNI code), but that's okay since instance fields don't contribute to binary size
141         Field[] fields = clazz.getFields();
142         for(int i=0; i<fields.length; i++) {
143             if (!dest.contains(fields[i]) && fields[i].isStatic()) { 
144                 System.out.println("  pruning field " + clazz.getClassName() + "." + fields[i].getName());
145                 cg.removeField(fields[i]);
146             }
147             /*  -- there's really no point to this --
148             if (!constructed && !fields[i].isStatic()) {
149                 System.out.println("  unconstructed: pruning field " + clazz.getClassName() + "." + fields[i].getName());
150                 cg.removeField(fields[i]);
151             }
152             */
153         }
154
155         int numMethods = 0;
156         boolean good = false;
157         for(int i=0; i<methods.length; i++) {
158             if (dest.contains(methods[i]) && (constructed || !methods[i].isStatic())) {
159                 if (!methods[i].getName().equals("<clinit>")) good = true;
160             } else {
161                 if (methods[i].getCode() == null) {
162                     System.out.println("  empty codeblock: " + clazz.getClassName() + "." + methods[i].getName());
163                 } else {
164                     System.out.println("  pruning " +(constructed?"":"unconstructed")+ " method " +
165                                        clazz.getClassName() + "." + methods[i].getName());
166                     // FIXME: try deleteMethods
167                     if (deleteMethods) { cg.removeMethod(methods[i]); continue; }
168                     MethodGen mg = new MethodGen(methods[i], clazz.getClassName(), newcpg);
169                     mg.removeExceptions();
170                     InstructionList il = new InstructionList();
171                     mg.setInstructionList(il);
172                     InstructionHandle ih_0 = il.append(factory.createNew("java.lang.UnsatisfiedLinkError"));
173                     il.append(InstructionConstants.DUP);
174                     il.append(factory.createInvoke("java.lang.UnsatisfiedLinkError",
175                                                    "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
176                     il.append(InstructionConstants.ATHROW);
177                     mg.setMaxStack();
178                     mg.setMaxLocals();
179                     mg.removeExceptions();
180                     mg.removeLocalVariables();
181                     mg.removeExceptionHandlers();
182                     mg.removeLineNumbers();
183                     cg.replaceMethod(methods[i], mg.getMethod());
184                     il.dispose();
185                 }
186             }
187         }
188
189         if (!good) {
190             System.out.println("DROPPING " + clazz.getClassName());
191             JavaClass[] ifaces = clazz.getInterfaces();
192             String[] ifacestrings = new String[ifaces.length];
193             for(int i=0; i<ifaces.length; i++) ifacestrings[i] = ifaces[i].getClassName();
194             cg = new ClassGen(clazz.getClassName(),
195                               clazz.getSuperClass().getClassName(),
196                               clazz.getFileName(),
197                               clazz.getAccessFlags(),
198                               ifacestrings,
199                               newcpg);
200         } else {
201             System.out.println("dumping " + clazz.getClassName());
202         }
203         new File(outdir + "/" + new File(clazz.getClassName().replace('.', '/')).getParent()).mkdirs();
204         cg.getJavaClass().dump(outdir + "/" + clazz.getClassName().replace('.', '/') + ".class");
205     }
206
207     public JavaClass sig2class(String sig) throws Exception {
208         if (sig == null) return null;
209         while (sig.length() > 0 && (sig.charAt(0) == 'L' || sig.charAt(0) == '[')) {
210             if (sig.charAt(0) == 'L') sig = sig.substring(1, sig.length() - 1);
211             else if (sig.charAt(0) == '[') sig = sig.substring(1, sig.length());
212         }
213         if (sig.length() <= 1) return null;
214         if (sig.equals("<null object>")) return null;
215         if (sig.startsWith("<return address")) return null;
216         return repo.loadClass(sig);
217     }
218     public void load(String sig) throws Exception {
219         if (sig == null) return;
220         while (sig.length() > 0 && (sig.charAt(0) == 'L' || sig.charAt(0) == '[')) {
221             if (sig.charAt(0) == 'L') sig = sig.substring(1, sig.length() - 1);
222             else if (sig.charAt(0) == '[') sig = sig.substring(1, sig.length());
223         }
224         if (sig.length() <= 1) return;
225         if (sig.equals("<null object>")) return;
226         if (sig.startsWith("<return address")) return;
227         visitJavaClass(repo.loadClass(sig));
228     }
229     public void load(Type t) throws Exception {
230         if (t == null) return;
231         if (t instanceof ArrayType) load(((ArrayType)t).getElementType());
232         if (!(t instanceof ObjectType)) return;
233         load(((ObjectType)t).getClassName());
234     }
235
236     public String getMethodSignature(Method m, ConstantPoolGen cpg) throws Exception { return m.getName() + m.getSignature(); }
237     public String getMethodSignature(InvokeInstruction ii, ConstantPoolGen cpg) throws Exception {
238         String sig = "";
239         Type[] argtypes = ii.getArgumentTypes(cpg);
240         for(int j=0; j<argtypes.length; j++) sig += argtypes[j].getSignature();
241         return ii.getMethodName(cpg) + "(" + sig + ")" + ii.getReturnType(cpg).getSignature();
242     }
243
244     public void visitJavaMethod(JavaClass jc, Method method) throws Exception {
245         visitJavaClass(jc);
246         if (jc.getClassName().indexOf("SharedLib") != -1) return;
247         if (jc.getClassName().indexOf("Datagram") != -1) return;
248
249         // gcj bug; gcj can't compile this method from a .class file input; I have no idea why
250         if (jc.getClassName().equals("java.lang.System") && method.getName().equals("runFinalizersOnExit")) return;
251
252         if (dest.contains(method)) return;
253         dest.add(method);
254
255         if (method.isStatic()) loadMethod(jc.getClassName() + ".<clinit>");
256
257         level += 2;
258         for(int i=0; i<level; i++) System.out.print(" ");
259         ConstantPoolGen cpg = new ConstantPoolGen(method.getConstantPool());
260         System.out.println(jc.getClassName() + "." + getMethodSignature(method, cpg));
261         markMethodInSubclasses(jc, method, cpg);
262         if (method.getCode() == null) { level -= 2; return; }
263         byte[] code = method.getCode().getCode();
264         InstructionList il = new InstructionList(code);
265         Instruction[] instructions = il.getInstructions();
266         for(int i=0; i<instructions.length; i++){ 
267             Instruction instr = instructions[i];
268             if (instr instanceof LoadClass) {
269                 ObjectType ot = (ObjectType)((LoadClass)instr).getLoadClassType(cpg);
270                 if (ot != null) loadMethod(ot.getClassName() + ".<clinit>");
271             }
272             if (instr instanceof CPInstruction) load(((CPInstruction)instr).getType(cpg));
273             if (instr instanceof TypedInstruction) {
274                 try { load(((TypedInstruction)instr).getType(cpg)); } catch (Exception e) { /* DELIBERATE */ }
275             }
276             if (instr instanceof NEW) {
277                 for(int j=0; j<level; j++) System.out.print(" ");
278                 loadMethod(((NEW)instr).getLoadClassType(cpg).getClassName() + ".<init>");
279             }
280             if (instr instanceof org.apache.bcel.generic.FieldOrMethod)
281                 load(((org.apache.bcel.generic.FieldOrMethod)instr).getClassType(cpg));
282             if (instr instanceof org.apache.bcel.generic.FieldInstruction) {
283                 load(((org.apache.bcel.generic.FieldInstruction)instr).getFieldType(cpg));
284                 load(((org.apache.bcel.generic.FieldInstruction)instr).getType(cpg));
285                 String fieldName = ((org.apache.bcel.generic.FieldInstruction)instr).getFieldName(cpg);
286                 JavaClass jc2 = repo.loadClass(((ObjectType)((org.apache.bcel.generic.FieldInstruction)instr).
287                                                 getLoadClassType(cpg)).getClassName());
288                 Field[] fields = jc2.getFields();
289                 for(int j=0; j<fields.length; j++) if (fields[j].getName().equals(fieldName)) visitJavaField(fields[j]);
290             }
291             if (instr instanceof InvokeInstruction) {
292                 InvokeInstruction ii = (InvokeInstruction)instr;
293                 String ii_sig = getMethodSignature(ii, cpg);
294                 JavaClass c = sig2class(ii.getLoadClassType(cpg).getSignature());
295
296                 load(ii.getType(cpg));
297                 Method[] meths = getMethods(c);
298                 boolean good = false;
299                 for(int i2=0; i2<meths.length; i2++) {
300                     if (getMethodSignature(meths[i2], cpg).equals(ii_sig)) {
301                         visitJavaMethod(c, meths[i2]);
302                         good = true;
303                         break;
304                     }
305                 } 
306                 if (!good) throw new Exception("couldn't find method " + getMethodSignature(ii, cpg) + " in " + c.getClassName());
307             }
308         }
309         level -= 2;
310
311         // FIXME: move this to the top
312         Type[] argtypes = method.getArgumentTypes();
313         for(int i=0; i<argtypes.length; i++) load(argtypes[i]);
314         if (method.getExceptionTable() != null) {
315             String[] exntypes = method.getExceptionTable().getExceptionNames();
316             for(int i=0; i<exntypes.length; i++) load(exntypes[i]);
317         }
318     }
319
320     public void visitJavaField(Field field) throws Exception {
321         if (!dest.contains(field)) dest.add(field);
322     }
323
324     public void visitJavaClass(JavaClass clazz) throws Exception {
325         if (dest.contains(clazz)) return;
326         dest.add(clazz);
327
328         ConstantPoolGen cpg = new ConstantPoolGen(clazz.getConstantPool());
329         System.out.println(clazz.getClassName() + ".class");
330
331         JavaClass superclass = clazz.getSuperClass();
332         for(JavaClass sup = superclass; sup != null; sup = sup.getSuperClass()) {
333             if (subclasses.get(sup) == null) subclasses.put(sup, new HashSet());
334             ((HashSet)subclasses.get(sup)).add(clazz);
335         }
336         JavaClass[] interfaces = clazz.getAllInterfaces();
337         for(int i=0; i<interfaces.length; i++) {
338             if (subclasses.get(interfaces[i]) == null) subclasses.put(interfaces[i], new HashSet());
339             ((HashSet)subclasses.get(interfaces[i])).add(clazz);
340         }
341
342         for(JavaClass sup = superclass; sup != null; sup = sup.getSuperClass()) {
343             visitJavaClass(sup);
344             remarkMethods(sup, clazz, cpg);
345         }
346         for(int i=0; i<interfaces.length; i++) {
347             visitJavaClass(interfaces[i]);
348             remarkMethods(interfaces[i], clazz, cpg);
349         }
350
351         Field[] fields = clazz.getFields();
352         for(int i=0; i<fields.length; i++) {
353             if (!fields[i].isStatic()) visitJavaField(fields[i]);
354             else {
355                 Type t = fields[i].getType();
356                 if (t instanceof ObjectType) load(t);
357             }
358         }
359
360         Method[] methods = getMethods(clazz);
361         for(int i=0; i<methods.length; i++) {
362             //if (methods[i].getName().equals("<clinit>")) visitJavaMethod(clazz, methods[i]);
363             if (methods[i].getName().equals("equals")) visitJavaMethod(clazz, methods[i]);
364             if (methods[i].getName().equals("hashCode")) visitJavaMethod(clazz, methods[i]);
365             if (methods[i].getName().equals("finalize")) visitJavaMethod(clazz, methods[i]);
366             if (methods[i].getName().equals("clone")) visitJavaMethod(clazz, methods[i]);
367             if (methods[i].getName().equals("toString")) visitJavaMethod(clazz, methods[i]);
368         }
369     }
370
371     public void markMethodInSubclasses(JavaClass c, Method m, JavaClass subclass, ConstantPoolGen cpg) throws Exception {
372         if (m.isStatic()) return;
373         String sig = getMethodSignature(m, cpg);
374         Method[] submethods = getMethods(subclass);
375         for(int j=0; j<submethods.length; j++)
376             if (getMethodSignature(submethods[j], cpg).equals(sig))
377                 visitJavaMethod(subclass, submethods[j]);
378     }
379     public void markMethodInSubclasses(JavaClass c, Method m, ConstantPoolGen cpg) throws Exception {
380         if (m.isStatic()) return;
381         HashSet s = (HashSet)subclasses.get(c);
382         if (s == null) return;
383         Object[] subclasses = s.toArray();
384         for(int i=0; i<subclasses.length; i++) {
385             JavaClass subclass = (JavaClass)subclasses[i];
386             if (subclass == c) continue;
387             markMethodInSubclasses(c, m, subclass, cpg);
388         }
389     }
390         
391     public void remarkMethods(JavaClass c, ConstantPoolGen cpg) throws Exception {
392         Method[] meths =getMethods(c);
393         for(int j=0; j<meths.length; j++) if (dest.contains(meths[j])) markMethodInSubclasses(c, meths[j], cpg);
394     }
395
396     public void remarkMethods(JavaClass c, JavaClass target, ConstantPoolGen cpg) throws Exception {
397         Method[] meths = getMethods(c);
398         for(int j=0; j<meths.length; j++) if (dest.contains(meths[j])) markMethodInSubclasses(c, meths[j], target, cpg);
399     }
400
401     public static Hashtable methodsHashtable = new Hashtable();
402     public static Method[] getMethods(JavaClass c) {
403         Method[] ret = (Method[])methodsHashtable.get(c);
404         if (ret == null) methodsHashtable.put(c, ret = c.getMethods());
405         return ret;
406     }
407
408 }