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