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