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.*;
11 public class BytecodePruner {
13 public static final boolean deleteMethods = false;
14 public static SyntheticRepository repo = null;
15 public static HashSet dest = new HashSet();
16 public static String outdir = ".";
17 public static Hashtable subclasses = new Hashtable();
18 public static int level = 0;
20 public BytecodePruner() { }
22 public void loadAllMethods(String classname) throws Exception {
23 visitJavaClass(repo.loadClass(classname));
24 Method[] meths = getMethods(repo.loadClass(classname));
25 for(int i=0; i<meths.length; i++)
26 visitJavaMethod(repo.loadClass(classname), meths[i]);
29 public void loadField(String classAndMethodName) throws Exception {
30 String classname = classAndMethodName.substring(0, classAndMethodName.lastIndexOf('.'));
31 String methodname = classAndMethodName.substring(classAndMethodName.lastIndexOf('.') + 1);
32 visitJavaClass(repo.loadClass(classname));
33 Field[] meths = repo.loadClass(classname).getFields();
34 for(int i=0; i<meths.length; i++)
35 if (meths[i].getName().equals(methodname))
36 visitJavaField(meths[i]);
40 public void loadMethod(String classAndMethodName) throws Exception {
41 String classname = classAndMethodName.substring(0, classAndMethodName.lastIndexOf('.'));
42 String methodname = classAndMethodName.substring(classAndMethodName.lastIndexOf('.') + 1);
43 if (classname.endsWith("." + methodname)) methodname = "<init>";
44 visitJavaClass(repo.loadClass(classname));
45 Method[] meths = getMethods(repo.loadClass(classname));
46 for(int i=0; i<meths.length; i++)
47 if (meths[i].getName().equals(methodname))
48 visitJavaMethod(repo.loadClass(classname), meths[i]);
50 public static void main(String[] s) throws Exception {
52 if (s.length >= 3 && s[1].equals("-o")) { outdir = s[2]; start += 2; }
53 repo = SyntheticRepository.getInstance(new ClassPath(s[0]));
55 BytecodePruner bcp = new BytecodePruner();
56 for(int i=start; i<s.length; i++) {
58 if (s[i].endsWith(".class")) {
59 bcp.visitJavaClass(repo.loadClass(s[i].substring(0, s[i].length() - 6)));
61 JavaClass cl = repo.loadClass(s[i].substring(0, s[i].lastIndexOf('.')));;
62 bcp.visitJavaClass(cl);
63 Method[] meths = getMethods(cl);
64 for(int j=0; j<meths.length; j++) {
65 if (meths[j].getName().equals(s[i].substring(s[i].lastIndexOf('.') + 1)))
66 bcp.visitJavaMethod(cl, meths[j]);
69 } catch (Exception e) {
70 System.out.println("WARNING: couldn't load class for " + s[i]);
74 System.out.println("\n\n======================================================================\n");
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");
81 bcp.loadAllMethods("java.util.Hashtable$HashIterator");
82 bcp.loadMethod("java.util.SimpleTimeZone.useDaylightTime");
83 bcp.visitJavaClass(repo.loadClass("gnu.gcj.runtime.FinalizerThread"));
84 bcp.visitJavaClass(repo.loadClass("gnu.gcj.runtime.FirstThread"));
86 bcp.loadMethod("java.lang.Thread.run"); // we call start(), but the VM calls run()...
87 bcp.loadMethod("java.lang.ref.Reference.enqueue"); // the GC calls this directly
88 bcp.loadAllMethods("gnu.gcj.runtime.StringBuffer"); // the compiler emits calls directly to this class
90 bcp.loadAllMethods("gnu.gcj.protocol.http.Handler");
91 bcp.loadAllMethods("gnu.gcj.protocol.file.Handler");
92 bcp.loadAllMethods("gnu.gcj.protocol.core.Handler");
93 bcp.loadAllMethods("gnu.gcj.protocol.jar.Handler");
94 bcp.loadAllMethods("gnu.gcj.convert.Input_UTF8"); // retrieved via reflection
95 bcp.loadAllMethods("gnu.gcj.convert.Output_UTF8"); // retrieved via reflection
96 bcp.loadAllMethods("gnu.gcj.convert.Input_8859_1"); // retrieved via reflection
97 bcp.loadAllMethods("gnu.gcj.convert.Output_8859_1"); // retrieved via reflection
98 bcp.loadAllMethods("gnu.gcj.convert.Input_ASCII"); // retrieved via reflection
99 bcp.loadAllMethods("gnu.gcj.convert.Output_ASCII"); // retrieved via reflection
101 bcp.loadAllMethods("java.util.Date");
102 bcp.loadAllMethods("java.text.DateFormat");
103 bcp.loadAllMethods("java.text.NumberFormat");
105 Method[] meths = getMethods(repo.loadClass("org.ibex.plat.Linux"));
106 for(int i=0; i<meths.length; i++) {
107 if (meths[i].getName().equals("main"))
108 bcp.visitJavaMethod(repo.loadClass("org.ibex.plat.Linux"), meths[i]);
110 System.out.println();
111 System.out.println("Dumping...");
113 StringTokenizer st = new StringTokenizer(s[0], ":");
114 while(st.hasMoreTokens()) {
115 ZipFile zf = new ZipFile(st.nextToken());
116 Enumeration e = zf.entries();
117 while(e.hasMoreElements()) {
118 String ss = ((ZipEntry)e.nextElement()).getName();
119 if (!ss.endsWith(".class")) continue;
120 ss = ss.substring(0, ss.length() - 6);
121 ss = ss.replace('/', '.');
122 dump(repo.loadClass(ss));
127 public static void dump(JavaClass clazz) throws Exception {
128 if (!dest.contains(clazz)) return;
130 ConstantPoolGen newcpg = new ConstantPoolGen(clazz.getConstantPool());
131 ClassGen cg = new ClassGen(clazz);
132 InstructionFactory factory = new InstructionFactory(cg, newcpg);
135 cg.setConstantPool(newcpg);
137 // we can only prune static fields (to avoid altering object layout, which is hardcoded into
138 // CNI code), but that's okay since instance fields don't contribute to binary size
139 Field[] fields = clazz.getFields();
140 for(int i=0; i<fields.length; i++)
141 if (!dest.contains(fields[i]) && fields[i].isStatic()) {
142 System.out.println(" pruning field " + clazz.getClassName() + "." + fields[i].getName());
143 cg.removeField(fields[i]);
146 Method[] methods = getMethods(clazz);
148 boolean good = false;
149 for(int i=0; i<methods.length; i++) {
150 if (dest.contains(methods[i])
151 || clazz.getClassName().startsWith("gnu.gcj.runtime.")
152 || (clazz.getClassName().startsWith("java.lang.") &&
153 !(clazz.getClassName().equals("java.lang.System") && methods[i].getName().equals("runFinalizersOnExit")))
155 if (!methods[i].getName().equals("<clinit>")) good = true;
157 if (methods[i].getCode() == null) {
158 System.out.println(" empty codeblock: " + clazz.getClassName() + "." + methods[i].getName());
160 System.out.println(" pruning " + clazz.getClassName() + "." + methods[i].getName());
161 if (deleteMethods) { cg.removeMethod(methods[i]); continue; }
162 MethodGen mg = new MethodGen(methods[i], clazz.getClassName(), newcpg);
163 mg.removeExceptions();
164 InstructionList il = new InstructionList();
165 mg.setInstructionList(il);
166 InstructionHandle ih_0 = il.append(factory.createNew("java.lang.UnsatisfiedLinkError"));
167 il.append(InstructionConstants.DUP);
168 il.append(factory.createInvoke("java.lang.UnsatisfiedLinkError",
169 "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
170 il.append(InstructionConstants.ATHROW);
173 mg.removeExceptions();
174 mg.removeLocalVariables();
175 mg.removeExceptionHandlers();
176 mg.removeLineNumbers();
177 cg.replaceMethod(methods[i], mg.getMethod());
183 new File(outdir + "/" + new File(clazz.getClassName().replace('.', '/')).getParent()).mkdirs();
184 System.out.println("dumping " + clazz.getClassName());
185 cg.getJavaClass().dump(outdir + "/" + clazz.getClassName().replace('.', '/') + ".class");
188 public JavaClass sig2class(String sig) throws Exception {
189 if (sig == null) return null;
190 while (sig.length() > 0 && (sig.charAt(0) == 'L' || sig.charAt(0) == '[')) {
191 if (sig.charAt(0) == 'L') sig = sig.substring(1, sig.length() - 1);
192 else if (sig.charAt(0) == '[') sig = sig.substring(1, sig.length());
194 if (sig.length() <= 1) return null;
195 if (sig.equals("<null object>")) return null;
196 if (sig.startsWith("<return address")) return null;
197 return repo.loadClass(sig);
199 public void load(String sig) throws Exception {
200 if (sig == null) return;
201 while (sig.length() > 0 && (sig.charAt(0) == 'L' || sig.charAt(0) == '[')) {
202 if (sig.charAt(0) == 'L') sig = sig.substring(1, sig.length() - 1);
203 else if (sig.charAt(0) == '[') sig = sig.substring(1, sig.length());
205 if (sig.length() <= 1) return;
206 if (sig.equals("<null object>")) return;
207 if (sig.startsWith("<return address")) return;
208 visitJavaClass(repo.loadClass(sig));
210 public void load(Type t) throws Exception {
211 if (t == null) return;
212 if (t instanceof ArrayType) load(((ArrayType)t).getElementType());
213 if (!(t instanceof ObjectType)) return;
214 load(((ObjectType)t).getClassName());
217 public String getMethodSignature(Method m, ConstantPoolGen cpg) throws Exception { return m.getName() + m.getSignature(); }
218 public String getMethodSignature(InvokeInstruction ii, ConstantPoolGen cpg) throws Exception {
220 Type[] argtypes = ii.getArgumentTypes(cpg);
221 for(int j=0; j<argtypes.length; j++) sig += argtypes[j].getSignature();
222 return ii.getMethodName(cpg) + "(" + sig + ")" + ii.getReturnType(cpg).getSignature();
225 public void visitJavaMethod(JavaClass jc, Method method) throws Exception {
227 if (jc.getClassName().indexOf("SharedLib") != -1) return;
228 if (jc.getClassName().indexOf("Datagram") != -1) return;
230 // gcj bug; gcj can't compile this method from a .class file input; I have no idea why
231 if (jc.getClassName().equals("java.lang.System") && method.getName().equals("runFinalizersOnExit")) return;
233 if (dest.contains(method)) return;
236 for(int i=0; i<level; i++) System.out.print(" ");
237 ConstantPoolGen cpg = new ConstantPoolGen(method.getConstantPool());
238 System.out.println(jc.getClassName() + "." + getMethodSignature(method, cpg));
239 markMethodInSubclasses(jc, method, cpg);
240 if (method.getCode() == null) { level -= 2; return; }
241 byte[] code = method.getCode().getCode();
242 InstructionList il = new InstructionList(code);
243 Instruction[] instructions = il.getInstructions();
244 for(int i=0; i<instructions.length; i++){
245 Instruction instr = instructions[i];
246 if (instr instanceof LoadClass) load(((LoadClass)instr).getLoadClassType(cpg));
247 if (instr instanceof CPInstruction) load(((CPInstruction)instr).getType(cpg));
248 if (instr instanceof TypedInstruction) {
249 try { load(((TypedInstruction)instr).getType(cpg)); } catch (Exception e) { /* DELIBERATE */ }
251 if (instr instanceof NEW) {
252 for(int j=0; j<level; j++) System.out.print(" ");
253 loadMethod(((NEW)instr).getLoadClassType(cpg).getClassName() + ".<init>");
255 if (instr instanceof org.apache.bcel.generic.FieldOrMethod)
256 load(((org.apache.bcel.generic.FieldOrMethod)instr).getClassType(cpg));
257 if (instr instanceof org.apache.bcel.generic.FieldInstruction) {
258 load(((org.apache.bcel.generic.FieldInstruction)instr).getFieldType(cpg));
259 load(((org.apache.bcel.generic.FieldInstruction)instr).getType(cpg));
260 String fieldName = ((org.apache.bcel.generic.FieldInstruction)instr).getFieldName(cpg);
261 JavaClass jc2 = repo.loadClass(((ObjectType)((org.apache.bcel.generic.FieldInstruction)instr).
262 getLoadClassType(cpg)).getClassName());
263 Field[] fields = jc2.getFields();
264 for(int j=0; j<fields.length; j++) if (fields[j].getName().equals(fieldName)) visitJavaField(fields[j]);
266 if (instr instanceof InvokeInstruction) {
267 InvokeInstruction ii = (InvokeInstruction)instr;
268 String ii_sig = getMethodSignature(ii, cpg);
269 JavaClass c = sig2class(ii.getLoadClassType(cpg).getSignature());
270 load(ii.getReturnType(cpg));
271 load(ii.getType(cpg));
272 Method[] meths = getMethods(c);
273 boolean good = false;
274 for(int i2=0; i2<meths.length; i2++) {
275 if (getMethodSignature(meths[i2], cpg).equals(ii_sig)) {
276 visitJavaMethod(c, meths[i2]);
281 if (!good) throw new Exception("couldn't find method " + getMethodSignature(ii, cpg) + " in " + c.getClassName());
285 // FIXME: move this to the top
286 load(method.getReturnType());
287 Type[] argtypes = method.getArgumentTypes();
288 for(int i=0; i<argtypes.length; i++) load(argtypes[i]);
289 if (method.getExceptionTable() != null) {
290 String[] exntypes = method.getExceptionTable().getExceptionNames();
291 for(int i=0; i<exntypes.length; i++) load(exntypes[i]);
295 public void visitJavaField(Field field) throws Exception {
296 if (dest.contains(field)) return;
298 load(field.getType());
301 public void visitJavaClass(JavaClass clazz) throws Exception {
302 if (dest.contains(clazz)) return;
305 ConstantPoolGen cpg = new ConstantPoolGen(clazz.getConstantPool());
306 String name = clazz.getClassName();
307 System.out.println(clazz.getClassName() + ".class");
309 JavaClass superclass = clazz.getSuperClass();
310 JavaClass[] interfaces = clazz.getAllInterfaces();
311 for(JavaClass sup = superclass; sup != null; sup = sup.getSuperClass()) {
312 if (subclasses.get(sup) == null) subclasses.put(sup, new HashSet());
313 ((HashSet)subclasses.get(sup)).add(clazz);
315 for(int i=0; i<interfaces.length; i++) {
316 if (subclasses.get(interfaces[i]) == null) subclasses.put(interfaces[i], new HashSet());
317 ((HashSet)subclasses.get(interfaces[i])).add(clazz);
321 if (clazz.getClassName().startsWith("org.ibex.")) loadAllMethods(clazz.getClassName());
323 for(JavaClass sup = superclass; sup != null; sup = sup.getSuperClass()) {
325 remarkMethods(sup, clazz, cpg);
327 for(int i=0; i<interfaces.length; i++) {
328 visitJavaClass(interfaces[i]);
329 remarkMethods(interfaces[i], clazz, cpg);
332 Method[] methods = getMethods(clazz);
333 for(int i=0; i<methods.length; i++) {
334 if (methods[i].getName().equals("<clinit>")) visitJavaMethod(clazz, methods[i]);
335 if (methods[i].getName().equals("equals")) visitJavaMethod(clazz, methods[i]);
336 if (methods[i].getName().equals("hashCode")) visitJavaMethod(clazz, methods[i]);
337 if (methods[i].getName().equals("finalize")) visitJavaMethod(clazz, methods[i]);
338 if (methods[i].getName().equals("clone")) visitJavaMethod(clazz, methods[i]);
339 if (methods[i].getName().equals("toString")) visitJavaMethod(clazz, methods[i]);
343 public void markMethodInSubclasses(JavaClass c, Method m, JavaClass subclass, ConstantPoolGen cpg) throws Exception {
344 if (m.isStatic()) return;
345 String sig = getMethodSignature(m, cpg);
346 Method[] submethods = getMethods(subclass);
347 for(int j=0; j<submethods.length; j++)
348 if (getMethodSignature(submethods[j], cpg).equals(sig))
349 visitJavaMethod(subclass, submethods[j]);
351 public void markMethodInSubclasses(JavaClass c, Method m, ConstantPoolGen cpg) throws Exception {
352 if (m.isStatic()) return;
353 HashSet s = (HashSet)subclasses.get(c);
354 if (s == null) return;
355 Object[] subclasses = s.toArray();
356 for(int i=0; i<subclasses.length; i++) {
357 JavaClass subclass = (JavaClass)subclasses[i];
358 if (subclass == c) continue;
359 for(int j=0; j<level; j++) System.out.print(" ");
360 System.out.println(" [subclass " + subclass.getClassName() + "]");
361 markMethodInSubclasses(c, m, subclass, cpg);
365 public void remarkMethods(JavaClass c, ConstantPoolGen cpg) throws Exception {
366 Method[] meths =getMethods(c);
367 for(int j=0; j<meths.length; j++) if (dest.contains(meths[j])) markMethodInSubclasses(c, meths[j], cpg);
370 public void remarkMethods(JavaClass c, JavaClass target, 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], target, cpg);
375 public static Hashtable methodsHashtable = new Hashtable();
376 public static Method[] getMethods(JavaClass c) {
377 Method[] ret = (Method[])methodsHashtable.get(c);
378 if (ret == null) methodsHashtable.put(c, ret = c.getMethods());