1 // Copyright (C) 2004 Brian Alliet
3 // Based on NanoGoat by Adam Megac
5 // Copyright (C) 2004 Adam Megacz <adam@ibex.org> all rights reserved.
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
12 package com.brian_web.gcclass;
17 import org.apache.bcel.Constants;
18 import org.apache.bcel.util.*;
19 import org.apache.bcel.generic.*;
20 import org.apache.bcel.classfile.*;
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
25 public class GCClass {
26 private static final String[] PRE_REF = {
27 "java.lang.Thread.run",
28 "java.security.PrivilegedAction.run"
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;",
41 private static final String[] NO_OUTPUT = { "java", "javax", "sun", "com.sun", "apple", "com.apple" };
44 public static void main(String[] args) throws Exception {
46 System.err.println("Usage GCClass classpath outdir entrypoint1 ... [ entrypoint n]");
49 GCClass gc = new GCClass(args[0]);
50 for(int i=2;i<args.length;i++) gc.referenceMethod(args[i]);
52 gc.dump(new File(args[1]));
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();
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]);
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());
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);
79 public final ObjectType referenceClass(ObjectType t) {
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);
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]));
97 public final void referenceMethod(MethodRef m) {
98 if(completed.get(m) != null) return;
100 if(m.c.getClassName().startsWith("[")) {
101 completed.put(m,Boolean.TRUE);
105 Hashtable h = classRefHash(m.c);
106 h.put(m,Boolean.TRUE);
109 referenceClass(m.ret);
110 for(int i=0;i<m.args.length;i++) referenceClass(m.args[i]);
113 public final void referenceField(FieldRef f) {
114 Hashtable h = classRefHash(f.c);
115 h.put(f,Boolean.TRUE);
116 referenceClass(f.ftype);
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;
127 public void go() throws Exn, ClassNotFoundException {
128 while(work.size() != 0) {
129 while(work.size() != 0) process((MethodRef) work.remove(work.size()-1));
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);
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);
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);
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);
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);
178 //System.err.println("Processing " + mr + "...");
180 JavaClass c = repoGet(mr.c.toString());
182 if(!c.isClass() && !mr.name.equals("<clinit>")) return;
184 Method m = findMethod(c,mr);
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; }
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;
196 throw new Exn("Couldn't find " + sig);
199 Code code = m.getCode();
200 if(code == null) return;
202 ConstantPoolGen cpg = (ConstantPoolGen) cpgCache.get(c);
203 if(cpg == null) cpgCache.put(c,cpg=new ConstantPoolGen(c.getConstantPool()));
205 InstructionList insnList = new InstructionList(code.getCode());
206 Instruction[] insns = insnList.getInstructions();
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));
219 private static Method findMethod(JavaClass c, MethodRef mr) {
220 Method[] ms = c.getMethods();
221 for(int i=0;i<ms.length;i++) {
223 if(m.getName().equals(mr.name) && m.getReturnType().equals(mr.ret) && Arrays.equals(m.getArgumentTypes(),mr.args))
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);
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);
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);
265 cg.replaceMethod(m,mg.getMethod());
268 //System.err.println("Keeping method " + mr);
272 Field[] fields = c.getFields();
273 for(int i=0;i<fields.length;i++) {
275 FieldRef fr = new FieldRef(c,f);
276 if(refs.get(fr) == null) {
277 System.err.println("Removing field " + fr);
280 //System.err.println("Keeping field " + fr);
284 JavaClass n = cg.getJavaClass();
288 public static class Exn extends Exception { public Exn(String s) { super(s); } }
291 private static class MethodRef {
297 public MethodRef(JavaClass c, Method m) {
298 this(new ObjectType(c.getClassName()),m.getName(),m.getReturnType(),m.getArgumentTypes());
301 public MethodRef(InvokeInstruction i, ConstantPoolGen cp) {
302 this(i.getClassType(cp),i.getMethodName(cp),i.getReturnType(cp),i.getArgumentTypes(cp));
305 public MethodRef(ObjectType c, String name, Type ret, Type[] args) { this.c = c; this.name = name; this.ret = ret; this.args = args; }
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);
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();
319 public String toString() { return c.toString() + "." + name + Type.getMethodSignature(ret,args); }
322 public static class FieldRef {
327 public FieldRef(JavaClass c, Field f) {
328 this(new ObjectType(c.getClassName()),f.getName(),f.getType());
331 public FieldRef(FieldInstruction i, ConstantPoolGen cp) {
332 this(i.getClassType(cp),i.getFieldName(cp),i.getFieldType(cp));
334 public FieldRef(ObjectType c, String name, Type ftype) { this.c = c; this.name = name; this.ftype = ftype; }
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);
341 public int hashCode() { return name.hashCode() ^ c.hashCode(); }
342 public String toString() { return c.toString() + "." + name; }