/* ClassInfo Copyright (C) 1998-1999 Jochen Hoenicke. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package net.sf.jode.bytecode; import net.sf.jode.GlobalOptions; import net.sf.jode.util.UnifyHash; import java.io.DataInputStream; import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.OutputStream; import java.io.IOException; import java.io.FileNotFoundException; import java.util.Enumeration; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; ///#def COLLECTIONS java.util import java.util.Arrays; import java.util.Iterator; import java.util.ListIterator; import java.util.List; import java.util.ArrayList; ///#enddef ///#def COLLECTIONEXTRA java.lang import java.lang.Comparable; ///#enddef import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * Accesses, creates or modifies java bytecode classes or interfaces. * This class represents a class or interface, it can't be used for * primitive or array types. Every class/interface is associated with * a class path, which is used to load the class in memory. * *
setXXX
methods.
*
* setXXX
methods.
*
* getClassName()
also works for top level classes,
* setClassName() must only be called on inner classes and will not
* change the bytecode name.java.util.Map$Entry
is
* Entry
. If you change its ClassName to
* Yrtne
and save it, it will still be in a file called
* Map$Entry.class
, but a debugger would call it
* java.util.Map.Yrtne
. Note that you should also save
* Map
, because it also has a reference to the
* ClassName.
* java.lang.reflect.Modifier
. java.lang.Object
as their super class.
* java.util.Map$Entry
. There are four different types
* of classes:
* getOuterClass()
returns null
and
* isMethodScoped()
returns false
.
* getOuterClass()
returns not null
.
*
* The bytecode name (getName()
) of an inner class is
* most times of the form Package.Outer$Inner
. But
* ClassInfo also supports differently named classes, as long as the
* InnerClass attribute is present. The method
* getClassName()
returns the name of the inner class
* (Inner
in the above example).
*
* You can get all inner classes of a class with the
* getClasses
method.
* isMethodScoped()
returns true
and
* getClassName()
returns not null
. In
* that case getOuterClass()
returns null
,
* too.getName()
) of an method scoped class is
* most times of the form Package.Outer$Number$Inner
. But
* ClassInfo also supports differently named classes, as long as the
* InnerClass attribute is present. isMethodScoped()
returns true
and
* getClassName()
returns null
. In that
* case getOuterClass()
returns null
,
* too.getName()
) of an method scoped class is
* most times of the form Package.Outer$Number
. But
* ClassInfo also supports differently named classes, as long as the
* InnerClass attribute is present. java/lang/String
(type
* signatures); this is convenient since java bytecode does the same.
* On the other hand a class type should be represented as
* jode/bytecode/ClassInfo
class. There should be a
* method to convert to it, but I need a ClassPath for this. Should
* the method be in ClassInfo (I don't think so), should an instance
* of TypeSignature have a ClassPath as member variable, or should
* getClassInfo() take a ClassPath parameter? What about arrays?
* getSuperclass
throw the IOException
* instead (I don't like that). superClassOf
and
* implementedBy
can throw an IOException, getSuperclass not.
*
* @author Jochen Hoenicke */
public final class ClassInfo extends BinaryInfo implements Comparable {
private static ClassPath defaultClasspath;
private int status = 0;
private boolean modified = false;
private boolean isGuessed = false;
private ClassPath classpath;
private int modifiers = -1;
private String name;
private String className;
private boolean methodScoped;
private ClassInfo superclass;
private ClassInfo outerClass;
private ClassInfo[] interfaces;
private ClassInfo[] innerClasses;
private FieldInfo[] fields;
private MethodInfo[] methods;
private String sourceFile;
private boolean hasInnerClassesAttr;
/**
* This constant can be used as parameter to drop. It specifies
* that no information at all should be kept for the current class.
*
* @see #load
*/
public static final int NONE = 0;
/**
* This constant can be used as parameter to load. It specifies
* that at least the outer class information should be loaded, i.e.
* the outer class, the class name. It is the
* only information that is loaded recursively: It is also
* automatically loaded for the outer class and it is loaded for
* all inner and extra classes, if these fields are loaded.
* The reason for the recursive load is simple: In java bytecode
* a class contains the outer class information for all outer,
* inner and extra classes, so we can create this information
* without the need to read the outer class. We also need this
* information for outer and inner classes when writing a class.
*
* @see #load
*/
public static final int OUTERCLASS = 5;
/**
* This constant can be used as parameter to load. It specifies
* that at least the hierarchy information, i.e. the
* superclass/interfaces fields and the modifiers
* of this class should be loaded.
*
* @see #load
*/
public static final int HIERARCHY = 10;
/**
* This constant can be used as parameter to load. It specifies
* that all public fields, methods and inner class declarations
* should be loaded. It doesn't load method bodies.
*
* @see #load
*/
public static final int PUBLICDECLARATIONS = 20;
/**
* This constant can be used as parameter to load. It specifies
* that all the fields, methods and inner class declaration
* should be loaded. It doesn't load method bodies.
*
* @see #load
*/
public static final int DECLARATIONS = 30;
/**
* This constant can be used as parameter to load. It specifies
* that everything in the class except debugging information and
* non-standard attributes should be loaded.
*
* @see #load
*/
public static final int NODEBUG = 80;
/**
* This constant can be used as parameter to load. It specifies
* that everything in the class except non-standard attributes
* should be loaded.
*
* @see #load
*/
public static final int ALMOSTALL = 90;
/**
* This constant can be used as parameter to load. It specifies
* that everything in the class should be loaded.
*
* @see #load
*/
public static final int ALL = 100;
/**
* @deprecated
*/
public static void setClassPath(String path) {
setClassPath(new ClassPath(path));
}
/**
* @deprecated
*/
public static void setClassPath(ClassPath path) {
defaultClasspath= path;
}
/**
* @deprecated
*/
public static boolean exists(String name) {
return defaultClasspath.existsClass(name);
}
/**
* @deprecated
*/
public static boolean isPackage(String name) {
return defaultClasspath.isDirectory(name.replace('.', '/'));
}
/**
* @deprecated
*/
public static Enumeration getClassesAndPackages(String packageName) {
return defaultClasspath.listClassesAndPackages(packageName);
}
/**
* @deprecated
*/
public static ClassInfo forName(String name) {
return defaultClasspath.getClassInfo(name);
}
ClassInfo(String name, ClassPath classpath) {
this.name = name.intern();
this.classpath = classpath;
}
/**
* Returns the classpath in which this class was created.
*/
public ClassPath getClassPath() {
return classpath;
}
/****** READING CLASS FILES ***************************************/
private static int javaModifiersToBytecode(int javaModifiers) {
int modifiers = javaModifiers & (Modifier.FINAL
| 0x20 /*ACC_SUPER*/
| Modifier.INTERFACE
| Modifier.ABSTRACT);
if ((javaModifiers & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0)
return Modifier.PUBLIC | modifiers;
else
return modifiers;
}
private void mergeModifiers(int newModifiers) {
if (modifiers == -1) {
modifiers = newModifiers;
return;
}
if (((modifiers ^ newModifiers) & ~0x20) == 0) {
modifiers |= newModifiers;
return;
}
int oldSimple = javaModifiersToBytecode(modifiers);
if (((oldSimple ^ newModifiers) & ~0x20) == 0) {
modifiers |= newModifiers & 0x20;
return;
}
int newSimple = javaModifiersToBytecode(newModifiers);
if (((newSimple ^ modifiers) & ~0x20) == 0) {
modifiers = newModifiers | (modifiers & 0x20);
return;
}
throw new ClassFormatError
("modifiers in InnerClass info doesn't match: "
+ modifiers + "<->" + newModifiers);
}
private void mergeOuterInfo(String className, ClassInfo outer,
int realModifiers, boolean ms)
throws ClassFormatException
{
if (status >= OUTERCLASS) {
if ((className == null
? this.className != null : !className.equals(this.className))
|| this.outerClass != outer)
throw new ClassFormatException("Outer information mismatch "
+name+": "+className+","+outer+","+ms+"<->"+this.className +","+this.outerClass+","+this.methodScoped);
mergeModifiers(realModifiers);
} else {
if (realModifiers != -1)
mergeModifiers(realModifiers);
this.className = className;
this.outerClass = outer;
this.methodScoped = ms;
this.status = OUTERCLASS;
}
}
private void readInnerClassesAttribute(int length, ConstantPool cp,
DataInputStream input)
throws IOException
{
/* The InnerClasses attribute is transformed in a special way
* so we want to taker a closer look. According to the inner
* class specification,
*
* http://java.sun.com/products/jdk/1.1/docs/guide/innerclasses/spec/innerclasses.doc10.html#18814
*
* there are several InnerClass records in a class. We differ
* three different types:
*
* The InnerClass records for our own inner classes: They can
* easily be recognized, since this class must be mentioned in
* the outer_class_info_index field.
*
* The InnerClass records for the outer class and its outer
* classes, and so on: According to the spec, these must
* always be present if this is a class scoped class. And they
* must be in reversed order, i.e. the outer most class comes
* first.
*
* Some other InnerClass records, the extra classes. This is
* optional, but we don't want to loose this information if we
* just transform classes, so we memorize for which classes we
* have to keep the information anyway.
*
* Currently we don't use all informations, since we don't
* update the information for inner/outer/extra classes or
* check it for consistency. This might be bad, since this
* means that
* * load(ALL); write(new File()) ** doesn't work. */ hasInnerClassesAttr = true; int count = input.readUnsignedShort(); if (length != 2 + 8 * count) throw new ClassFormatException ("InnerClasses attribute has wrong length"); int innerCount = 0, outerCount = 0, extraCount = 0; /** * The first part will contain the inner classes, the last * part the extra classes. */ ClassInfo[] innerExtra = new ClassInfo[count]; for (int i=0; i < count; i++) { int innerIndex = input.readUnsignedShort(); int outerIndex = input.readUnsignedShort(); int nameIndex = input.readUnsignedShort(); String inner = cp.getClassName(innerIndex); String outer = outerIndex != 0 ? cp.getClassName(outerIndex) : null; String innername = nameIndex != 0 ? cp.getUTF8(nameIndex) : null; int access = input.readUnsignedShort(); if (innername != null && innername.length() == 0) innername = null; /* Some compilers give method scope classes a valid * outer field, but we mustn't handle them as inner * classes. The best way to distinguish this case * is by the class name. */ if (outer != null && innername != null && inner.length() > outer.length() + 2 + innername.length() && inner.startsWith(outer+"$") && inner.endsWith("$"+innername) && Character.isDigit(inner.charAt(outer.length() + 1))) outer = null; ClassInfo innerCI = classpath.getClassInfo(inner); ClassInfo outerCI = null; if (outer != null) { outerCI = classpath.getClassInfo(outer); /* If we didn't find an InnerClasses info for outerCI, yet, * this means that it doesn't have an outer class. So we * know its (empty) outer class status now. */ if (outerCI.status < OUTERCLASS) outerCI.mergeOuterInfo(null, null, -1, false); } if (innername == null) /* anonymous class */ outerCI = null; innerCI.mergeOuterInfo(innername, outerCI, access, outerCI == null); if (outerCI == this) innerExtra[innerCount++] = innerCI; else { /* Remove outerCI from the extra part of innerExtra * since it is implicit now. */ for (int j = count - 1; j >= count - extraCount; j--) { if (innerExtra[j] == outerCI) { System.arraycopy(innerExtra, count - extraCount, innerExtra, count - extraCount + 1, j - (count - extraCount)); extraCount--; break; } } /* Add innerCI to the extra classes, except if it is * this class. */ if (innerCI != this) innerExtra[count - (++extraCount)] = innerCI; } } /* Now inner classes are at the front of the array in correct * order. The extra classes are in reverse order at the end * of the array. */ if (innerCount > 0) { innerClasses = new ClassInfo[innerCount]; for (int i=0; i < innerCount; i++) innerClasses[i] = innerExtra[i]; } else innerClasses = null; /* All remaining classes that are mentioned in the constant * pool must have an empty outer class info. This is * specified in the 2nd edition of the JVM specification. */ for (int i = 1; i < cp.size(); i++) { if (cp.tags[i] == cp.CLASS) { String clName = cp.getUTF8(cp.indices1[i]); if (clName.charAt(0) != '[') { ClassInfo ci = classpath.getClassInfo (clName.replace('/','.')); if (ci.status < OUTERCLASS) ci.mergeOuterInfo(null, null, -1, false); } } } } void readAttribute(String name, int length, ConstantPool cp, DataInputStream input, int howMuch) throws IOException { if (howMuch >= ClassInfo.ALMOSTALL && name.equals("SourceFile")) { if (length != 2) throw new ClassFormatException("SourceFile attribute" + " has wrong length"); sourceFile = cp.getUTF8(input.readUnsignedShort()); } else if (howMuch >= ClassInfo.OUTERCLASS && name.equals("InnerClasses")) { readInnerClassesAttribute(length, cp, input); } else super.readAttribute(name, length, cp, input, howMuch); } void loadFromReflection(Class clazz, int howMuch) throws SecurityException, ClassFormatException { if (howMuch >= OUTERCLASS) { Class declarer = clazz.getDeclaringClass(); if (declarer != null) { /* We have to guess the className, since reflection doesn't * tell it :-( */ int dollar = name.lastIndexOf('$'); className = name.substring(dollar+1); outerClass = classpath.getClassInfo(declarer.getName()); /* As mentioned above OUTERCLASS is recursive */ if (outerClass.status < OUTERCLASS) outerClass.loadFromReflection(declarer, OUTERCLASS); } else { /* Check if class name ends with $[numeric]$name or * $[numeric], in which case it is a method scoped * resp. anonymous class. */ int dollar = name.lastIndexOf('$'); if (dollar >= 0 && Character.isDigit(name.charAt(dollar+1))) { /* anonymous class */ className = null; outerClass = null; methodScoped = true; } else { int dollar2 = name.lastIndexOf('$', dollar); if (dollar2 >= 0 && Character.isDigit(name.charAt(dollar2+1))) { className = name.substring(dollar+1); outerClass = null; methodScoped = true; } } } } if (howMuch >= HIERARCHY) { modifiers = clazz.getModifiers(); if (clazz.getSuperclass() == null) superclass = clazz == Object.class ? null : classpath.getClassInfo("java.lang.Object"); else superclass = classpath.getClassInfo (clazz.getSuperclass().getName()); Class[] ifaces = clazz.getInterfaces(); interfaces = new ClassInfo[ifaces.length]; for (int i=0; i
load
a class from its classpath instead. This may
* be useful for special kinds of input streams, that ClassPath
* doesn't handle though.
*
* @param input The input stream, containing the class in standard
* bytecode format.
* @param howMuch The amount of information that should be read in, one
* of HIERARCHY, PUBLICDECLARATIONS, DECLARATIONS or ALL.
* @exception ClassFormatException if the file doesn't denote a valid
* class.
* @exception IOException if input throws an exception.
* @exception IllegalStateException if this ClassInfo was modified.
* @see #load
*/
public void read(DataInputStream input, int howMuch)
throws IOException
{
if (modified)
throw new IllegalStateException(name);
if (status >= howMuch)
return;
/* Since we have to read the whole class anyway, we load all
* info, that we may need later and that does not take much memory.
*/
if (howMuch <= DECLARATIONS)
howMuch = DECLARATIONS;
/* header */
if (input.readInt() != 0xcafebabe)
throw new ClassFormatException("Wrong magic");
int version = input.readUnsignedShort();
version |= input.readUnsignedShort() << 16;
if (version < (45 << 16 | 0)
|| version > (47 << 16 | 0))
throw new ClassFormatException("Wrong class version");
/* constant pool */
ConstantPool cpool = new ConstantPool();
cpool.read(input);
/* always read modifiers, name, super, ifaces */
{
modifiers = input.readUnsignedShort();
String className = cpool.getClassName(input.readUnsignedShort());
if (!name.equals(className))
throw new ClassFormatException("wrong name " + className);
String superName = cpool.getClassName(input.readUnsignedShort());
superclass = superName != null ? classpath.getClassInfo(superName) : null;
int count = input.readUnsignedShort();
interfaces = new ClassInfo[count];
for (int i=0; i< count; i++) {
interfaces[i] = classpath.getClassInfo
(cpool.getClassName(input.readUnsignedShort()));
}
}
/* fields */
if (howMuch >= PUBLICDECLARATIONS) {
int count = input.readUnsignedShort();
fields = new FieldInfo[count];
for (int i=0; i< count; i++) {
fields[i] = new FieldInfo();
fields[i].read(cpool, input, howMuch);
}
} else {
byte[] skipBuf = new byte[6];
int count = input.readUnsignedShort();
for (int i=0; i< count; i++) {
input.readFully(skipBuf); // modifier, name, type
skipAttributes(input);
}
}
/* methods */
if (howMuch >= PUBLICDECLARATIONS) {
int count = input.readUnsignedShort();
methods = new MethodInfo[count];
for (int i=0; i< count; i++) {
methods[i] = new MethodInfo();
methods[i].read(cpool, input, howMuch);
}
} else {
byte[] skipBuf = new byte[6];
int count = input.readUnsignedShort();
for (int i=0; i< count; i++) {
input.readFully(skipBuf); // modifier, name, type
skipAttributes(input);
}
}
/* attributes */
readAttributes(cpool, input, howMuch);
status = howMuch;
}
private void reserveSmallConstants(GrowableConstantPool gcp) {
for (int i=0; i < fields.length; i++)
fields[i].reserveSmallConstants(gcp);
for (int i=0; i < methods.length; i++)
methods[i].reserveSmallConstants(gcp);
}
/****** WRITING CLASS FILES ***************************************/
private void prepareWriting(GrowableConstantPool gcp) {
gcp.putClassName(name);
gcp.putClassName(superclass.name);
for (int i=0; i < interfaces.length; i++)
gcp.putClassName(interfaces[i].name);
for (int i=0; i < fields.length; i++)
fields[i].prepareWriting(gcp);
for (int i=0; i < methods.length; i++)
methods[i].prepareWriting(gcp);
for (int i=0; i < innerClasses.length; i++)
gcp.putClassName(innerClasses[i].name);
if (sourceFile != null) {
gcp.putUTF8("SourceFile");
gcp.putUTF8(sourceFile);
}
/* All classes mentioned in the constant pool must have an
* outer class info. This is clearly specified in the 2nd
* edition of the JVM specification.
*/
hasInnerClassesAttr = false;
for (int i = 1; i < gcp.size(); i++) {
if (gcp.tags[i] == gcp.CLASS) {
String clName;
try {
clName = gcp.getUTF8(gcp.indices1[i]);
} catch (ClassFormatException ex) {
throw new InternalError(ex.getMessage());
}
if (clName.charAt(0) != '[') {
ClassInfo ci = classpath.getClassInfo
(clName.replace('/','.'));
if (ci.status < OUTERCLASS) {
GlobalOptions.err.println
("WARNING: "+ ci.name
+ "'s outer class isn't known.");
} else {
if ((ci.outerClass != null || ci.methodScoped)
&& ! hasInnerClassesAttr) {
gcp.putUTF8("innerClasses");
hasInnerClassesAttr = true;
}
if (ci.outerClass != null)
gcp.putClassName(ci.outerClass.name);
if (ci.className != null)
gcp.putUTF8(ci.className);
}
}
}
}
prepareAttributes(gcp);
}
int getKnownAttributeCount() {
int count = 0;
if (sourceFile != null)
count++;
if (hasInnerClassesAttr)
count++;
return count;
}
void writeKnownAttributes(GrowableConstantPool gcp,
DataOutputStream output)
throws IOException {
if (sourceFile != null) {
output.writeShort(gcp.putUTF8("SourceFile"));
output.writeInt(2);
output.writeShort(gcp.putUTF8(sourceFile));
}
List outers = new ArrayList();
for (int i = 0; i < gcp.size(); i++) {
if (gcp.tags[i] == gcp.CLASS) {
String clName;
try {
clName = gcp.getUTF8(gcp.indices1[i]);
} catch (ClassFormatException ex) {
throw new InternalError(ex.getMessage());
}
if (clName.charAt(0) != '[') {
ClassInfo ci = classpath.getClassInfo
(clName.replace('/','.'));
while (ci.status >= OUTERCLASS
&& ci.outerClass != null || ci.methodScoped) {
/* Order is important so remove ci if it
* already exists and add it to the end. This
* way the outermost classes go to the end.
*/
outers.remove(ci);
outers.add(ci);
ci = ci.outerClass;
}
}
}
}
if (hasInnerClassesAttr) {
int count = outers.size();
output.writeShort(gcp.putUTF8("InnerClasses"));
output.writeInt(2 + count * 8);
output.writeShort(count);
ListIterator iter = outers.listIterator(count);
while (iter.hasPrevious()) {
ClassInfo ci = (ClassInfo) iter.previous();
output.writeShort(gcp.putClassName(ci.name));
output.writeShort(ci.outerClass == null ? 0 :
gcp.putClassName(ci.outerClass.name));
output.writeShort(ci.className == null ? 0 :
gcp.putUTF8(ci.className));
output.writeShort(ci.modifiers);
}
}
}
/**
* Writes a class to the given DataOutputStream. Of course this only
* works if ALL information for this class is loaded/set. If this
* class has an outer class, inner classes or extra classes, their
* status must contain at least the OUTERCLASS information.
* @param out the output stream.
* @exception IOException if out throws io exception.
* @exception IllegalStateException if not enough information is set.
*/
public void write(DataOutputStream out) throws IOException {
if (status <= ALL)
throw new IllegalStateException("state is "+status);
GrowableConstantPool gcp = new GrowableConstantPool();
reserveSmallConstants(gcp);
prepareWriting(gcp);
out.writeInt(0xcafebabe);
out.writeShort(3);
out.writeShort(45);
gcp.write(out);
out.writeShort(javaModifiersToBytecode(modifiers));
out.writeShort(gcp.putClassName(name));
out.writeShort(gcp.putClassName(superclass.getName()));
out.writeShort(interfaces.length);
for (int i=0; i < interfaces.length; i++)
out.writeShort(gcp.putClassName(interfaces[i].getName()));
out.writeShort(fields.length);
for (int i=0; i < fields.length; i++)
fields[i].write(gcp, out);
out.writeShort(methods.length);
for (int i=0; i < methods.length; i++)
methods[i].write(gcp, out);
writeAttributes(gcp, out);
}
/**
* Loads the contents of a class from the classpath.
* @param howMuch The amount of information that should be read
* in, one of HIERARCHY
,
* PUBLICDECLARATIONS
,
* DECLARATIONS
, ALMOSTALL
* or ALL
.
* @exception ClassFormatException if the file doesn't denote a
* valid class.
* @exception FileNotFoundException if class wasn't found in classpath.
* @exception IOException if an io exception occured.
* @exception IllegalStateException if this ClassInfo was modified.
* @see #HIERARCHY
* @see #PUBLICDECLARATIONS
* @see #DECLARATIONS
* @see #ALMOSTALL
* @see #ALL
*/
public void load(int howMuch)
throws IOException
{
if (modified)
throw new IllegalStateException(name);
if (status >= howMuch)
return;
if (classpath.loadClass(this, howMuch)) {
if (status < howMuch)
throw new IllegalStateException("state = "+status);
return;
}
throw new FileNotFoundException(name);
}
/**
* Guess the contents of a class. It
* @param howMuch The amount of information that should be read, e.g.
* HIERARCHY
.
* @exception ClassFormatException if the file doesn't denote a
* valid class.
* @exception FileNotFoundException if class wasn't found in classpath.
* @exception IOException if an io exception occured.
* @exception IllegalStateException if this ClassInfo was modified.
* @see #OUTERCLASS
* @see #HIERARCHY
* @see #PUBLICDECLARATIONS
* @see #DECLARATIONS
* @see #ALMOSTALL
* @see #ALL
*/
public void guess(int howMuch)
{
if (howMuch <= status)
throw new IllegalStateException("status = "+status);
isGuessed = true;
if (howMuch >= OUTERCLASS) {
modifiers = Modifier.PUBLIC | 0x20;
int dollar = name.lastIndexOf('$');
if (dollar == -1) {
/* normal class */
} else if (Character.isDigit(name.charAt(dollar+1))) {
/* anonymous class */
methodScoped = true;
} else {
className = name.substring(dollar+1);
int prevDollar = name.lastIndexOf('$', dollar);
if (prevDollar >= 0
&& Character.isDigit(name.charAt(prevDollar))) {
/* probably method scoped class, (or inner class
* of anoymous class) */
methodScoped = true;
outerClass = classpath.getClassInfo
(name.substring(0, prevDollar));
} else {
/* inner class, we assume it is static, so we don't
* get an exception when we search for the this$0
* parameter in an constructor invocation.
*/
modifiers |= Modifier.STATIC;
outerClass = classpath.getClassInfo
(name.substring(0, dollar));
}
}
}
if (howMuch >= HIERARCHY) {
if (name.equals("java.lang.Object"))
superclass = null;
else
superclass = classpath.getClassInfo("java.lang.Object");
interfaces = new ClassInfo[0];
}
if (howMuch >= PUBLICDECLARATIONS) {
methods = new MethodInfo[0];
fields = new FieldInfo[0];
innerClasses = new ClassInfo[0];
}
status = howMuch;
}
/**
* This is the counter part to load. It will drop all
* informations bigger than "keep" and clean up the memory.
* @param keep tells how much info we should keep, can be
* NONE
or anything that load
accepts.
* @see #load
*/
public void drop(int keep) {
if (status <= keep)
return;
if (modified) {
System.err.println("Dropping info between " + keep + " and "
+ status + " in modified class " + this + ".");
Thread.dumpStack();
return;
}
if (keep < HIERARCHY) {
superclass = null;
interfaces = null;
}
if (keep < OUTERCLASS) {
methodScoped = false;
outerClass = null;
innerClasses = null;
}
if (keep < PUBLICDECLARATIONS) {
fields = null;
methods = null;
status = keep;
} else {
if (status >= DECLARATIONS)
/* We don't drop non-public declarations, since this
* is not worth it.
*/
keep = DECLARATIONS;
for (int i=0; i < fields.length; i++)
fields[i].drop(keep);
for (int i=0; i < methods.length; i++)
methods[i].drop(keep);
}
if (keep < ALMOSTALL)
sourceFile = null;
super.drop(keep);
status = keep;
}
/**
* Returns the full qualified name of this class.
* @return the full qualified name of this class, an interned string.
*/
public String getName() {
return name;
}
public boolean isGuessed() {
return isGuessed;
}
/**
* Returns the java class name of a class, without package or
* outer classes. This is null for an anonymous class. For other
* classes it is the name that occured after the
* class
keyword (provided it was compiled from
* java).
* This need OUTERCLASS information loaded to work properly.
*
* @return the short name of this class. Returns null for
* anonymous classes.
*
* @exception IllegalStateException if OUTERCLASS information wasn't
* loaded yet. */
public String getClassName() {
if (status < OUTERCLASS)
throw new IllegalStateException("status is "+status);
if (className != null || isMethodScoped())
return className;
int dot = name.lastIndexOf('.');
return name.substring(dot+1);
}
/**
* Returns the ClassInfo object for the super class.
* @return the short name of this class.
* @exception IllegalStateException if HIERARCHY information wasn't
* loaded yet.
*/
public ClassInfo getSuperclass() {
if (status < HIERARCHY)
throw new IllegalStateException("status is "+status);
return superclass;
}
/**
* Returns the ClassInfo object for the super class.
* @return the short name of this class.
* @exception IllegalStateException if HIERARCHY information wasn't
* loaded yet.
*/
public ClassInfo[] getInterfaces() {
if (status < HIERARCHY)
throw new IllegalStateException("status is "+status);
return interfaces;
}
public int getModifiers() {
if (modifiers == -1)
throw new IllegalStateException("status is "+status);
return modifiers;
}
public boolean isInterface() {
return Modifier.isInterface(getModifiers());
}
public FieldInfo findField(String name, String typeSig) {
if (status < PUBLICDECLARATIONS)
throw new IllegalStateException("status is "+status);
for (int i=0; i< fields.length; i++)
if (fields[i].getName().equals(name)
&& fields[i].getType().equals(typeSig))
return fields[i];
return null;
}
public MethodInfo findMethod(String name, String typeSig) {
if (status < PUBLICDECLARATIONS)
throw new IllegalStateException("status is "+status);
for (int i=0; i< methods.length; i++)
if (methods[i].getName().equals(name)
&& methods[i].getType().equals(typeSig))
return methods[i];
return null;
}
public MethodInfo[] getMethods() {
if (status < PUBLICDECLARATIONS)
throw new IllegalStateException("status is "+status);
return methods;
}
public FieldInfo[] getFields() {
if (status < PUBLICDECLARATIONS)
throw new IllegalStateException("status is "+status);
return fields;
}
/**
* Returns the outer class of this class if it is an inner class.
* This needs the OUTERCLASS information loaded.
* @return The class that declared this class, null if the class
* isn't declared in a class scope
*
* @exception IllegalStateException if OUTERCLASS information
* wasn't loaded yet.
*/
public ClassInfo getOuterClass() {
if (status < OUTERCLASS)
throw new IllegalStateException("status is "+status);
return outerClass;
}
/**
* Returns true if the class was declared inside a method.
* This needs the OUTERCLASS information loaded.
* @return true if this is a method scoped or an anonymous class,
* false otherwise.
*
* @exception IllegalStateException if OUTERCLASS information
* wasn't loaded yet.
*/
public boolean isMethodScoped() {
if (status < OUTERCLASS)
throw new IllegalStateException("status is "+status);
return methodScoped;
}
public ClassInfo[] getClasses() {
if (status < PUBLICDECLARATIONS)
throw new IllegalStateException("status is "+status);
return innerClasses;
}
public String getSourceFile() {
return sourceFile;
}
public void setName(String newName) {
name = newName.intern();
modified = true;
}
public void setSuperclass(ClassInfo newSuper) {
superclass = newSuper;
modified = true;
}
public void setInterfaces(ClassInfo[] newIfaces) {
interfaces = newIfaces;
modified = true;
}
public void setModifiers(int newModifiers) {
modifiers = newModifiers;
modified = true;
}
public void setMethods(MethodInfo[] mi) {
methods = mi;
modified = true;
}
public void setFields(FieldInfo[] fi) {
fields = fi;
modified = true;
}
public void setOuterClass(ClassInfo oc) {
outerClass = oc;
modified = true;
}
public void setMethodScoped(boolean ms) {
methodScoped = ms;
modified = true;
}
public void setClasses(ClassInfo[] ic) {
innerClasses = ic;
modified = true;
}
public void setSourceFile(String newSource) {
sourceFile = newSource;
modified = true;
}
/**
* Gets the serial version UID of this class. If a final static
* long serialVersionUID field is present, its constant value
* is returned. Otherwise the UID is calculated with the algorithm
* in the serial version spec.
* @return the serial version UID of this class.
* @exception IllegalStateException if DECLARATIONS aren't loaded.
* @exception NoSuchAlgorithmException if SHA-1 message digest is not
* supported (needed for calculation of UID.
*/
public long getSerialVersionUID() throws NoSuchAlgorithmException {
if (status < DECLARATIONS)
throw new IllegalStateException("status is "+status);
FieldInfo fi = findField("serialVersionUID", "J");
if (fi != null
&& ((fi.getModifiers() & (Modifier.STATIC | Modifier.FINAL))
== (Modifier.STATIC | Modifier.FINAL))
&& fi.getConstant() != null)
return ((Long) fi.getConstant()).longValue();
final MessageDigest md = MessageDigest.getInstance("SHA");
OutputStream digest = new OutputStream() {
public void write(int b) {
md.update((byte) b);
}
public void write(byte[] data, int offset, int length) {
md.update(data, offset, length);
}
};
DataOutputStream out = new DataOutputStream(digest);
try {
out.writeUTF(this.name);
// just look at interesting bits of modifiers
int modifs = javaModifiersToBytecode(this.modifiers)
& (Modifier.ABSTRACT | Modifier.FINAL
| Modifier.INTERFACE | Modifier.PUBLIC);
out.writeInt(modifs);
ClassInfo[] interfaces = (ClassInfo[]) this.interfaces.clone();
Arrays.sort(interfaces);
for (int i=0; i < interfaces.length; i++)
out.writeUTF(interfaces[i].name);
FieldInfo[] fields = (FieldInfo[]) this.fields.clone();
Arrays.sort(fields);
for (int i=0; i < fields.length; i++) {
modifs = fields[i].getModifiers();
if ((modifs & Modifier.PRIVATE) != 0
&& (modifs & (Modifier.STATIC
| Modifier.TRANSIENT)) != 0)
continue;
out.writeUTF(fields[i].getName());
out.writeInt(modifs);
out.writeUTF(fields[i].getType());
}
MethodInfo[] methods = (MethodInfo[]) this.methods.clone();
Arrays.sort(methods);
for (int i=0; i < methods.length; i++) {
modifs = methods[i].getModifiers();
/* The modifiers of