duke@435: /*
duke@435: * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
duke@435: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@435: *
duke@435: * This code is free software; you can redistribute it and/or modify it
duke@435: * under the terms of the GNU General Public License version 2 only, as
duke@435: * published by the Free Software Foundation.
duke@435: *
duke@435: * This code is distributed in the hope that it will be useful, but WITHOUT
duke@435: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@435: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
duke@435: * version 2 for more details (a copy is included in the LICENSE file that
duke@435: * accompanied this code).
duke@435: *
duke@435: * You should have received a copy of the GNU General Public License version
duke@435: * 2 along with this work; if not, write to the Free Software Foundation,
duke@435: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@435: *
duke@435: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
duke@435: * CA 95054 USA or visit www.sun.com if you need additional information or
duke@435: * have any questions.
duke@435: *
duke@435: */
duke@435:
duke@435: import java.io.*;
duke@435: import java.util.*;
duke@435:
duke@435:
duke@435: /**
duke@435:
This class finds transitive closure of dependencies from a given
duke@435: root set of classes. If your project has lots of .class files and you
duke@435: want to ship only those .class files which are used (transitively)
duke@435: from a root set of classes, then you can use this utility.
duke@435: How does it work?
duke@435:
duke@435: We walk through all constant pool entries of a given class and
duke@435: find all modified UTF-8 entries. Anything that looks like a class name is
duke@435: considered as a class and we search for that class in the given
duke@435: classpath. If we find a .class of that name, then we add that class to
duke@435: list.
duke@435:
duke@435: We could have used CONSTANT_ClassInfo type constants only. But
duke@435: that will miss classes used through Class.forName or xyz.class
duke@435: construct. But, if you refer to a class name in some other string we
duke@435: would include it as dependency :(. But this is quite unlikely
duke@435: anyway. To look for exact Class.forName argument(s) would involve
duke@435: bytecode analysis. Also, we handle only simple reflection. If you
duke@435: accept name of a class from externally (for eg properties file or
duke@435: command line args for example, this utility will not be able to find
duke@435: that dependency. In such cases, include those classes in the root set.
duke@435:
duke@435: */
duke@435:
duke@435: public class ClosureFinder {
duke@435: private Collection roots; // root class names Collection
duke@435: private Map visitedClasses; // set of all dependencies as a Map
duke@435: private String classPath; // classpath to look for .class files
duke@435: private String[] pathComponents; // classpath components
duke@435: private static final boolean isWindows = File.separatorChar != '/';
duke@435:
duke@435: public ClosureFinder(Collection roots, String classPath) {
duke@435: this.roots = roots;
duke@435: this.classPath = classPath;
duke@435: parseClassPath();
duke@435: }
duke@435:
duke@435: // parse classPath into pathComponents array
duke@435: private void parseClassPath() {
duke@435: List paths = new ArrayList();
duke@435: StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator);
duke@435: while (st.hasMoreTokens())
duke@435: paths.add(st.nextToken());
duke@435:
duke@435: Object[] arr = paths.toArray();
duke@435: pathComponents = new String[arr.length];
duke@435: System.arraycopy(arr, 0, pathComponents, 0, arr.length);
duke@435: }
duke@435:
duke@435: // if output is aleady not computed, compute it now
duke@435: // result is a map from class file name to base path where the .class was found
duke@435: public Map find() {
duke@435: if (visitedClasses == null) {
duke@435: visitedClasses = new HashMap();
duke@435: computeClosure();
duke@435: }
duke@435: return visitedClasses;
duke@435: }
duke@435:
duke@435: // compute closure for all given root classes
duke@435: private void computeClosure() {
duke@435: for (Iterator rootsItr = roots.iterator(); rootsItr.hasNext();) {
duke@435: String name = (String) rootsItr.next();
duke@435: name = name.substring(0, name.indexOf(".class"));
duke@435: computeClosure(name);
duke@435: }
duke@435: }
duke@435:
duke@435:
duke@435: // looks up for .class in pathComponents and returns
duke@435: // base path if found, else returns null
duke@435: private String lookupClassFile(String classNameAsPath) {
duke@435: for (int i = 0; i < pathComponents.length; i++) {
duke@435: File f = new File(pathComponents[i] + File.separator +
duke@435: classNameAsPath + ".class");
duke@435: if (f.exists()) {
duke@435: if (isWindows) {
duke@435: String name = f.getName();
duke@435: // Windows reports special devices AUX,NUL,CON as files
duke@435: // under any directory. It does not care about file extention :-(
duke@435: if (name.compareToIgnoreCase("AUX.class") == 0 ||
duke@435: name.compareToIgnoreCase("NUL.class") == 0 ||
duke@435: name.compareToIgnoreCase("CON.class") == 0) {
duke@435: return null;
duke@435: }
duke@435: }
duke@435: return pathComponents[i];
duke@435: }
duke@435: }
duke@435: return null;
duke@435: }
duke@435:
duke@435:
duke@435: // from JVM spec. 2'nd edition section 4.4
duke@435: private static final int CONSTANT_Class = 7;
duke@435: private static final int CONSTANT_FieldRef = 9;
duke@435: private static final int CONSTANT_MethodRef = 10;
duke@435: private static final int CONSTANT_InterfaceMethodRef = 11;
duke@435: private static final int CONSTANT_String = 8;
duke@435: private static final int CONSTANT_Integer = 3;
duke@435: private static final int CONSTANT_Float = 4;
duke@435: private static final int CONSTANT_Long = 5;
duke@435: private static final int CONSTANT_Double = 6;
duke@435: private static final int CONSTANT_NameAndType = 12;
duke@435: private static final int CONSTANT_Utf8 = 1;
duke@435:
duke@435: // whether a given string may be a class name?
duke@435: private boolean mayBeClassName(String internalClassName) {
duke@435: int len = internalClassName.length();
duke@435: for (int s = 0; s < len; s++) {
duke@435: char c = internalClassName.charAt(s);
duke@435: if (!Character.isJavaIdentifierPart(c) && c != '/')
duke@435: return false;
duke@435: }
duke@435: return true;
duke@435: }
duke@435:
duke@435: // compute closure for a given class
duke@435: private void computeClosure(String className) {
duke@435: if (visitedClasses.get(className) != null) return;
duke@435: String basePath = lookupClassFile(className);
duke@435: if (basePath != null) {
duke@435: visitedClasses.put(className, basePath);
duke@435: try {
duke@435: File classFile = new File(basePath + File.separator + className + ".class");
duke@435: FileInputStream fis = new FileInputStream(classFile);
duke@435: DataInputStream dis = new DataInputStream(fis);
duke@435: // look for .class signature
duke@435: if (dis.readInt() != 0xcafebabe) {
duke@435: System.err.println(classFile.getAbsolutePath() + " is not a valid .class file");
duke@435: return;
duke@435: }
duke@435:
duke@435: // ignore major and minor version numbers
duke@435: dis.readShort();
duke@435: dis.readShort();
duke@435:
duke@435: // read number of constant pool constants
duke@435: int numConsts = (int) dis.readShort();
duke@435: String[] strings = new String[numConsts];
duke@435:
duke@435: // zero'th entry is unused
duke@435: for (int cpIndex = 1; cpIndex < numConsts; cpIndex++) {
duke@435: int constType = (int) dis.readByte();
duke@435: switch (constType) {
duke@435: case CONSTANT_Class:
duke@435: case CONSTANT_String:
duke@435: dis.readShort(); // string name index;
duke@435: break;
duke@435:
duke@435: case CONSTANT_FieldRef:
duke@435: case CONSTANT_MethodRef:
duke@435: case CONSTANT_InterfaceMethodRef:
duke@435: case CONSTANT_NameAndType:
duke@435: case CONSTANT_Integer:
duke@435: case CONSTANT_Float:
duke@435: // all these are 4 byte constants
duke@435: dis.readInt();
duke@435: break;
duke@435:
duke@435: case CONSTANT_Long:
duke@435: case CONSTANT_Double:
duke@435: // 8 byte constants
duke@435: dis.readLong();
duke@435: // occupies 2 cp entries
duke@435: cpIndex++;
duke@435: break;
duke@435:
duke@435:
duke@435: case CONSTANT_Utf8: {
duke@435: strings[cpIndex] = dis.readUTF();
duke@435: break;
duke@435: }
duke@435:
duke@435: default:
duke@435: System.err.println("invalid constant pool entry");
duke@435: return;
duke@435: }
duke@435: }
duke@435:
duke@435: // now walk thru the string constants and look for class names
duke@435: for (int s = 0; s < numConsts; s++) {
duke@435: if (strings[s] != null && mayBeClassName(strings[s]))
duke@435: computeClosure(strings[s].replace('/', File.separatorChar));
duke@435: }
duke@435:
duke@435: } catch (IOException exp) {
duke@435: // ignore for now
duke@435: }
duke@435:
duke@435: }
duke@435: }
duke@435:
duke@435: // a sample main that accepts roots classes in a file and classpath as args
duke@435: public static void main(String[] args) {
duke@435: if (args.length != 2) {
duke@435: System.err.println("Usage: ClosureFinder ");
duke@435: System.exit(1);
duke@435: }
duke@435:
duke@435: List roots = new ArrayList();
duke@435: try {
duke@435: FileInputStream fis = new FileInputStream(args[0]);
duke@435: DataInputStream dis = new DataInputStream(fis);
duke@435: String line = null;
duke@435: while ((line = dis.readLine()) != null) {
duke@435: if (isWindows) {
duke@435: line = line.replace('/', File.separatorChar);
duke@435: }
duke@435: roots.add(line);
duke@435: }
duke@435: } catch (IOException exp) {
duke@435: System.err.println(exp.getMessage());
duke@435: System.exit(2);
duke@435: }
duke@435:
duke@435: ClosureFinder cf = new ClosureFinder(roots, args[1]);
duke@435: Map out = cf.find();
duke@435: Iterator res = out.keySet().iterator();
duke@435: for(; res.hasNext(); ) {
duke@435: String className = (String) res.next();
duke@435: System.out.println(className + ".class");
duke@435: }
duke@435: }
duke@435: }