more stuff
[org.ibex.gcclass.git] / src / com / brian_web / gcclass / GCClass.java
1 // Copyright (C) 2004 Brian Alliet
2
3 // Based on NanoGoat by Adam Megac
4
5 // Copyright (C) 2004 Adam Megacz <adam@ibex.org> all rights reserved.
6 //
7 // You may modify, copy, and redistribute this code under the terms of
8 // the GNU Library Public License version 2.1, with the exception of
9 // the portion of clause 6a after the semicolon (aka the "obnoxious
10 // relink clause")
11
12 package com.brian_web.gcclass;
13
14 import java.util.*;
15 import java.io.*;
16
17 import org.apache.bcel.Constants;
18 import org.apache.bcel.util.*;
19 import org.apache.bcel.generic.*;
20 import org.apache.bcel.classfile.*;
21
22 // FEATURE: Rebuild each method with a new constant pool to eliminate extra constant pool entries
23 // FEATURE: Optimize away INSTANCEOF if the class can never be instansiated
24
25 public class GCClass {
26     private static final String[] PRE_REF = {
27         "java.lang.Thread.run",
28         "java.security.PrivilegedAction.run"
29     };
30     
31     // NOTE: This doesn't mean these classes are ignored alltogether
32     //       failures to resolve them are just ignored
33     private static final String[] IGNORED_METHODS = {
34         "java.net.SocketImpl.setOption(ILjava/lang/Object;)V",
35         "java.net.SocketImpl.getOption(I)Ljava/lang/Object;",
36         "java.awt.geom.*",
37         "apple.awt.*",
38         "java.security.*"
39     };
40     
41     private static final String[] NO_OUTPUT = { "java", "javax", "sun", "com.sun", "apple", "com.apple" };
42     
43     
44     public static void main(String[] args) throws Exception {
45         if(args.length < 3) {
46             System.err.println("Usage GCClass  classpath outdir entrypoint1 ... [ entrypoint n]");
47             System.exit(1);
48         }
49         GCClass gc = new GCClass(args[0]);
50         for(int i=2;i<args.length;i++) gc.referenceMethod(args[i]);
51         gc.go();
52         gc.dump(new File(args[1]));
53     }
54     
55     private final Repository repo;
56     private final Vector work = new Vector();
57     private final Hashtable completed = new Hashtable();
58     private final Hashtable references = new Hashtable();
59     
60     public GCClass(String classpath) throws ClassNotFoundException {
61         System.err.println(ClassPath.SYSTEM_CLASS_PATH + File.pathSeparator + classpath);
62         repo = SyntheticRepository.getInstance(new ClassPath(ClassPath.SYSTEM_CLASS_PATH + File.pathSeparator + classpath));
63         for(int i=0;i<PRE_REF.length;i++) referenceMethod(PRE_REF[i]);
64     }
65     
66     private Hashtable classRefHash(JavaClass c) { return classRefHash(new ObjectType(c.getClassName())); }
67     private Hashtable classRefHash(ObjectType c) {
68         Hashtable h = (Hashtable) references.get(c);
69         if(h == null) references.put(c,h=new Hashtable());
70         return h;
71     }
72     
73     public final ObjectType referenceClass(JavaClass c) { return referenceClass(c.getClassName()); }
74     public final ObjectType referenceClass(String s) { return referenceClass(new ObjectType(s)); }
75     public final ObjectType referenceClass(Type t) {
76         if(t instanceof ObjectType) return referenceClass((ObjectType)t);
77         return null;
78     }
79     
80     public final ObjectType referenceClass(ObjectType t) {
81         classRefHash(t);
82         return t;
83     }
84     
85     public final void referenceMethod(String s) throws ClassNotFoundException {
86         int p = s.lastIndexOf('.');
87         if(p == -1) throw new IllegalArgumentException("invalid class/method string");
88         String cs = s.substring(0,p);
89         String ms = s.substring(p+1);
90         
91         JavaClass c = repoGet(cs);
92         Method[] methods = c.getMethods();
93         for(int i=0;i<methods.length;i++)
94             if(methods[i].getName().equals(ms))
95                 referenceMethod(new MethodRef(c,methods[i]));
96     }
97         
98     public final void referenceMethod(MethodRef m) {
99         if(completed.get(m) != null) return;
100         
101         if(m.c.getClassName().startsWith("[")) {
102             completed.put(m,Boolean.TRUE);
103             return;
104         }
105         
106         Hashtable h = classRefHash(m.c);
107         h.put(m,Boolean.TRUE);
108         work.add(m);
109         
110         referenceClass(m.ret);
111         for(int i=0;i<m.args.length;i++) referenceClass(m.args[i]);
112     }
113     
114     public final void referenceField(FieldRef f) {
115         Hashtable h = classRefHash(f.c);
116         h.put(f,Boolean.TRUE);
117         referenceClass(f.ftype);
118     }
119     
120     private Hashtable repoCache = new Hashtable();
121     public JavaClass repoGet(ObjectType t) throws ClassNotFoundException { return repoGet(t.getClassName()); }
122     public JavaClass repoGet(String s) throws ClassNotFoundException {
123         Object o = repoCache.get(s);
124         if(o == null) repoCache.put(s,o = repo.loadClass(s));
125         return (JavaClass) o;
126     }
127     
128     public void go() throws Exn, ClassNotFoundException {
129         while(work.size() != 0) {
130             while(work.size() != 0) process((MethodRef) work.remove(work.size()-1));
131             fixup();
132         }
133     }
134     
135     private void fixup() throws ClassNotFoundException {
136         for(Enumeration e = references.keys(); e.hasMoreElements(); ) {
137             ObjectType t = (ObjectType) e.nextElement();
138             JavaClass c = repoGet(t);
139             if(c == null) continue;
140             Hashtable refs = (Hashtable) references.get(t);
141             if(refs.size() != 0) {
142                 MethodRef clinit = new MethodRef(t,"<clinit>",Type.VOID,Type.NO_ARGS);
143                 if(findMethod(c,clinit) != null) referenceMethod(clinit);
144             }
145             Method[] methods = c.getMethods();
146             JavaClass[] supers = c.getSuperClasses();
147             JavaClass[] interfaces = c.getInterfaces();
148             //System.err.println("Fixing up " + t);
149             for(int i=0;i<supers.length;i++) referenceClass(supers[i]);
150             for(int i=0;methods != null && i<methods.length;i++) {
151                 MethodRef mr = new MethodRef(c,methods[i]);
152                 if(refs.get(mr) != null) continue;
153                 for(int j=0;j<supers.length;j++) {
154                     MethodRef smr = new MethodRef(supers[j],methods[i]);
155                     Hashtable srefs = classRefHash(supers[j]);
156                     if(srefs.get(smr) != null) referenceMethod(mr);
157                     
158                     JavaClass[] interfaces2 = supers[j].getInterfaces();
159                     for(int k=0;interfaces2 != null && k<interfaces2.length;k++) {
160                         MethodRef imr = new MethodRef(interfaces2[k],methods[i]);
161                         Hashtable irefs = classRefHash(interfaces2[k]);
162                         if(irefs.get(imr) != null) referenceMethod(mr);
163                     }
164                 }
165                 for(int j=0;interfaces != null && j<interfaces.length;j++) {
166                     MethodRef imr = new MethodRef(interfaces[j],methods[i]);
167                     Hashtable irefs = classRefHash(interfaces[j]);
168                     if(irefs.get(imr) != null) referenceMethod(mr);
169                 }
170             }                                             
171         }
172     }
173     
174     private Hashtable cpgCache = new Hashtable();
175     private void process(MethodRef mr) throws Exn, ClassNotFoundException {
176         if(completed.get(mr) != null) return;
177         completed.put(mr,Boolean.TRUE);
178         
179         //System.err.println("Processing " + mr + "...");
180
181         JavaClass c = repoGet(mr.c.toString());
182         
183         if(!c.isClass() && !mr.name.equals("<clinit>")) return;
184         
185         Method m = findMethod(c,mr);
186         if(m == null) {
187             JavaClass supers[] = c.getSuperClasses();
188             for(int i=0;i<supers.length;i++) {
189                 m = findMethod(supers[i],mr);
190                 if(m != null) { referenceMethod(new MethodRef(supers[i],m)); return; }
191             }
192             String sig = mr.toString();
193             for(int i=0;i<IGNORED_METHODS.length;i++) {
194                 String pat = IGNORED_METHODS[i];
195                 if(pat.endsWith("*") ? sig.startsWith(pat.substring(0,pat.length()-1)) : sig.equals(pat)) return;
196             }
197             throw new Exn("Couldn't find " + sig);
198         }
199         
200         Code code = m.getCode();
201         if(code == null) return;
202         
203         ConstantPoolGen cpg = (ConstantPoolGen) cpgCache.get(c);
204         if(cpg == null) cpgCache.put(c,cpg=new ConstantPoolGen(c.getConstantPool()));
205         
206         InstructionList insnList = new InstructionList(code.getCode());
207         Instruction[] insns = insnList.getInstructions();
208         
209         for(int n=0;n<insns.length;n++) {
210             Instruction i = insns[n];
211             if(i instanceof ANEWARRAY || i instanceof CHECKCAST || i instanceof INSTANCEOF || i instanceof MULTIANEWARRAY || i instanceof NEW)
212                 referenceClass(((CPInstruction)i).getType(cpg));
213             else if(i instanceof FieldInstruction) // GETFIED, GETSTATIC, PUTFIELD, PUTSTATIC
214                 referenceField(new FieldRef((FieldInstruction)i,cpg));
215             else if(i instanceof InvokeInstruction) // INVOKESTATIC, INVOKEVIRTUAL, INVOKESPECIAL
216                 referenceMethod(new MethodRef((InvokeInstruction)i,cpg));
217         }
218     }
219     
220     private static Method findMethod(JavaClass c, MethodRef mr) {
221         Method[] ms = c.getMethods();
222         for(int i=0;i<ms.length;i++) {
223             Method m = ms[i];
224             if(m.getName().equals(mr.name) && m.getReturnType().equals(mr.ret) && Arrays.equals(m.getArgumentTypes(),mr.args))
225                return m;
226         }
227         return null;
228     }
229     
230     public void dump(File outdir) throws IOException, ClassNotFoundException {
231         if(!outdir.isDirectory()) throw new IOException("" + outdir + " is not a directory");
232         OUTER: for(Enumeration e = references.keys(); e.hasMoreElements(); ) {
233             ObjectType t = (ObjectType) e.nextElement();
234             String name =  t.getClassName();
235             for(int i=0;i<NO_OUTPUT.length;i++) if(name.startsWith(NO_OUTPUT[i])) continue OUTER;
236             Hashtable refs = (Hashtable) references.get(t);
237             JavaClass c = repoGet(t.getClassName());
238             if(c == null) continue;
239             File cf = new File(outdir,t.getClassName().replace('.',File.separatorChar) + ".class");
240             cf.getParentFile().mkdirs();
241             dumpClass(c,refs,cf);
242         }
243     }
244     
245     private void dumpClass(JavaClass c, Hashtable refs, File file) throws IOException {
246         ClassGen cg = new ClassGen(c);
247         Method[] methods= c.getMethods();
248         for(int i=0;i<methods.length;i++) {
249             Method m = methods[i];
250             MethodRef mr = new MethodRef(c,m);
251             if(refs.get(mr) == null) {
252                 System.err.println("Removing method " + mr);
253                 if(false) {
254                     cg.removeMethod(m);
255                 } else {
256                     InstructionFactory fac = new InstructionFactory(cg,cg.getConstantPool());
257                     InstructionList il = new InstructionList();
258                     MethodGen mg = new MethodGen(m.getAccessFlags(),m.getReturnType(),m.getArgumentTypes(),null,m.getName(),c.getClassName(),il,cg.getConstantPool());
259                     il.append(fac.createNew("java.lang.UnsatisfiedLinkError"));
260                     il.append(InstructionConstants.DUP);
261                     il.append(new PUSH(cg.getConstantPool(),"" + mr + " has been pruned"));
262                     il.append(fac.createInvoke("java.lang.UnsatisfiedLinkError","<init>",Type.VOID, new Type[]{Type.STRING},Constants.INVOKESPECIAL));
263                     il.append(InstructionConstants.ATHROW);
264                     mg.setMaxStack();
265                     mg.setMaxLocals();
266                     cg.replaceMethod(m,mg.getMethod());
267                 }
268             } else {
269                 //System.err.println("Keeping method " + mr);
270             }
271         }
272         
273         Field[] fields = c.getFields();
274         for(int i=0;i<fields.length;i++) {
275             Field f = fields[i];
276             FieldRef fr = new FieldRef(c,f);
277             if(refs.get(fr) == null) {
278                 System.err.println("Removing field " + fr);
279                 cg.removeField(f);
280             } else {
281                 //System.err.println("Keeping field " + fr);
282             }
283         }
284         
285         JavaClass n = cg.getJavaClass();
286         n.dump(file);
287     }
288     
289     public static class Exn extends Exception { public Exn(String s) { super(s); } }
290         
291         
292     private static class MethodRef {
293         ObjectType c;
294         String name;
295         Type ret;
296         Type[] args;
297         
298         public MethodRef(JavaClass c, Method m) {
299             this(new ObjectType(c.getClassName()),m.getName(),m.getReturnType(),m.getArgumentTypes());
300         }
301         
302         public MethodRef(InvokeInstruction i, ConstantPoolGen cp) {
303             this(i.getClassType(cp),i.getMethodName(cp),i.getReturnType(cp),i.getArgumentTypes(cp));
304         }
305         
306         public MethodRef(ObjectType c, String name, Type ret, Type[] args) { this.c = c; this.name = name; this.ret = ret; this.args = args; }
307         
308         public boolean equals(Object o_) {
309             if(!(o_ instanceof MethodRef)) return false;
310             MethodRef o = (MethodRef)o_;
311             boolean r = name.equals(o.name) && c.equals(o.c) && ret.equals(o.ret) && Arrays.equals(args,o.args);
312             return r;
313         }
314         // FIXME: ArrayType.java in BCEL doesn't properly implement hashCode()
315         public int hashCode() {
316             int hc = name.hashCode()  ^ c.hashCode(); //^ ret.hashCode();
317             //for(int i=0;i<args.length;i++) hc ^= args[i].hashCode();
318             return hc;
319         }
320         public String toString() { return c.toString() + "." + name + Type.getMethodSignature(ret,args); }
321     }
322     
323     public static class FieldRef {
324         ObjectType c;
325         String name;
326         Type ftype;
327         
328         public FieldRef(JavaClass c, Field f) {
329             this(new ObjectType(c.getClassName()),f.getName(),f.getType());
330         }
331         
332         public FieldRef(FieldInstruction i, ConstantPoolGen cp) {
333             this(i.getClassType(cp),i.getFieldName(cp),i.getFieldType(cp));
334         }
335         public FieldRef(ObjectType c, String name, Type ftype) { this.c = c; this.name = name; this.ftype = ftype; }
336         
337         public boolean equals(Object o_) {
338             if(!(o_ instanceof FieldRef)) return false;
339             FieldRef o = (FieldRef)o_;
340             return name.equals(o.name) && c.equals(o.c);
341         }
342         public int hashCode() { return name.hashCode() ^ c.hashCode(); }
343         public String toString() { return c.toString() + "." + name; }
344     }
345 }