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 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]);
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());
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);
80 public final ObjectType referenceClass(ObjectType t) {
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);
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]));
98 public final void referenceMethod(MethodRef m) {
99 if(completed.get(m) != null) return;
101 if(m.c.getClassName().startsWith("[")) {
102 completed.put(m,Boolean.TRUE);
106 Hashtable h = classRefHash(m.c);
107 h.put(m,Boolean.TRUE);
110 referenceClass(m.ret);
111 for(int i=0;i<m.args.length;i++) referenceClass(m.args[i]);
114 public final void referenceField(FieldRef f) {
115 Hashtable h = classRefHash(f.c);
116 h.put(f,Boolean.TRUE);
117 referenceClass(f.ftype);
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;
128 public void go() throws Exn, ClassNotFoundException {
129 while(work.size() != 0) {
130 while(work.size() != 0) process((MethodRef) work.remove(work.size()-1));
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);
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);
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);
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);
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);
179 //System.err.println("Processing " + mr + "...");
181 JavaClass c = repoGet(mr.c.toString());
183 if(!c.isClass() && !mr.name.equals("<clinit>")) return;
185 Method m = findMethod(c,mr);
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; }
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;
197 throw new Exn("Couldn't find " + sig);
200 Code code = m.getCode();
201 if(code == null) return;
203 ConstantPoolGen cpg = (ConstantPoolGen) cpgCache.get(c);
204 if(cpg == null) cpgCache.put(c,cpg=new ConstantPoolGen(c.getConstantPool()));
206 InstructionList insnList = new InstructionList(code.getCode());
207 Instruction[] insns = insnList.getInstructions();
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));
220 private static Method findMethod(JavaClass c, MethodRef mr) {
221 Method[] ms = c.getMethods();
222 for(int i=0;i<ms.length;i++) {
224 if(m.getName().equals(mr.name) && m.getReturnType().equals(mr.ret) && Arrays.equals(m.getArgumentTypes(),mr.args))
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);
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);
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);
266 cg.replaceMethod(m,mg.getMethod());
269 //System.err.println("Keeping method " + mr);
273 Field[] fields = c.getFields();
274 for(int i=0;i<fields.length;i++) {
276 FieldRef fr = new FieldRef(c,f);
277 if(refs.get(fr) == null) {
278 System.err.println("Removing field " + fr);
281 //System.err.println("Keeping field " + fr);
285 JavaClass n = cg.getJavaClass();
289 public static class Exn extends Exception { public Exn(String s) { super(s); } }
292 private static class MethodRef {
298 public MethodRef(JavaClass c, Method m) {
299 this(new ObjectType(c.getClassName()),m.getName(),m.getReturnType(),m.getArgumentTypes());
302 public MethodRef(InvokeInstruction i, ConstantPoolGen cp) {
303 this(i.getClassType(cp),i.getMethodName(cp),i.getReturnType(cp),i.getArgumentTypes(cp));
306 public MethodRef(ObjectType c, String name, Type ret, Type[] args) { this.c = c; this.name = name; this.ret = ret; this.args = args; }
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);
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();
320 public String toString() { return c.toString() + "." + name + Type.getMethodSignature(ret,args); }
323 public static class FieldRef {
328 public FieldRef(JavaClass c, Field f) {
329 this(new ObjectType(c.getClassName()),f.getName(),f.getType());
332 public FieldRef(FieldInstruction i, ConstantPoolGen cp) {
333 this(i.getClassType(cp),i.getFieldName(cp),i.getFieldType(cp));
335 public FieldRef(ObjectType c, String name, Type ftype) { this.c = c; this.name = name; this.ftype = ftype; }
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);
342 public int hashCode() { return name.hashCode() ^ c.hashCode(); }
343 public String toString() { return c.toString() + "." + name; }