reference superclass fields
[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 public class GCClass {
23     private static final String[] PRE_REF = {
24         "java.lang.Thread.run",
25         "java.security.PrivilegedAction.run"
26     };
27     
28     // NOTE: This doesn't mean these classes are ignored alltogether
29     //       failures to resolve them are just ignored
30     private static final String[] IGNORED_METHODS = {
31         "java.net.SocketImpl.setOption(ILjava/lang/Object;)V",
32         "java.net.SocketImpl.getOption(I)Ljava/lang/Object;",
33         "java.awt.geom.*",
34         "apple.awt.*",
35         "java.security.*"
36     };
37     
38     private static final String[] IGNORED_FIELDS = {
39         "java.io.ObjectInputStream.SUBCLASS_IMPLEMENTATION_PERMISSION"
40     };
41     
42     private static final String[] NO_OUTPUT = { "java", "javax", "sun", "com.sun", "apple", "com.apple" };
43     
44     
45     public static void main(String[] args) throws Exception {
46         if(args.length < 3) {
47             System.err.println("Usage GCClass classpath outdir entrypoint1 ... [ entrypoint n]");
48             System.exit(1);
49         }
50         GCClass gc = new GCClass(args[0]);
51         for(int i=2;i<args.length;i++) gc.referenceMethod(args[i]);
52         gc.go();
53         gc.dump(new File(args[1]));
54     }
55     
56     private final Repository repo;
57     private final Vector work = new Vector();
58     private final Hashtable completed = new Hashtable();
59     private final Hashtable references = new Hashtable();
60     private final Hashtable instansiated = new Hashtable();
61     
62     public GCClass(String classpath) throws ClassNotFoundException {
63         if(classpath.startsWith("="))
64             classpath = classpath.substring(1);
65         else
66             classpath = ClassPath.SYSTEM_CLASS_PATH + File.pathSeparator + classpath;
67         repo = SyntheticRepository.getInstance(new ClassPath(classpath));
68         for(int i=0;i<PRE_REF.length;i++) {
69             try {
70                 referenceMethod(PRE_REF[i]);
71             } catch(ClassNotFoundException e) {
72                 System.err.println("WARNING: Couldn't preref: " + PRE_REF[i]);
73             }
74         }
75     }
76     
77     private Hashtable classRefHash(JavaClass c) { return classRefHash(new ObjectType(c.getClassName())); }
78     private Hashtable classRefHash(ObjectType c) {
79         Hashtable h = (Hashtable) references.get(c);
80         if(h == null) references.put(c,h=new Hashtable());
81         return h;
82     }
83     
84     public final ObjectType referenceClass(JavaClass c) { return referenceClass(c.getClassName()); }
85     public final ObjectType referenceClass(String s) { return referenceClass(new ObjectType(s)); }
86     public final ObjectType referenceClass(Type t) {
87         if(t instanceof ObjectType) return referenceClass((ObjectType)t);
88         return null;
89     }
90     
91     public final ObjectType referenceClass(ObjectType t) {
92         classRefHash(t);
93         return t;
94     }
95     
96     public void referenceMethod(String s) throws ClassNotFoundException {
97         int p = s.lastIndexOf('.');
98         if(p == -1) throw new IllegalArgumentException("invalid class/method string");
99         String cs = s.substring(0,p);
100         String ms = s.substring(p+1);
101         boolean skip = false;
102         
103         if(cs.startsWith("-")) { cs = cs.substring(1); skip = true; }
104         
105         if(!skip && (ms.equals("*") || ms.equals("<init>")))
106             instansiated.put(new ObjectType(cs),Boolean.TRUE);
107         
108         JavaClass c = repoGet(cs);
109         Method[] methods = c.getMethods();
110         for(int i=0;i<methods.length;i++) {
111             if(ms.equals("*") || methods[i].getName().equals(ms)) {
112                 MethodRef mr = new MethodRef(c,methods[i]);
113                 if(skip) completed.put(mr,Boolean.TRUE);
114                 else referenceMethod(mr);
115             }
116         }
117     }
118         
119     private final void referenceMethod(MethodRef m) {
120         if(completed.get(m) != null) return;
121         
122         if(m.c.getClassName().startsWith("[")) {
123             completed.put(m,Boolean.TRUE);
124             return;
125         }
126         
127         Hashtable h = classRefHash(m.c);
128         h.put(m,Boolean.TRUE);
129         work.add(m);
130         
131         referenceClass(m.ret);
132         for(int i=0;i<m.args.length;i++) referenceClass(m.args[i]);
133     }
134     
135     private final void referenceField(FieldRef f) throws ClassNotFoundException  {
136         if(completed.get(f) != null) return;
137         
138         Hashtable h = classRefHash(f.c);
139         h.put(f,Boolean.TRUE);
140         
141         // process(FieldRef) doesn't create much work so we don't bother queuing it 
142         process(f);
143         
144         referenceClass(f.ftype);
145     }
146     
147     private Hashtable repoCache = new Hashtable();
148     private JavaClass repoGet(ObjectType t) throws ClassNotFoundException { return repoGet(t.getClassName()); }
149     private JavaClass repoGet(String s) throws ClassNotFoundException {
150         Object o = repoCache.get(s);
151         if(o == null) repoCache.put(s,o = repo.loadClass(s));
152         return (JavaClass) o;
153     }
154     
155     public void go() throws Exn {
156         while(work.size() != 0) {
157             while(work.size() != 0) {
158                 MethodRef mr = (MethodRef) work.remove(work.size()-1);
159                 try {
160                     process(mr);
161                 } catch(ClassNotFoundException e) {
162                     e.printStackTrace();
163                     String refBy = mr.refBy == null ? "unknown" : mr.refBy.toString();
164                     throw new Exn("ERROR: " + refBy + " references " + mr + " which cannot be found");
165                 }
166             }
167             try {
168                 fixup();
169             } catch(ClassNotFoundException e) {
170                 e.printStackTrace();
171                 throw new Exn("ClassNotFoundException in fixup");
172             }
173         }
174     }
175     
176     private void fixup() throws ClassNotFoundException {
177         for(Enumeration e = references.keys(); e.hasMoreElements(); ) {
178             ObjectType t = (ObjectType) e.nextElement();
179             JavaClass c = repoGet(t);
180             if(c == null) continue;
181             
182             Hashtable refs = (Hashtable) references.get(t);
183             // add a ref to clinit is any fields/methods are referenced
184             if(refs.size() != 0) {
185                 MethodRef clinit = new MethodRef(t,"<clinit>",Type.VOID,Type.NO_ARGS);
186                 if(findMethod(c,clinit) != null) referenceMethod(clinit);
187             }
188             
189             Method[] methods = c.getMethods();
190             JavaClass[] supers = c.getSuperClasses();
191             JavaClass[] interfaces = c.getInterfaces();
192             
193             // If a subclass can be instansiated all its superclasses also can
194             if(instansiated.get(t) != null) {
195                 for(int i=0;i<supers.length;i++) {
196                     ObjectType st = new ObjectType(supers[i].getClassName());
197                     if(instansiated.get(st) != null) break;
198                     instansiated.put(st, Boolean.TRUE);
199                 }
200             }
201             
202             // If a subclass is referenced all is superclasses also are
203             for(int i=0;i<supers.length;i++) referenceClass(supers[i]);
204             
205             // Go though each method and look for method references a
206             // superclass or interfaces version of the method, references them
207             // result in references to us
208             for(int i=0;methods != null && i<methods.length;i++) {
209                 MethodRef mr = new MethodRef(c,methods[i]);
210                 if(refs.get(mr) != null) continue;
211                 for(int j=0;j<supers.length;j++) {
212                     MethodRef smr = new MethodRef(supers[j],methods[i]);
213                     Hashtable srefs = classRefHash(supers[j]);
214                     if(srefs.get(smr) != null) referenceMethod(mr);
215                     
216                     JavaClass[] interfaces2 = supers[j].getInterfaces();
217                     for(int k=0;interfaces2 != null && k<interfaces2.length;k++) {
218                         MethodRef imr = new MethodRef(interfaces2[k],methods[i]);
219                         Hashtable irefs = classRefHash(interfaces2[k]);
220                         if(irefs.get(imr) != null) referenceMethod(mr);
221                     }
222                 }
223                 for(int j=0;interfaces != null && j<interfaces.length;j++) {
224                     MethodRef imr = new MethodRef(interfaces[j],methods[i]);
225                     Hashtable irefs = classRefHash(interfaces[j]);
226                     if(irefs.get(imr) != null) referenceMethod(mr);
227                 }
228             }                                             
229         }
230     }
231     
232     private Hashtable cpgCache = new Hashtable();
233     private void process(MethodRef mr) throws Exn, ClassNotFoundException {
234         if(completed.get(mr) != null) return;
235         completed.put(mr,Boolean.TRUE);
236         
237         //System.err.println("Processing " + mr + "...");
238
239         JavaClass c = repoGet(mr.c.toString());
240         
241         // interfaces can only have a clinit method - every other method has no definition
242         if(!c.isClass() && !mr.name.equals("<clinit>")) return;
243         
244         Method m = findMethod(c,mr);
245         if(m == null) {
246             JavaClass supers[] = c.getSuperClasses();
247             for(int i=0;i<supers.length;i++) {
248                 m = findMethod(supers[i],mr);
249                 if(m != null) { referenceMethod(new MethodRef(supers[i],m)); return; }
250             }
251             String sig = mr.toString();
252             for(int i=0;i<IGNORED_METHODS.length;i++) {
253                 String pat = IGNORED_METHODS[i];
254                 if(pat.endsWith("*") ? sig.startsWith(pat.substring(0,pat.length()-1)) : sig.equals(pat)) return;
255             }
256             throw new ClassNotFoundException("" + mr + " not found (but the class was)");
257         }
258         
259         Code code = m.getCode();
260         if(code == null) return;
261         
262         ConstantPoolGen cpg = (ConstantPoolGen) cpgCache.get(c);
263         if(cpg == null) cpgCache.put(c,cpg=new ConstantPoolGen(c.getConstantPool()));
264         
265         InstructionList insnList = new InstructionList(code.getCode());
266         Instruction[] insns = insnList.getInstructions();
267         
268         for(int n=0;n<insns.length;n++) {
269             Instruction i = insns[n];
270             if(i instanceof NEW)
271                 instansiated.put(((CPInstruction)i).getType(cpg),Boolean.TRUE);
272             if(i instanceof ANEWARRAY || i instanceof CHECKCAST || i instanceof INSTANCEOF || i instanceof MULTIANEWARRAY || i instanceof NEW)
273                 referenceClass(((CPInstruction)i).getType(cpg));
274             else if(i instanceof FieldInstruction) // GETFIED, GETSTATIC, PUTFIELD, PUTSTATIC
275                 referenceField(new FieldRef((FieldInstruction)i,cpg));
276             else if(i instanceof InvokeInstruction) // INVOKESTATIC, INVOKEVIRTUAL, INVOKESPECIAL
277                 referenceMethod(new MethodRef((InvokeInstruction)i,cpg,mr));
278         }
279     }
280     
281     private void process(FieldRef fr) throws ClassNotFoundException {
282         if(completed.get(fr) != null) return;
283         completed.put(fr,Boolean.TRUE);
284
285         JavaClass c = repoGet(fr.c.toString());
286         Field f = findField(c,fr);
287         if(f == null) {
288             JavaClass supers[] = c.getSuperClasses();
289             for(int i=0;i<supers.length;i++) {
290                 f = findField(supers[i],fr);
291                 if(f != null) { referenceField(new FieldRef(supers[i],f)); return; }
292             }
293             String sig = fr.toString();
294             for(int i=0;i<IGNORED_FIELDS.length;i++) {
295                 String pat = IGNORED_FIELDS[i];
296                 if(pat.endsWith("*") ? sig.startsWith(pat.substring(0,pat.length()-1)) : sig.equals(pat)) return;
297             }
298             throw new ClassNotFoundException("" + fr + " not found (but the class was)");            
299         }
300         /* nothing to do */
301     }
302     
303     private static Method findMethod(JavaClass c, MethodRef mr) {
304         Method[] ms = c.getMethods();
305         for(int i=0;i<ms.length;i++) {
306             Method m = ms[i];
307             if(m.getName().equals(mr.name) && m.getReturnType().equals(mr.ret) && Arrays.equals(m.getArgumentTypes(),mr.args))
308                return m;
309         }
310         return null;
311     }
312     
313     private static Field findField(JavaClass c, FieldRef fr) {
314         Field[] fs = c.getFields();
315         for(int i=0;i<fs.length;i++) {
316             Field f = fs[i];
317             if(f.getName().equals(fr.name) && f.getType().equals(fr.ftype))
318                 return f;
319         }
320         return null;
321     }
322     
323     public void dump(File outdir) throws IOException, ClassNotFoundException {
324         if(!outdir.isDirectory()) throw new IOException("" + outdir + " is not a directory");
325         OUTER: for(Enumeration e = references.keys(); e.hasMoreElements(); ) {
326             ObjectType t = (ObjectType) e.nextElement();
327             String name =  t.getClassName();
328             for(int i=0;i<NO_OUTPUT.length;i++) if(name.startsWith(NO_OUTPUT[i])) continue OUTER;
329             Hashtable refs = (Hashtable) references.get(t);
330             JavaClass c = repoGet(t.getClassName());
331             if(c == null) continue;
332             boolean staticOnly = c.isClass() && instansiated.get(t) == null;
333             File cf = new File(outdir,t.getClassName().replace('.',File.separatorChar) + ".class");
334             cf.getParentFile().mkdirs();
335             dumpClass(c,refs,staticOnly,cf);
336         }
337     }
338     
339     private void dumpClass(JavaClass c, Hashtable refs, boolean staticOnly, File file) throws IOException {
340         ClassGen oldCG = new ClassGen(c);
341         ConstantPoolGen oldCP = oldCG.getConstantPool();
342         
343         ConstantPoolGen cp = new ConstantPoolGen();
344         ClassGen cg = new ClassGen(c.getClassName(),c.getSuperclassName(),c.getSourceFileName(),c.getAccessFlags(),c.getInterfaceNames(),cp);
345         
346         Method[] methods= oldCG.getMethods();
347         for(int i=0;i<methods.length;i++) {
348             Method m = methods[i];
349             MethodRef mr = new MethodRef(c,m);
350             if((staticOnly && !m.isStatic()) || refs.get(mr) == null) {
351                 System.err.println("Removing method " + mr);
352                 if(true) {
353                     InstructionFactory fac = new InstructionFactory(cg,cg.getConstantPool());
354                     InstructionList il = new InstructionList();
355                     MethodGen mg = new MethodGen(m.getAccessFlags(),m.getReturnType(),m.getArgumentTypes(),null,m.getName(),c.getClassName(),il,cp);
356                     il.append(fac.createNew("java.lang.UnsatisfiedLinkError"));
357                     il.append(InstructionConstants.DUP);
358                     if(false) {
359                         il.append(new PUSH(cg.getConstantPool(),"" + mr + " has been pruned"));
360                         il.append(fac.createInvoke("java.lang.UnsatisfiedLinkError","<init>",Type.VOID, new Type[]{Type.STRING},Constants.INVOKESPECIAL));
361                     } else {
362                         il.append(fac.createInvoke("java.lang.UnsatisfiedLinkError","<init>",Type.VOID,Type.NO_ARGS,Constants.INVOKESPECIAL));
363                     }
364                     il.append(InstructionConstants.ATHROW);
365                     mg.setMaxStack();
366                     mg.setMaxLocals();
367                     cg.addMethod(mg.getMethod());
368                 }
369             } else {                
370                 MethodGen mg = new MethodGen(m,cg.getClassName(),oldCP);
371                 mg.setConstantPool(cp);
372                 if(mg.getInstructionList() != null) mg.getInstructionList().replaceConstantPool(oldCP, cp);
373                 
374                 Attribute[] attrs = m.getAttributes();
375                 for(int j=0;j<attrs.length;j++) {
376                     Attribute a = attrs[j];
377                     if(a instanceof Code || a instanceof ExceptionTable) continue;
378                     mg.removeAttribute(a);
379                     Constant con = oldCP.getConstant(a.getNameIndex());
380                     a.setNameIndex(cp.addConstant(con,oldCP));
381                     mg.addAttribute(a);                    
382                 }
383                 
384                 mg.removeLineNumbers();
385                 mg.removeLocalVariables();
386                 cg.addMethod(mg.getMethod());
387             }
388         }
389         
390         Field[] fields = c.getFields();
391         for(int i=0;i<fields.length;i++) {
392             Field f = fields[i];
393             FieldRef fr = new FieldRef(c,f);
394             if(refs.get(fr) == null) {
395                 System.err.println("Removing field " + fr);
396             } else {
397                 //System.err.println("Keeping field " + fr);
398                 FieldGen fg = new FieldGen(f.getAccessFlags(),f.getType(),f.getName(),cp);
399                 Attribute[] attrs = f.getAttributes();
400                 for(int j=0;j<attrs.length;j++) {
401                     if(attrs[j] instanceof ConstantValue) {
402                         ConstantObject co = (ConstantObject) oldCP.getConstant(((ConstantValue)attrs[i]).getConstantValueIndex());
403                         Object o = co.getConstantValue(oldCP.getConstantPool());
404                         if(co instanceof ConstantLong) fg.setInitValue(((Number)o).longValue());
405                         else if(co instanceof ConstantInteger) fg.setInitValue(((Number)o).intValue());
406                         else if(co instanceof ConstantFloat) fg.setInitValue(((Number)o).floatValue());
407                         else if(co instanceof ConstantDouble) fg.setInitValue(((Number)o).floatValue());
408                         else if(co instanceof ConstantString) fg.setInitValue((String)o);
409                         else throw new Error("should never happen");
410                     } else {
411                         Attribute a = attrs[j];
412                         Constant con = oldCP.getConstant(a.getNameIndex());
413                         a.setNameIndex(cp.addConstant(con,oldCP));
414                         //System.err.println("Adding attribute: " + attrs[j]);
415                         fg.addAttribute(a);
416                     }
417                 }
418                 /*if(f.getConstantValue() != null) throw new Error("this might be broken");
419                 FieldGen fg = new FieldGen(f.getAccessFlags(),f.getType(),f.getName(),cp);*/
420                 cg.addField(fg.getField());
421             }
422         }
423         
424         JavaClass n = cg.getJavaClass();
425         n.dump(file);
426     }
427     
428     public static class Exn extends Exception { public Exn(String s) { super(s); } }
429     
430     private static class MethodRef {
431         ObjectType c;
432         String name;
433         Type ret;
434         Type[] args;
435         MethodRef refBy;
436                 
437         public MethodRef(JavaClass c, Method m) {
438             this(new ObjectType(c.getClassName()),m.getName(),m.getReturnType(),m.getArgumentTypes());
439         }
440         
441         public MethodRef(InvokeInstruction i, ConstantPoolGen cp, MethodRef refBy) {
442             this(i.getClassType(cp),i.getMethodName(cp),i.getReturnType(cp),i.getArgumentTypes(cp));
443             this.refBy = refBy;
444         }
445         
446         public MethodRef(ObjectType c, String name, Type ret, Type[] args) { this.c = c; this.name = name; this.ret = ret; this.args = args; }
447         
448         public boolean equals(Object o_) {
449             if(!(o_ instanceof MethodRef)) return false;
450             MethodRef o = (MethodRef)o_;
451             boolean r = name.equals(o.name) && c.equals(o.c) && ret.equals(o.ret) && Arrays.equals(args,o.args);
452             return r;
453         }
454         // FIXME: ArrayType.java in BCEL doesn't properly implement hashCode()
455         public int hashCode() {
456             int hc = name.hashCode()  ^ c.hashCode(); //^ ret.hashCode();
457             //for(int i=0;i<args.length;i++) hc ^= args[i].hashCode();
458             return hc;
459         }
460         public String toString() { return c.toString() + "." + name + Type.getMethodSignature(ret,args); }
461     }
462     
463     private static class FieldRef {
464         ObjectType c;
465         String name;
466         Type ftype;
467         MethodRef refBy;
468         
469         public FieldRef(JavaClass c, Field f) {
470             this(new ObjectType(c.getClassName()),f.getName(),f.getType());
471         }
472         
473         public FieldRef(FieldInstruction i, ConstantPoolGen cp) {
474             this(i.getClassType(cp),i.getFieldName(cp),i.getFieldType(cp));
475         }
476         public FieldRef(ObjectType c, String name, Type ftype) { this.c = c; this.name = name; this.ftype = ftype; }
477         
478         public boolean equals(Object o_) {
479             if(!(o_ instanceof FieldRef)) return false;
480             FieldRef o = (FieldRef)o_;
481             return name.equals(o.name) && c.equals(o.c);
482         }
483         public int hashCode() { return name.hashCode() ^ c.hashCode(); }
484         public String toString() { return c.toString() + "." + name; }
485     }
486 }