typo
[org.ibex.gcclass.git] / src / com / brian_web / gcclass / GCClass.java
1 // Copyright (C) 2004 Brian Alliet
2
3 // Based on NanoGoat by Adam Megacz
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         repo = SyntheticRepository.getInstance(new ClassPath(ClassPath.SYSTEM_CLASS_PATH + File.pathSeparator + classpath));
62         for(int i=0;i<PRE_REF.length;i++) referenceMethod(PRE_REF[i]);
63     }
64     
65     private Hashtable classRefHash(JavaClass c) { return classRefHash(new ObjectType(c.getClassName())); }
66     private Hashtable classRefHash(ObjectType c) {
67         Hashtable h = (Hashtable) references.get(c);
68         if(h == null) references.put(c,h=new Hashtable());
69         return h;
70     }
71     
72     public final ObjectType referenceClass(JavaClass c) { return referenceClass(c.getClassName()); }
73     public final ObjectType referenceClass(String s) { return referenceClass(new ObjectType(s)); }
74     public final ObjectType referenceClass(Type t) {
75         if(t instanceof ObjectType) return referenceClass((ObjectType)t);
76         return null;
77     }
78     
79     public final ObjectType referenceClass(ObjectType t) {
80         classRefHash(t);
81         return t;
82     }
83     
84     public final void referenceMethod(String s) throws ClassNotFoundException {
85         int p = s.lastIndexOf('.');
86         if(p == -1) throw new IllegalArgumentException("invalid class/method string");
87         String cs = s.substring(0,p);
88         String ms = s.substring(p+1);
89         
90         JavaClass c = repoGet(cs);
91         Method[] methods = c.getMethods();
92         for(int i=0;i<methods.length;i++)
93             if(methods[i].getName().equals(ms))
94                 referenceMethod(new MethodRef(c,methods[i]));
95     }
96         
97     public final void referenceMethod(MethodRef m) {
98         if(completed.get(m) != null) return;
99         
100         if(m.c.getClassName().startsWith("[")) {
101             completed.put(m,Boolean.TRUE);
102             return;
103         }
104         
105         Hashtable h = classRefHash(m.c);
106         h.put(m,Boolean.TRUE);
107         work.add(m);
108         
109         referenceClass(m.ret);
110         for(int i=0;i<m.args.length;i++) referenceClass(m.args[i]);
111     }
112     
113     public final void referenceField(FieldRef f) {
114         Hashtable h = classRefHash(f.c);
115         h.put(f,Boolean.TRUE);
116         referenceClass(f.ftype);
117     }
118     
119     private Hashtable repoCache = new Hashtable();
120     public JavaClass repoGet(ObjectType t) throws ClassNotFoundException { return repoGet(t.getClassName()); }
121     public JavaClass repoGet(String s) throws ClassNotFoundException {
122         Object o = repoCache.get(s);
123         if(o == null) repoCache.put(s,o = repo.loadClass(s));
124         return (JavaClass) o;
125     }
126     
127     public void go() throws Exn, ClassNotFoundException {
128         while(work.size() != 0) {
129             while(work.size() != 0) process((MethodRef) work.remove(work.size()-1));
130             fixup();
131         }
132     }
133     
134     private void fixup() throws ClassNotFoundException {
135         for(Enumeration e = references.keys(); e.hasMoreElements(); ) {
136             ObjectType t = (ObjectType) e.nextElement();
137             JavaClass c = repoGet(t);
138             if(c == null) continue;
139             Hashtable refs = (Hashtable) references.get(t);
140             if(refs.size() != 0) {
141                 MethodRef clinit = new MethodRef(t,"<clinit>",Type.VOID,Type.NO_ARGS);
142                 if(findMethod(c,clinit) != null) referenceMethod(clinit);
143             }
144             Method[] methods = c.getMethods();
145             JavaClass[] supers = c.getSuperClasses();
146             JavaClass[] interfaces = c.getInterfaces();
147             //System.err.println("Fixing up " + t);
148             for(int i=0;i<supers.length;i++) referenceClass(supers[i]);
149             for(int i=0;methods != null && i<methods.length;i++) {
150                 MethodRef mr = new MethodRef(c,methods[i]);
151                 if(refs.get(mr) != null) continue;
152                 for(int j=0;j<supers.length;j++) {
153                     MethodRef smr = new MethodRef(supers[j],methods[i]);
154                     Hashtable srefs = classRefHash(supers[j]);
155                     if(srefs.get(smr) != null) referenceMethod(mr);
156                     
157                     JavaClass[] interfaces2 = supers[j].getInterfaces();
158                     for(int k=0;interfaces2 != null && k<interfaces2.length;k++) {
159                         MethodRef imr = new MethodRef(interfaces2[k],methods[i]);
160                         Hashtable irefs = classRefHash(interfaces2[k]);
161                         if(irefs.get(imr) != null) referenceMethod(mr);
162                     }
163                 }
164                 for(int j=0;interfaces != null && j<interfaces.length;j++) {
165                     MethodRef imr = new MethodRef(interfaces[j],methods[i]);
166                     Hashtable irefs = classRefHash(interfaces[j]);
167                     if(irefs.get(imr) != null) referenceMethod(mr);
168                 }
169             }                                             
170         }
171     }
172     
173     private Hashtable cpgCache = new Hashtable();
174     private void process(MethodRef mr) throws Exn, ClassNotFoundException {
175         if(completed.get(mr) != null) return;
176         completed.put(mr,Boolean.TRUE);
177         
178         //System.err.println("Processing " + mr + "...");
179
180         JavaClass c = repoGet(mr.c.toString());
181         
182         if(!c.isClass() && !mr.name.equals("<clinit>")) return;
183         
184         Method m = findMethod(c,mr);
185         if(m == null) {
186             JavaClass supers[] = c.getSuperClasses();
187             for(int i=0;i<supers.length;i++) {
188                 m = findMethod(supers[i],mr);
189                 if(m != null) { referenceMethod(new MethodRef(supers[i],m)); return; }
190             }
191             String sig = mr.toString();
192             for(int i=0;i<IGNORED_METHODS.length;i++) {
193                 String pat = IGNORED_METHODS[i];
194                 if(pat.endsWith("*") ? sig.startsWith(pat.substring(0,pat.length()-1)) : sig.equals(pat)) return;
195             }
196             throw new Exn("Couldn't find " + sig);
197         }
198         
199         Code code = m.getCode();
200         if(code == null) return;
201         
202         ConstantPoolGen cpg = (ConstantPoolGen) cpgCache.get(c);
203         if(cpg == null) cpgCache.put(c,cpg=new ConstantPoolGen(c.getConstantPool()));
204         
205         InstructionList insnList = new InstructionList(code.getCode());
206         Instruction[] insns = insnList.getInstructions();
207         
208         for(int n=0;n<insns.length;n++) {
209             Instruction i = insns[n];
210             if(i instanceof ANEWARRAY || i instanceof CHECKCAST || i instanceof INSTANCEOF || i instanceof MULTIANEWARRAY || i instanceof NEW)
211                 referenceClass(((CPInstruction)i).getType(cpg));
212             else if(i instanceof FieldInstruction) // GETFIED, GETSTATIC, PUTFIELD, PUTSTATIC
213                 referenceField(new FieldRef((FieldInstruction)i,cpg));
214             else if(i instanceof InvokeInstruction) // INVOKESTATIC, INVOKEVIRTUAL, INVOKESPECIAL
215                 referenceMethod(new MethodRef((InvokeInstruction)i,cpg));
216         }
217     }
218     
219     private static Method findMethod(JavaClass c, MethodRef mr) {
220         Method[] ms = c.getMethods();
221         for(int i=0;i<ms.length;i++) {
222             Method m = ms[i];
223             if(m.getName().equals(mr.name) && m.getReturnType().equals(mr.ret) && Arrays.equals(m.getArgumentTypes(),mr.args))
224                return m;
225         }
226         return null;
227     }
228     
229     public void dump(File outdir) throws IOException, ClassNotFoundException {
230         if(!outdir.isDirectory()) throw new IOException("" + outdir + " is not a directory");
231         OUTER: for(Enumeration e = references.keys(); e.hasMoreElements(); ) {
232             ObjectType t = (ObjectType) e.nextElement();
233             String name =  t.getClassName();
234             for(int i=0;i<NO_OUTPUT.length;i++) if(name.startsWith(NO_OUTPUT[i])) continue OUTER;
235             Hashtable refs = (Hashtable) references.get(t);
236             JavaClass c = repoGet(t.getClassName());
237             if(c == null) continue;
238             File cf = new File(outdir,t.getClassName().replace('.',File.separatorChar) + ".class");
239             cf.getParentFile().mkdirs();
240             dumpClass(c,refs,cf);
241         }
242     }
243     
244     private void dumpClass(JavaClass c, Hashtable refs, File file) throws IOException {
245         ClassGen cg = new ClassGen(c);
246         Method[] methods= c.getMethods();
247         for(int i=0;i<methods.length;i++) {
248             Method m = methods[i];
249             MethodRef mr = new MethodRef(c,m);
250             if(refs.get(mr) == null) {
251                 System.err.println("Removing method " + mr);
252                 if(false) {
253                     cg.removeMethod(m);
254                 } else {
255                     InstructionFactory fac = new InstructionFactory(cg,cg.getConstantPool());
256                     InstructionList il = new InstructionList();
257                     MethodGen mg = new MethodGen(m.getAccessFlags(),m.getReturnType(),m.getArgumentTypes(),null,m.getName(),c.getClassName(),il,cg.getConstantPool());
258                     il.append(fac.createNew("java.lang.UnsatisfiedLinkError"));
259                     il.append(InstructionConstants.DUP);
260                     il.append(new PUSH(cg.getConstantPool(),"" + mr + " has been pruned"));
261                     il.append(fac.createInvoke("java.lang.UnsatisfiedLinkError","<init>",Type.VOID, new Type[]{Type.STRING},Constants.INVOKESPECIAL));
262                     il.append(InstructionConstants.ATHROW);
263                     mg.setMaxStack();
264                     mg.setMaxLocals();
265                     cg.replaceMethod(m,mg.getMethod());
266                 }
267             } else {
268                 //System.err.println("Keeping method " + mr);
269             }
270         }
271         
272         Field[] fields = c.getFields();
273         for(int i=0;i<fields.length;i++) {
274             Field f = fields[i];
275             FieldRef fr = new FieldRef(c,f);
276             if(refs.get(fr) == null) {
277                 System.err.println("Removing field " + fr);
278                 cg.removeField(f);
279             } else {
280                 //System.err.println("Keeping field " + fr);
281             }
282         }
283         
284         JavaClass n = cg.getJavaClass();
285         n.dump(file);
286     }
287     
288     public static class Exn extends Exception { public Exn(String s) { super(s); } }
289         
290         
291     private static class MethodRef {
292         ObjectType c;
293         String name;
294         Type ret;
295         Type[] args;
296         
297         public MethodRef(JavaClass c, Method m) {
298             this(new ObjectType(c.getClassName()),m.getName(),m.getReturnType(),m.getArgumentTypes());
299         }
300         
301         public MethodRef(InvokeInstruction i, ConstantPoolGen cp) {
302             this(i.getClassType(cp),i.getMethodName(cp),i.getReturnType(cp),i.getArgumentTypes(cp));
303         }
304         
305         public MethodRef(ObjectType c, String name, Type ret, Type[] args) { this.c = c; this.name = name; this.ret = ret; this.args = args; }
306         
307         public boolean equals(Object o_) {
308             if(!(o_ instanceof MethodRef)) return false;
309             MethodRef o = (MethodRef)o_;
310             boolean r = name.equals(o.name) && c.equals(o.c) && ret.equals(o.ret) && Arrays.equals(args,o.args);
311             return r;
312         }
313         // FIXME: ArrayType.java in BCEL doesn't properly implement hashCode()
314         public int hashCode() {
315             int hc = name.hashCode()  ^ c.hashCode(); //^ ret.hashCode();
316             //for(int i=0;i<args.length;i++) hc ^= args[i].hashCode();
317             return hc;
318         }
319         public String toString() { return c.toString() + "." + name + Type.getMethodSignature(ret,args); }
320     }
321     
322     public static class FieldRef {
323         ObjectType c;
324         String name;
325         Type ftype;
326         
327         public FieldRef(JavaClass c, Field f) {
328             this(new ObjectType(c.getClassName()),f.getName(),f.getType());
329         }
330         
331         public FieldRef(FieldInstruction i, ConstantPoolGen cp) {
332             this(i.getClassType(cp),i.getFieldName(cp),i.getFieldType(cp));
333         }
334         public FieldRef(ObjectType c, String name, Type ftype) { this.c = c; this.name = name; this.ftype = ftype; }
335         
336         public boolean equals(Object o_) {
337             if(!(o_ instanceof FieldRef)) return false;
338             FieldRef o = (FieldRef)o_;
339             return name.equals(o.name) && c.equals(o.c);
340         }
341         public int hashCode() { return name.hashCode() ^ c.hashCode(); }
342         public String toString() { return c.toString() + "." + name; }
343     }
344 }