This commit is contained in:
FranzHaidnor
2023-10-25 15:13:44 +08:00
parent 84c1f7f535
commit c91945c791
181 changed files with 6917 additions and 5349 deletions

View File

@@ -43,6 +43,13 @@
<version>2.0.7</version> <version>2.0.7</version>
</dependency> </dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
@@ -68,7 +75,7 @@
<configuration> <configuration>
<transformers> <transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>haidnor.jvm.Main</mainClass> <mainClass>haidnor.jvm.HaidnorJVM</mainClass>
</transformer> </transformer>
</transformers> </transformers>
</configuration> </configuration>

View File

@@ -0,0 +1,83 @@
package haidnor.jvm;
import haidnor.jvm.bcel.classfile.JavaClass;
import haidnor.jvm.classloader.JVMClassLoader;
import haidnor.jvm.core.JavaExecutionEngine;
import haidnor.jvm.rtda.Metaspace;
import haidnor.jvm.runtime.JVMThread;
import haidnor.jvm.util.JVMThreadHolder;
import lombok.SneakyThrows;
import org.apache.commons.cli.*;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* <a href="https://github.com/FranzHaidnor">GitHub FranzHaidnor</a>
*/
public class HaidnorJVM {
@SneakyThrows
public static void main(String[] args) {
String banner = """
██╗ ██╗ █████╗ ██╗██████╗ ███╗ ██╗ ██████╗ ██████╗ ██╗██╗ ██╗███╗ ███╗
██║ ██║██╔══██╗██║██╔══██╗████╗ ██║██╔═══██╗██╔══██╗ ██║██║ ██║████╗ ████║
███████║███████║██║██║ ██║██╔██╗ ██║██║ ██║██████╔╝ ██║██║ ██║██╔████╔██║
██╔══██║██╔══██║██║██║ ██║██║╚██╗██║██║ ██║██╔══██╗ ██ ██║╚██╗ ██╔╝██║╚██╔╝██║
██║ ██║██║ ██║██║██████╔╝██║ ╚████║╚██████╔╝██║ ██║ ╚█████╔╝ ╚████╔╝ ██║ ╚═╝ ██║
╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚════╝ ╚═══╝ ╚═╝ ╚═╝
""";
System.out.println(banner);
CommandLine cmd = initCommandLine(args);
// 指定从 .jar 文件运行
if (cmd.hasOption("jar")) {
String jarFilePath = cmd.getOptionValue("jar");
try (JarFile jarFile = new JarFile(jarFilePath)) {
JVMClassLoader classLoader = new JVMClassLoader(jarFile, "ApplicationClassLoader");
String mainClass = jarFile.getManifest().getMainAttributes().getValue("Main-Class");
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6);
if (className.equals(mainClass)) {
JVMThreadHolder.set(new JVMThread());
JavaClass javaClass = classLoader.loadWithJar(jarFile, entry);
Metaspace.registerJavaClass(javaClass);
JavaExecutionEngine.callMainMethod(javaClass);
return;
}
}
}
}
}
// 指定从 .class 文件运行
if (cmd.hasOption("class")) {
JVMThreadHolder.set(new JVMThread());
String path = cmd.getOptionValue("class");
JVMClassLoader bootClassLoader = new JVMClassLoader("ApplicationClassLoader");
JavaClass javaClass = bootClassLoader.loadWithAbsolutePath(path);
JavaExecutionEngine.callMainMethod(javaClass);
}
}
private static CommandLine initCommandLine(String[] args) throws ParseException {
Option jarOption = new Option("jar", true, "运行 jar 程序");
Option classOption = new Option("class", true, "运行 .class 字节码文件");
OptionGroup optionGroup = new OptionGroup();
optionGroup.addOption(jarOption).addOption(classOption);
Options options = new Options();
options.addOptionGroup(optionGroup);
CommandLineParser parser = new DefaultParser();
return parser.parse(options, args);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -25,24 +25,14 @@ import org.apache.commons.lang3.ArrayUtils;
*/ */
public final class ExceptionConst { public final class ExceptionConst {
/**
* Enum corresponding to the various Exception Class arrays, used by
* {@link ExceptionConst#createExceptions(EXCS, Class...)}
*/
public enum EXCS {
EXCS_CLASS_AND_INTERFACE_RESOLUTION, EXCS_FIELD_AND_METHOD_RESOLUTION, EXCS_INTERFACE_METHOD_RESOLUTION, EXCS_STRING_RESOLUTION, EXCS_ARRAY_EXCEPTION,
}
/** /**
* The mother of all exceptions * The mother of all exceptions
*/ */
public static final Class<Throwable> THROWABLE = Throwable.class; public static final Class<Throwable> THROWABLE = Throwable.class;
/** /**
* Super class of any run-time exception * Super class of any run-time exception
*/ */
public static final Class<RuntimeException> RUNTIME_EXCEPTION = RuntimeException.class; public static final Class<RuntimeException> RUNTIME_EXCEPTION = RuntimeException.class;
/** /**
* Super class of any linking exception (aka Linkage Error) * Super class of any linking exception (aka Linkage Error)
*/ */
@@ -61,38 +51,32 @@ public final class ExceptionConst {
public static final Class<NoSuchMethodError> NO_SUCH_METHOD_ERROR = NoSuchMethodError.class; public static final Class<NoSuchMethodError> NO_SUCH_METHOD_ERROR = NoSuchMethodError.class;
public static final Class<NoClassDefFoundError> NO_CLASS_DEF_FOUND_ERROR = NoClassDefFoundError.class; public static final Class<NoClassDefFoundError> NO_CLASS_DEF_FOUND_ERROR = NoClassDefFoundError.class;
public static final Class<UnsatisfiedLinkError> UNSATISFIED_LINK_ERROR = UnsatisfiedLinkError.class; public static final Class<UnsatisfiedLinkError> UNSATISFIED_LINK_ERROR = UnsatisfiedLinkError.class;
public static final Class<VerifyError> VERIFY_ERROR = VerifyError.class; public static final Class<VerifyError> VERIFY_ERROR = VerifyError.class;
/* UnsupportedClassVersionError is new in JDK 1.2 */
// public static final Class UnsupportedClassVersionError = UnsupportedClassVersionError.class;
/** /**
* Run-Time Exceptions * Run-Time Exceptions
*/ */
public static final Class<NullPointerException> NULL_POINTER_EXCEPTION = NullPointerException.class; public static final Class<NullPointerException> NULL_POINTER_EXCEPTION = NullPointerException.class;
/* UnsupportedClassVersionError is new in JDK 1.2 */
// public static final Class UnsupportedClassVersionError = UnsupportedClassVersionError.class;
public static final Class<ArrayIndexOutOfBoundsException> ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION = ArrayIndexOutOfBoundsException.class; public static final Class<ArrayIndexOutOfBoundsException> ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION = ArrayIndexOutOfBoundsException.class;
public static final Class<ArithmeticException> ARITHMETIC_EXCEPTION = ArithmeticException.class; public static final Class<ArithmeticException> ARITHMETIC_EXCEPTION = ArithmeticException.class;
public static final Class<NegativeArraySizeException> NEGATIVE_ARRAY_SIZE_EXCEPTION = NegativeArraySizeException.class; public static final Class<NegativeArraySizeException> NEGATIVE_ARRAY_SIZE_EXCEPTION = NegativeArraySizeException.class;
public static final Class<ClassCastException> CLASS_CAST_EXCEPTION = ClassCastException.class; public static final Class<ClassCastException> CLASS_CAST_EXCEPTION = ClassCastException.class;
public static final Class<IllegalMonitorStateException> ILLEGAL_MONITOR_STATE = IllegalMonitorStateException.class; public static final Class<IllegalMonitorStateException> ILLEGAL_MONITOR_STATE = IllegalMonitorStateException.class;
/** /**
* Pre-defined exception arrays according to chapters 5.1-5.4 of the Java Virtual Machine Specification * Pre-defined exception arrays according to chapters 5.1-5.4 of the Java Virtual Machine Specification
*/ */
private static final Class<?>[] EXCS_CLASS_AND_INTERFACE_RESOLUTION = {NO_CLASS_DEF_FOUND_ERROR, CLASS_FORMAT_ERROR, VERIFY_ERROR, ABSTRACT_METHOD_ERROR, private static final Class<?>[] EXCS_CLASS_AND_INTERFACE_RESOLUTION = {NO_CLASS_DEF_FOUND_ERROR, CLASS_FORMAT_ERROR, VERIFY_ERROR, ABSTRACT_METHOD_ERROR,
EXCEPTION_IN_INITIALIZER_ERROR, ILLEGAL_ACCESS_ERROR}; // Chapter 5.1 EXCEPTION_IN_INITIALIZER_ERROR, ILLEGAL_ACCESS_ERROR}; // Chapter 5.1
private static final Class<?>[] EXCS_FIELD_AND_METHOD_RESOLUTION = {NO_SUCH_FIELD_ERROR, ILLEGAL_ACCESS_ERROR, NO_SUCH_METHOD_ERROR}; // Chapter 5.2 private static final Class<?>[] EXCS_FIELD_AND_METHOD_RESOLUTION = {NO_SUCH_FIELD_ERROR, ILLEGAL_ACCESS_ERROR, NO_SUCH_METHOD_ERROR}; // Chapter 5.2
/** /**
* Empty array. * Empty array.
*/ */
private static final Class<?>[] EXCS_INTERFACE_METHOD_RESOLUTION = new Class[0]; // Chapter 5.3 (as below) private static final Class<?>[] EXCS_INTERFACE_METHOD_RESOLUTION = new Class[0]; // Chapter 5.3 (as below)
/** /**
* Empty array. * Empty array.
*/ */
private static final Class<?>[] EXCS_STRING_RESOLUTION = new Class[0]; private static final Class<?>[] EXCS_STRING_RESOLUTION = new Class[0];
// Chapter 5.4 (no errors but the ones that _always_ could happen! How stupid.) // Chapter 5.4 (no errors but the ones that _always_ could happen! How stupid.)
private static final Class<?>[] EXCS_ARRAY_EXCEPTION = {NULL_POINTER_EXCEPTION, ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION}; private static final Class<?>[] EXCS_ARRAY_EXCEPTION = {NULL_POINTER_EXCEPTION, ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION};
@@ -125,4 +109,12 @@ public final class ExceptionConst {
return ArrayUtils.addAll(input, extraClasses); return ArrayUtils.addAll(input, extraClasses);
} }
/**
* Enum corresponding to the various Exception Class arrays, used by
* {@link ExceptionConst#createExceptions(EXCS, Class...)}
*/
public enum EXCS {
EXCS_CLASS_AND_INTERFACE_RESOLUTION, EXCS_FIELD_AND_METHOD_RESOLUTION, EXCS_INTERFACE_METHOD_RESOLUTION, EXCS_STRING_RESOLUTION, EXCS_ARRAY_EXCEPTION,
}
} }

View File

@@ -77,6 +77,13 @@ public abstract class Repository {
return repository; return repository;
} }
/**
* Sets repository instance to be used for class loading
*/
public static void setRepository(final haidnor.jvm.bcel.util.Repository rep) {
repository = rep;
}
/** /**
* @return list of super classes of clazz in ascending order, i.e., Object is always the last element * @return list of super classes of clazz in ascending order, i.e., Object is always the last element
* @throws ClassNotFoundException if any of the superclasses can't be found * @throws ClassNotFoundException if any of the superclasses can't be found
@@ -162,9 +169,9 @@ public abstract class Repository {
/** /**
* Tries to find class source using the internal repository instance. * Tries to find class source using the internal repository instance.
* *
* @see Class
* @return JavaClass object for given runtime class * @return JavaClass object for given runtime class
* @throws ClassNotFoundException if the class could not be found or parsed correctly * @throws ClassNotFoundException if the class could not be found or parsed correctly
* @see Class
*/ */
public static JavaClass lookupClass(final Class<?> clazz) throws ClassNotFoundException { public static JavaClass lookupClass(final Class<?> clazz) throws ClassNotFoundException {
return repository.loadClass(clazz); return repository.loadClass(clazz);
@@ -205,11 +212,4 @@ public abstract class Repository {
public static void removeClass(final String clazz) { public static void removeClass(final String clazz) {
repository.removeClass(repository.findClass(clazz)); repository.removeClass(repository.findClass(clazz));
} }
/**
* Sets repository instance to be used for class loading
*/
public static void setRepository(final haidnor.jvm.bcel.util.Repository rep) {
repository = rep;
}
} }

View File

@@ -46,6 +46,15 @@ public abstract class AccessFlags {
return access_flags; return access_flags;
} }
/**
* Set access flags aka "modifiers".
*
* @param accessFlags Access flags of the object.
*/
public final void setAccessFlags(final int accessFlags) {
this.access_flags = accessFlags;
}
/** /**
* @return Access flags of the object aka. "modifiers". * @return Access flags of the object aka. "modifiers".
*/ */
@@ -53,6 +62,15 @@ public abstract class AccessFlags {
return access_flags; return access_flags;
} }
/**
* Set access flags aka "modifiers".
*
* @param accessFlags Access flags of the object.
*/
public final void setModifiers(final int accessFlags) {
setAccessFlags(accessFlags);
}
public final boolean isAbstract() { public final boolean isAbstract() {
return (access_flags & Const.ACC_ABSTRACT) != 0; return (access_flags & Const.ACC_ABSTRACT) != 0;
} }
@@ -181,15 +199,6 @@ public abstract class AccessFlags {
setFlag(Const.ACC_VOLATILE, flag); setFlag(Const.ACC_VOLATILE, flag);
} }
/**
* Set access flags aka "modifiers".
*
* @param accessFlags Access flags of the object.
*/
public final void setAccessFlags(final int accessFlags) {
this.access_flags = accessFlags;
}
private void setFlag(final int flag, final boolean set) { private void setFlag(final int flag, final boolean set) {
if ((access_flags & flag) != 0) { // Flag is set already if ((access_flags & flag) != 0) { // Flag is set already
if (!set) { if (!set) {
@@ -199,13 +208,4 @@ public abstract class AccessFlags {
access_flags |= flag; access_flags |= flag;
} }
} }
/**
* Set access flags aka "modifiers".
*
* @param accessFlags Access flags of the object.
*/
public final void setModifiers(final int accessFlags) {
setAccessFlags(accessFlags);
}
} }

View File

@@ -31,6 +31,16 @@ import java.util.stream.Stream;
public class AnnotationEntry implements Node { public class AnnotationEntry implements Node {
public static final AnnotationEntry[] EMPTY_ARRAY = {}; public static final AnnotationEntry[] EMPTY_ARRAY = {};
private final int typeIndex;
private final ConstantPool constantPool;
private final boolean isRuntimeVisible;
private List<ElementValuePair> elementValuePairs;
public AnnotationEntry(final int typeIndex, final ConstantPool constantPool, final boolean isRuntimeVisible) {
this.typeIndex = typeIndex;
this.constantPool = constantPool;
this.isRuntimeVisible = isRuntimeVisible;
}
public static AnnotationEntry[] createAnnotationEntries(final Attribute[] attrs) { public static AnnotationEntry[] createAnnotationEntries(final Attribute[] attrs) {
// Find attributes that contain annotation data // Find attributes that contain annotation data
@@ -58,20 +68,6 @@ public class AnnotationEntry implements Node {
return annotationEntry; return annotationEntry;
} }
private final int typeIndex;
private final ConstantPool constantPool;
private final boolean isRuntimeVisible;
private List<ElementValuePair> elementValuePairs;
public AnnotationEntry(final int typeIndex, final ConstantPool constantPool, final boolean isRuntimeVisible) {
this.typeIndex = typeIndex;
this.constantPool = constantPool;
this.isRuntimeVisible = isRuntimeVisible;
}
/** /**
* Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
* I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.

View File

@@ -31,8 +31,8 @@ import java.util.stream.Stream;
*/ */
public abstract class Annotations extends Attribute implements Iterable<AnnotationEntry> { public abstract class Annotations extends Attribute implements Iterable<AnnotationEntry> {
private AnnotationEntry[] annotationTable;
private final boolean isRuntimeVisible; private final boolean isRuntimeVisible;
private AnnotationEntry[] annotationTable;
/** /**
* Constructs an instance. * Constructs an instance.

View File

@@ -53,16 +53,57 @@ import java.util.Map;
*/ */
public abstract class Attribute implements Cloneable, Node { public abstract class Attribute implements Cloneable, Node {
private static final boolean debug = Boolean.getBoolean(Attribute.class.getCanonicalName() + ".debug"); // Debugging on/off
private static final Map<String, Object> READERS = new HashMap<>();
/** /**
* Empty array. * Empty array.
* *
* @since 6.6.0 * @since 6.6.0
*/ */
public static final Attribute[] EMPTY_ARRAY = {}; public static final Attribute[] EMPTY_ARRAY = {};
private static final boolean debug = Boolean.getBoolean(Attribute.class.getCanonicalName() + ".debug"); // Debugging on/off
private static final Map<String, Object> READERS = new HashMap<>();
/**
* @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected int name_index; // Points to attribute name in constant pool TODO make private (has getter & setter)
/**
* @deprecated (since 6.0) (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected int length; // Content length of attribute field TODO make private (has getter & setter)
/**
* @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected byte tag; // Tag to distinguish subclasses TODO make private & final; supposed to be immutable
/**
* @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected ConstantPool constant_pool; // TODO make private (has getter & setter)
/**
* Constructs an instance.
*
* <pre>
* attribute_info {
* u2 attribute_name_index;
* u4 attribute_length;
* u1 info[attribute_length];
* }
* </pre>
*
* @param tag tag.
* @param nameIndex u2 name index.
* @param length u4 length.
* @param constantPool constant pool.
*/
protected Attribute(final byte tag, final int nameIndex, final int length, final ConstantPool constantPool) {
this.tag = tag;
this.name_index = Args.requireU2(nameIndex, 0, constantPool.getLength(), getClass().getSimpleName() + " name index");
this.length = Args.requireU4(length, getClass().getSimpleName() + " attribute length");
this.constant_pool = constantPool;
}
/** /**
* Add an Attribute reader capable of parsing (user-defined) attributes named "name". You should not add readers for the * Add an Attribute reader capable of parsing (user-defined) attributes named "name". You should not add readers for the
@@ -85,13 +126,12 @@ public abstract class Attribute implements Cloneable, Node {
* Class method reads one attribute from the input data stream. This method must not be accessible from the outside. It * Class method reads one attribute from the input data stream. This method must not be accessible from the outside. It
* is called by the Field and Method constructor methods. * is called by the Field and Method constructor methods.
* *
* @see JavaField
* @see JavaMethod
*
* @param dataInput Input stream * @param dataInput Input stream
* @param constantPool Array of constants * @param constantPool Array of constants
* @return Attribute * @return Attribute
* @throws IOException if an I/O error occurs. * @throws IOException if an I/O error occurs.
* @see JavaField
* @see JavaMethod
* @since 6.0 * @since 6.0
*/ */
public static Attribute readAttribute(final DataInput dataInput, final ConstantPool constantPool) throws IOException { public static Attribute readAttribute(final DataInput dataInput, final ConstantPool constantPool) throws IOException {
@@ -188,13 +228,12 @@ public abstract class Attribute implements Cloneable, Node {
* Class method reads one attribute from the input data stream. This method must not be accessible from the outside. It * Class method reads one attribute from the input data stream. This method must not be accessible from the outside. It
* is called by the Field and Method constructor methods. * is called by the Field and Method constructor methods.
* *
* @see JavaField
* @see JavaMethod
*
* @param dataInputStream Input stream * @param dataInputStream Input stream
* @param constantPool Array of constants * @param constantPool Array of constants
* @return Attribute * @return Attribute
* @throws IOException if an I/O error occurs. * @throws IOException if an I/O error occurs.
* @see JavaField
* @see JavaMethod
*/ */
public static Attribute readAttribute(final DataInputStream dataInputStream, final ConstantPool constantPool) throws IOException { public static Attribute readAttribute(final DataInputStream dataInputStream, final ConstantPool constantPool) throws IOException {
return readAttribute((DataInput) dataInputStream, constantPool); return readAttribute((DataInput) dataInputStream, constantPool);
@@ -209,53 +248,6 @@ public abstract class Attribute implements Cloneable, Node {
READERS.remove(name); READERS.remove(name);
} }
/**
* @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected int name_index; // Points to attribute name in constant pool TODO make private (has getter & setter)
/**
* @deprecated (since 6.0) (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected int length; // Content length of attribute field TODO make private (has getter & setter)
/**
* @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected byte tag; // Tag to distinguish subclasses TODO make private & final; supposed to be immutable
/**
* @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected ConstantPool constant_pool; // TODO make private (has getter & setter)
/**
* Constructs an instance.
*
* <pre>
* attribute_info {
* u2 attribute_name_index;
* u4 attribute_length;
* u1 info[attribute_length];
* }
* </pre>
*
* @param tag tag.
* @param nameIndex u2 name index.
* @param length u4 length.
* @param constantPool constant pool.
*/
protected Attribute(final byte tag, final int nameIndex, final int length, final ConstantPool constantPool) {
this.tag = tag;
this.name_index = Args.requireU2(nameIndex, 0, constantPool.getLength(), getClass().getSimpleName() + " name index");
this.length = Args.requireU4(length, getClass().getSimpleName() + " attribute length");
this.constant_pool = constantPool;
}
/** /**
* Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
* I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.
@@ -306,6 +298,14 @@ public abstract class Attribute implements Cloneable, Node {
return constant_pool; return constant_pool;
} }
/**
* @param constantPool Constant pool to be used for this object.
* @see ConstantPool
*/
public final void setConstantPool(final ConstantPool constantPool) {
this.constant_pool = constantPool;
}
/** /**
* @return Length of attribute field in bytes. * @return Length of attribute field in bytes.
*/ */
@@ -313,6 +313,13 @@ public abstract class Attribute implements Cloneable, Node {
return length; return length;
} }
/**
* @param length length in bytes.
*/
public final void setLength(final int length) {
this.length = length;
}
/** /**
* @return Name of attribute * @return Name of attribute
* @since 6.0 * @since 6.0
@@ -328,28 +335,6 @@ public abstract class Attribute implements Cloneable, Node {
return name_index; return name_index;
} }
/**
* @return Tag of attribute, i.e., its type. Value may not be altered, thus there is no setTag() method.
*/
public final byte getTag() {
return tag;
}
/**
* @param constantPool Constant pool to be used for this object.
* @see ConstantPool
*/
public final void setConstantPool(final ConstantPool constantPool) {
this.constant_pool = constantPool;
}
/**
* @param length length in bytes.
*/
public final void setLength(final int length) {
this.length = length;
}
/** /**
* @param nameIndex of attribute. * @param nameIndex of attribute.
*/ */
@@ -357,6 +342,13 @@ public abstract class Attribute implements Cloneable, Node {
this.name_index = nameIndex; this.name_index = nameIndex;
} }
/**
* @return Tag of attribute, i.e., its type. Value may not be altered, thus there is no setTag() method.
*/
public final byte getTag() {
return tag;
}
/** /**
* @return attribute name. * @return attribute name.
*/ */

View File

@@ -34,10 +34,14 @@ import java.util.Arrays;
*/ */
public class BootstrapMethod implements Cloneable { public class BootstrapMethod implements Cloneable {
/** Index of the CONSTANT_MethodHandle_info structure in the constant_pool table */ /**
* Index of the CONSTANT_MethodHandle_info structure in the constant_pool table
*/
private int bootstrapMethodRef; private int bootstrapMethodRef;
/** Array of references to the constant_pool table */ /**
* Array of references to the constant_pool table
*/
private int[] bootstrapArguments; private int[] bootstrapArguments;
/** /**
@@ -110,20 +114,6 @@ public class BootstrapMethod implements Cloneable {
return bootstrapArguments; return bootstrapArguments;
} }
/**
* @return index into constant_pool of bootstrap_method
*/
public int getBootstrapMethodRef() {
return bootstrapMethodRef;
}
/**
* @return count of number of boostrap arguments
*/
public int getNumBootstrapArguments() {
return bootstrapArguments.length;
}
/** /**
* @param bootstrapArguments int[] indices into constant_pool of CONSTANT_[type]_info * @param bootstrapArguments int[] indices into constant_pool of CONSTANT_[type]_info
*/ */
@@ -131,6 +121,13 @@ public class BootstrapMethod implements Cloneable {
this.bootstrapArguments = bootstrapArguments; this.bootstrapArguments = bootstrapArguments;
} }
/**
* @return index into constant_pool of bootstrap_method
*/
public int getBootstrapMethodRef() {
return bootstrapMethodRef;
}
/** /**
* @param bootstrapMethodRef int index into constant_pool of CONSTANT_MethodHandle * @param bootstrapMethodRef int index into constant_pool of CONSTANT_MethodHandle
*/ */
@@ -138,6 +135,13 @@ public class BootstrapMethod implements Cloneable {
this.bootstrapMethodRef = bootstrapMethodRef; this.bootstrapMethodRef = bootstrapMethodRef;
} }
/**
* @return count of number of boostrap arguments
*/
public int getNumBootstrapArguments() {
return bootstrapArguments.length;
}
/** /**
* @return String representation. * @return String representation.
*/ */

View File

@@ -122,11 +122,6 @@ public class BootstrapMethods extends Attribute implements Iterable<BootstrapMet
return bootstrapMethods; return bootstrapMethods;
} }
@Override
public Iterator<BootstrapMethod> iterator() {
return Stream.of(bootstrapMethods).iterator();
}
/** /**
* @param bootstrapMethods the array of bootstrap methods * @param bootstrapMethods the array of bootstrap methods
*/ */
@@ -134,6 +129,11 @@ public class BootstrapMethods extends Attribute implements Iterable<BootstrapMet
this.bootstrapMethods = bootstrapMethods; this.bootstrapMethods = bootstrapMethods;
} }
@Override
public Iterator<BootstrapMethod> iterator() {
return Stream.of(bootstrapMethods).iterator();
}
/** /**
* @return String representation. * @return String representation.
*/ */

View File

@@ -26,7 +26,7 @@ import java.util.zip.ZipFile;
* Wrapper class that parses a given Java .class file. The method <a href ="#parse">parse</a> returns a * Wrapper class that parses a given Java .class file. The method <a href ="#parse">parse</a> returns a
* <a href ="JavaClass.html"> JavaClass</a> object on success. When an I/O error or an inconsistency occurs an * <a href ="JavaClass.html"> JavaClass</a> object on success. When an I/O error or an inconsistency occurs an
* appropriate exception is propagated back to the caller. * appropriate exception is propagated back to the caller.
* * <p>
* The structure and the names comply, except for a few conveniences, exactly with the * The structure and the names comply, except for a few conveniences, exactly with the
* <a href="http://docs.oracle.com/javase/specs/"> JVM specification 1.0</a>. See this paper for further details about * <a href="http://docs.oracle.com/javase/specs/"> JVM specification 1.0</a>. See this paper for further details about
* the structure of a bytecode file. * the structure of a bytecode file.
@@ -34,9 +34,10 @@ import java.util.zip.ZipFile;
public final class ClassParser { public final class ClassParser {
private static final int BUFSIZE = 8192; private static final int BUFSIZE = 8192;
private DataInputStream dataInputStream;
private final boolean fileOwned; private final boolean fileOwned;
private final String fileName; private final String fileName;
private final boolean isZip; // Loaded from zip file
private DataInputStream dataInputStream;
private String zipFile; private String zipFile;
private int classNameIndex; private int classNameIndex;
private int superclassNameIndex; private int superclassNameIndex;
@@ -48,7 +49,6 @@ public final class ClassParser {
private JavaField[] fields; // class fields, i.e., its variables private JavaField[] fields; // class fields, i.e., its variables
private JavaMethod[] methods; // methods defined in the class private JavaMethod[] methods; // methods defined in the class
private Attribute[] attributes; // attributes defined in the class private Attribute[] attributes; // attributes defined in the class
private final boolean isZip; // Loaded from zip file
/** /**
* Parses class from the given stream. * Parses class from the given stream.

View File

@@ -29,7 +29,7 @@ import java.util.Arrays;
* This class represents a chunk of Java byte code contained in a method. It is instantiated by the * This class represents a chunk of Java byte code contained in a method. It is instantiated by the
* <em>Attribute.readAttribute()</em> method. A <em>Code</em> attribute contains informations about operand stack, local * <em>Attribute.readAttribute()</em> method. A <em>Code</em> attribute contains informations about operand stack, local
* variables, byte code and the exceptions handled within this method. * variables, byte code and the exceptions handled within this method.
* * <p>
* This attribute has attributes itself, namely <em>LineNumberTable</em> which is used for debugging purposes and * This attribute has attributes itself, namely <em>LineNumberTable</em> which is used for debugging purposes and
* <em>LocalVariableTable</em> which contains information about the local variables. * <em>LocalVariableTable</em> which contains information about the local variables.
* *
@@ -52,6 +52,7 @@ import java.util.Arrays;
* attribute_info attributes[attributes_count]; * attribute_info attributes[attributes_count];
* } * }
* </pre> * </pre>
*
* @see Attribute * @see Attribute
* @see CodeException * @see CodeException
* @see LineNumberTable * @see LineNumberTable
@@ -160,9 +161,8 @@ public final class Code extends Attribute {
} }
/** /**
* @return deep copy of this attribute
*
* @param constantPool the constant pool to duplicate * @param constantPool the constant pool to duplicate
* @return deep copy of this attribute
*/ */
@Override @Override
public Attribute copy(final ConstantPool constantPool) { public Attribute copy(final ConstantPool constantPool) {
@@ -209,6 +209,14 @@ public final class Code extends Attribute {
return attributes; return attributes;
} }
/**
* @param attributes the attributes to set for this Code
*/
public void setAttributes(final Attribute[] attributes) {
this.attributes = attributes != null ? attributes : EMPTY_ARRAY;
super.setLength(calculateLength()); // Adjust length
}
/** /**
* @return Actual byte code of the method. * @return Actual byte code of the method.
*/ */
@@ -216,6 +224,14 @@ public final class Code extends Attribute {
return code; return code;
} }
/**
* @param code byte code
*/
public void setCode(final byte[] code) {
this.code = code != null ? code : ArrayUtils.EMPTY_BYTE_ARRAY;
super.setLength(calculateLength()); // Adjust length
}
/** /**
* @return Table of handled exceptions. * @return Table of handled exceptions.
* @see CodeException * @see CodeException
@@ -224,6 +240,14 @@ public final class Code extends Attribute {
return exceptionTable; return exceptionTable;
} }
/**
* @param exceptionTable exception table
*/
public void setExceptionTable(final CodeException[] exceptionTable) {
this.exceptionTable = exceptionTable != null ? exceptionTable : CodeException.EMPTY_CODE_EXCEPTION_ARRAY;
super.setLength(calculateLength()); // Adjust length
}
/** /**
* @return the internal length of this code attribute (minus the first 6 bytes) and excluding all its attributes * @return the internal length of this code attribute (minus the first 6 bytes) and excluding all its attributes
*/ */
@@ -266,37 +290,6 @@ public final class Code extends Attribute {
return maxLocals; return maxLocals;
} }
/**
* @return Maximum size of stack used by this method.
*/
public int getMaxStack() {
return maxStack;
}
/**
* @param attributes the attributes to set for this Code
*/
public void setAttributes(final Attribute[] attributes) {
this.attributes = attributes != null ? attributes : EMPTY_ARRAY;
super.setLength(calculateLength()); // Adjust length
}
/**
* @param code byte code
*/
public void setCode(final byte[] code) {
this.code = code != null ? code : ArrayUtils.EMPTY_BYTE_ARRAY;
super.setLength(calculateLength()); // Adjust length
}
/**
* @param exceptionTable exception table
*/
public void setExceptionTable(final CodeException[] exceptionTable) {
this.exceptionTable = exceptionTable != null ? exceptionTable : CodeException.EMPTY_CODE_EXCEPTION_ARRAY;
super.setLength(calculateLength()); // Adjust length
}
/** /**
* @param maxLocals maximum number of local variables * @param maxLocals maximum number of local variables
*/ */
@@ -304,6 +297,13 @@ public final class Code extends Attribute {
this.maxLocals = maxLocals; this.maxLocals = maxLocals;
} }
/**
* @return Maximum size of stack used by this method.
*/
public int getMaxStack() {
return maxStack;
}
/** /**
* @param maxStack maximum stack size * @param maxStack maximum stack size
*/ */

View File

@@ -154,27 +154,6 @@ public final class CodeException implements Cloneable, Node {
return catchType; return catchType;
} }
/**
* @return Exclusive end index of the region where the handler is active.
*/
public int getEndPC() {
return endPc;
}
/**
* @return Starting address of exception handler, relative to the code.
*/
public int getHandlerPC() {
return handlerPc;
}
/**
* @return Inclusive start index of the region where the handler is active.
*/
public int getStartPC() {
return startPc;
}
/** /**
* @param catchType the type of exception that is caught * @param catchType the type of exception that is caught
*/ */
@@ -182,6 +161,13 @@ public final class CodeException implements Cloneable, Node {
this.catchType = catchType; this.catchType = catchType;
} }
/**
* @return Exclusive end index of the region where the handler is active.
*/
public int getEndPC() {
return endPc;
}
/** /**
* @param endPc end of handled block * @param endPc end of handled block
*/ */
@@ -189,6 +175,13 @@ public final class CodeException implements Cloneable, Node {
this.endPc = endPc; this.endPc = endPc;
} }
/**
* @return Starting address of exception handler, relative to the code.
*/
public int getHandlerPC() {
return handlerPc;
}
/** /**
* @param handlerPc where the actual code is * @param handlerPc where the actual code is
*/ */
@@ -196,6 +189,13 @@ public final class CodeException implements Cloneable, Node {
this.handlerPc = handlerPc; this.handlerPc = handlerPc;
} }
/**
* @return Inclusive start index of the region where the handler is active.
*/
public int getStartPC() {
return startPc;
}
/** /**
* @param startPc start of handled block * @param startPc start of handled block
*/ */

View File

@@ -45,6 +45,15 @@ public abstract class Constant implements Cloneable, Node {
return THIS.toString().hashCode(); return THIS.toString().hashCode();
} }
}; };
/**
* @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected byte tag; // TODO should be private & final
Constant(final byte tag) {
this.tag = tag;
}
/** /**
* @return Comparison strategy object * @return Comparison strategy object
@@ -53,6 +62,21 @@ public abstract class Constant implements Cloneable, Node {
return bcelComparator; return bcelComparator;
} }
/*
* In fact this tag is redundant since we can distinguish different 'Constant' objects by their type, i.e., via
* 'instanceof'. In some places we will use the tag for switch()es anyway.
*
* First, we want match the specification as closely as possible. Second we need the tag as an index to select the
* corresponding class name from the 'CONSTANT_NAMES' array.
*/
/**
* @param comparator Comparison strategy object
*/
public static void setComparator(final BCELComparator comparator) {
bcelComparator = comparator;
}
/** /**
* Reads one constant from the given input, the type depends on a tag byte. * Reads one constant from the given input, the type depends on a tag byte.
* *
@@ -104,30 +128,6 @@ public abstract class Constant implements Cloneable, Node {
} }
} }
/**
* @param comparator Comparison strategy object
*/
public static void setComparator(final BCELComparator comparator) {
bcelComparator = comparator;
}
/*
* In fact this tag is redundant since we can distinguish different 'Constant' objects by their type, i.e., via
* 'instanceof'. In some places we will use the tag for switch()es anyway.
*
* First, we want match the specification as closely as possible. Second we need the tag as an index to select the
* corresponding class name from the 'CONSTANT_NAMES' array.
*/
/**
* @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
*/
@java.lang.Deprecated
protected byte tag; // TODO should be private & final
Constant(final byte tag) {
this.tag = tag;
}
/** /**
* Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
* I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.

View File

@@ -107,13 +107,6 @@ public abstract class ConstantCP extends Constant {
return class_index; return class_index;
} }
/**
* @return Reference (index) to signature of the field.
*/
public final int getNameAndTypeIndex() {
return name_and_type_index;
}
/** /**
* @param classIndex points to Constant_class * @param classIndex points to Constant_class
*/ */
@@ -121,6 +114,13 @@ public abstract class ConstantCP extends Constant {
this.class_index = classIndex; this.class_index = classIndex;
} }
/**
* @return Reference (index) to signature of the field.
*/
public final int getNameAndTypeIndex() {
return name_and_type_index;
}
/** /**
* @param nameAndTypeIndex points to Constant_NameAndType * @param nameAndTypeIndex points to Constant_NameAndType
*/ */
@@ -130,7 +130,7 @@ public abstract class ConstantCP extends Constant {
/** /**
* @return String representation. * @return String representation.
* * <p>
* not final as ConstantInvokeDynamic needs to modify * not final as ConstantInvokeDynamic needs to modify
*/ */
@Override @Override

View File

@@ -88,6 +88,13 @@ public final class ConstantDouble extends Constant implements ConstantObject {
return bytes; return bytes;
} }
/**
* @param bytes the raw bytes that represent the double value
*/
public void setBytes(final double bytes) {
this.bytes = bytes;
}
/** /**
* @return Double object * @return Double object
*/ */
@@ -96,13 +103,6 @@ public final class ConstantDouble extends Constant implements ConstantObject {
return Double.valueOf(bytes); return Double.valueOf(bytes);
} }
/**
* @param bytes the raw bytes that represent the double value
*/
public void setBytes(final double bytes) {
this.bytes = bytes;
}
/** /**
* @return String representation. * @return String representation.
*/ */

View File

@@ -68,7 +68,7 @@ public final class ConstantDynamic extends ConstantCP {
/** /**
* @return Reference (index) to bootstrap method this constant refers to. * @return Reference (index) to bootstrap method this constant refers to.
* * <p>
* Note that this method is a functional duplicate of getClassIndex for use by ConstantInvokeDynamic. * Note that this method is a functional duplicate of getClassIndex for use by ConstantInvokeDynamic.
* @since 6.0 * @since 6.0
*/ */

View File

@@ -89,6 +89,13 @@ public final class ConstantFloat extends Constant implements ConstantObject {
return bytes; return bytes;
} }
/**
* @param bytes the raw bytes that represent this float
*/
public void setBytes(final float bytes) {
this.bytes = bytes;
}
/** /**
* @return Float object * @return Float object
*/ */
@@ -97,13 +104,6 @@ public final class ConstantFloat extends Constant implements ConstantObject {
return Float.valueOf(bytes); return Float.valueOf(bytes);
} }
/**
* @param bytes the raw bytes that represent this float
*/
public void setBytes(final float bytes) {
this.bytes = bytes;
}
/** /**
* @return String representation. * @return String representation.
*/ */

View File

@@ -88,6 +88,13 @@ public final class ConstantInteger extends Constant implements ConstantObject {
return bytes; return bytes;
} }
/**
* @param bytes the raw bytes that represent this integer
*/
public void setBytes(final int bytes) {
this.bytes = bytes;
}
/** /**
* @return Integer object * @return Integer object
*/ */
@@ -96,13 +103,6 @@ public final class ConstantInteger extends Constant implements ConstantObject {
return Integer.valueOf(bytes); return Integer.valueOf(bytes);
} }
/**
* @param bytes the raw bytes that represent this integer
*/
public void setBytes(final int bytes) {
this.bytes = bytes;
}
/** /**
* @return String representation. * @return String representation.
*/ */

View File

@@ -67,7 +67,7 @@ public final class ConstantInvokeDynamic extends ConstantCP {
/** /**
* @return Reference (index) to bootstrap method this constant refers to. * @return Reference (index) to bootstrap method this constant refers to.
* * <p>
* Note that this method is a functional duplicate of getClassIndex for use by ConstantInvokeDynamic. * Note that this method is a functional duplicate of getClassIndex for use by ConstantInvokeDynamic.
* @since 6.0 * @since 6.0
*/ */

View File

@@ -88,6 +88,13 @@ public final class ConstantLong extends Constant implements ConstantObject {
return bytes; return bytes;
} }
/**
* @param bytes the raw bytes that represent this long
*/
public void setBytes(final long bytes) {
this.bytes = bytes;
}
/** /**
* @return Long object * @return Long object
*/ */
@@ -96,13 +103,6 @@ public final class ConstantLong extends Constant implements ConstantObject {
return Long.valueOf(bytes); return Long.valueOf(bytes);
} }
/**
* @param bytes the raw bytes that represent this long
*/
public void setBytes(final long bytes) {
this.bytes = bytes;
}
/** /**
* @return String representation. * @return String representation.
*/ */

View File

@@ -86,14 +86,14 @@ public final class ConstantMethodHandle extends Constant {
return referenceIndex; return referenceIndex;
} }
public int getReferenceKind() {
return referenceKind;
}
public void setReferenceIndex(final int referenceIndex) { public void setReferenceIndex(final int referenceIndex) {
this.referenceIndex = referenceIndex; this.referenceIndex = referenceIndex;
} }
public int getReferenceKind() {
return referenceKind;
}
public void setReferenceKind(final int referenceKind) { public void setReferenceKind(final int referenceKind) {
this.referenceKind = referenceKind; this.referenceKind = referenceKind;
} }

View File

@@ -100,6 +100,13 @@ public final class ConstantNameAndType extends Constant {
return nameIndex; return nameIndex;
} }
/**
* @param nameIndex the name index of this constant
*/
public void setNameIndex(final int nameIndex) {
this.nameIndex = nameIndex;
}
/** /**
* @return signature * @return signature
*/ */
@@ -114,13 +121,6 @@ public final class ConstantNameAndType extends Constant {
return signatureIndex; return signatureIndex;
} }
/**
* @param nameIndex the name index of this constant
*/
public void setNameIndex(final int nameIndex) {
this.nameIndex = nameIndex;
}
/** /**
* @param signatureIndex the signature index in the constant pool of this type * @param signatureIndex the signature index in the constant pool of this type
*/ */

View File

@@ -35,34 +35,6 @@ import java.util.Iterator;
*/ */
public class ConstantPool implements Cloneable, Node, Iterable<Constant> { public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
private static String escape(final String str) {
final int len = str.length();
final StringBuilder buf = new StringBuilder(len + 5);
final char[] ch = str.toCharArray();
for (int i = 0; i < len; i++) {
switch (ch[i]) {
case '\n':
buf.append("\\n");
break;
case '\r':
buf.append("\\r");
break;
case '\t':
buf.append("\\t");
break;
case '\b':
buf.append("\\b");
break;
case '"':
buf.append("\\\"");
break;
default:
buf.append(ch[i]);
}
}
return buf.toString();
}
private Constant[] constantPool; private Constant[] constantPool;
/** /**
@@ -100,6 +72,34 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
} }
} }
private static String escape(final String str) {
final int len = str.length();
final StringBuilder buf = new StringBuilder(len + 5);
final char[] ch = str.toCharArray();
for (int i = 0; i < len; i++) {
switch (ch[i]) {
case '\n':
buf.append("\\n");
break;
case '\r':
buf.append("\\r");
break;
case '\t':
buf.append("\\t");
break;
case '\b':
buf.append("\\b");
break;
case '"':
buf.append("\\\"");
break;
default:
buf.append(ch[i]);
}
}
return buf.toString();
}
/** /**
* Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., the hierarchy of methods, fields, * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. I.e., the hierarchy of methods, fields,
* attributes, etc. spawns a tree of objects. * attributes, etc. spawns a tree of objects.
@@ -249,8 +249,8 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
* *
* @param index Index in constant pool * @param index Index in constant pool
* @return Constant value * @return Constant value
* @see Constant
* @throws ClassFormatException if index is invalid * @throws ClassFormatException if index is invalid
* @see Constant
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Constant> T getConstant(final int index) throws ClassFormatException { public <T extends Constant> T getConstant(final int index) throws ClassFormatException {
@@ -263,8 +263,8 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
* @param index Index in constant pool * @param index Index in constant pool
* @param tag Tag of expected constant, i.e., its type * @param tag Tag of expected constant, i.e., its type
* @return Constant value * @return Constant value
* @see Constant
* @throws ClassFormatException if constant type does not match tag * @throws ClassFormatException if constant type does not match tag
* @see Constant
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Constant> T getConstant(final int index, final byte tag) throws ClassFormatException { public <T extends Constant> T getConstant(final int index, final byte tag) throws ClassFormatException {
@@ -277,8 +277,8 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
* @param index Index in constant pool * @param index Index in constant pool
* @param tag Tag of expected constant, i.e., its type * @param tag Tag of expected constant, i.e., its type
* @return Constant value * @return Constant value
* @see Constant
* @throws ClassFormatException if constant type does not match tag * @throws ClassFormatException if constant type does not match tag
* @see Constant
* @since 6.6.0 * @since 6.6.0
*/ */
public <T extends Constant> T getConstant(final int index, final byte tag, final Class<T> castTo) throws ClassFormatException { public <T extends Constant> T getConstant(final int index, final byte tag, final Class<T> castTo) throws ClassFormatException {
@@ -296,8 +296,8 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
* @param index Index in constant pool * @param index Index in constant pool
* @param castTo The {@link Constant} subclass to cast to. * @param castTo The {@link Constant} subclass to cast to.
* @return Constant value * @return Constant value
* @see Constant
* @throws ClassFormatException if index is invalid * @throws ClassFormatException if index is invalid
* @see Constant
* @since 6.6.0 * @since 6.6.0
*/ */
public <T extends Constant> T getConstant(final int index, final Class<T> castTo) throws ClassFormatException { public <T extends Constant> T getConstant(final int index, final Class<T> castTo) throws ClassFormatException {
@@ -326,8 +326,8 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
* *
* @param index Index in constant pool * @param index Index in constant pool
* @return ConstantInteger value * @return ConstantInteger value
* @see ConstantInteger
* @throws ClassFormatException if constant type does not match tag * @throws ClassFormatException if constant type does not match tag
* @see ConstantInteger
*/ */
public ConstantInteger getConstantInteger(final int index) { public ConstantInteger getConstantInteger(final int index) {
return getConstant(index, Const.CONSTANT_Integer, ConstantInteger.class); return getConstant(index, Const.CONSTANT_Integer, ConstantInteger.class);
@@ -341,6 +341,13 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
return constantPool; return constantPool;
} }
/**
* @param constantPool
*/
public void setConstantPool(final Constant[] constantPool) {
this.constantPool = constantPool;
}
/** /**
* Gets string from constant pool and bypass the indirection of 'ConstantClass' and 'ConstantString' objects. I.e. these classes have an index field that * Gets string from constant pool and bypass the indirection of 'ConstantClass' and 'ConstantString' objects. I.e. these classes have an index field that
* points to another entry of the constant pool of type 'ConstantUtf8' which contains the real data. * points to another entry of the constant pool of type 'ConstantUtf8' which contains the real data.
@@ -348,9 +355,9 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
* @param index Index in constant pool * @param index Index in constant pool
* @param tag Tag of expected constant, either ConstantClass or ConstantString * @param tag Tag of expected constant, either ConstantClass or ConstantString
* @return Contents of string reference * @return Contents of string reference
* @throws IllegalArgumentException if tag is invalid
* @see ConstantClass * @see ConstantClass
* @see ConstantString * @see ConstantString
* @throws IllegalArgumentException if tag is invalid
*/ */
public String getConstantString(final int index, final byte tag) throws IllegalArgumentException { public String getConstantString(final int index, final byte tag) throws IllegalArgumentException {
int i; int i;
@@ -386,8 +393,8 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
* *
* @param index Index in constant pool * @param index Index in constant pool
* @return ConstantUtf8 value * @return ConstantUtf8 value
* @see ConstantUtf8
* @throws ClassFormatException if constant type does not match tag * @throws ClassFormatException if constant type does not match tag
* @see ConstantUtf8
*/ */
public ConstantUtf8 getConstantUtf8(final int index) throws ClassFormatException { public ConstantUtf8 getConstantUtf8(final int index) throws ClassFormatException {
return getConstant(index, Const.CONSTANT_Utf8, ConstantUtf8.class); return getConstant(index, Const.CONSTANT_Utf8, ConstantUtf8.class);
@@ -412,13 +419,6 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
constantPool[index] = constant; constantPool[index] = constant;
} }
/**
* @param constantPool
*/
public void setConstantPool(final Constant[] constantPool) {
this.constantPool = constantPool;
}
/** /**
* @return String representation. * @return String representation.
*/ */
@@ -430,4 +430,164 @@ public class ConstantPool implements Cloneable, Node, Iterable<Constant> {
} }
return buf.toString(); return buf.toString();
} }
// ---------------------------------------------- haidnorJVM
public ConstantFieldref getConstantFieldref(int constantFieldrefIndex) {
return getConstant(constantFieldrefIndex);
}
public ConstantMethodref getConstantMethodref(int constantMethodrefIndex) {
return getConstant(constantMethodrefIndex);
}
public ConstantClass getConstantClass(int constantClassIndex) {
return getConstant(constantClassIndex);
}
public ConstantNameAndType getConstantNameAndType(int constantNameAndTypeIndex) {
return getConstant(constantNameAndTypeIndex);
}
// ConstantClass ---------------------------------------------------------------------------------------------------
/**
* 获取长类名, 例如 java/lang/String
*/
public String constantClass_ClassName(final ConstantClass constantClass) {
ConstantUtf8 constantUtf8 = getConstant(constantClass.getNameIndex());
return constantUtf8.getBytes();
}
/**
* 获取长类名, 例如 java/lang/String
*/
public String constantClass_ClassName(int constantClassIndex) {
ConstantClass constantClass = getConstant(constantClassIndex);
return constantClass_ClassName(constantClass);
}
// ConstantFieldref ------------------------------------------------------------------------------------------------
/**
* 获取字段所处于Java类的类名, 例如 java/lang/String
*/
public String constantFieldref_ClassName(final ConstantFieldref constantFieldref) {
ConstantClass constClass = getConstant(constantFieldref.getClassIndex());
return (String) constClass.getConstantValue(this);
}
/**
* 获取字段所处于Java类的类名, 例如 java/lang/String
*/
public String constantFieldref_ClassName(int constantFieldrefIndex) {
ConstantFieldref constantFieldref = getConstantFieldref(constantFieldrefIndex);
return constantFieldref_ClassName(constantFieldref);
}
/**
* 获取字段名称
*/
public String getFieldName(final ConstantFieldref constantFieldref) {
ConstantNameAndType constNameAndType = getConstant(constantFieldref.getNameAndTypeIndex());
return constNameAndType.getName(this);
}
/**
* 获取字段名称
*/
public String getFieldName(int constantFieldrefIndex) {
ConstantFieldref constantFieldref = getConstantFieldref(constantFieldrefIndex);
return getFieldName(constantFieldref);
}
/**
* 获取字段类型签名
*/
public String getFieldSignature(final ConstantFieldref constantFieldref) {
ConstantNameAndType constNameAndType = getConstant(constantFieldref.getNameAndTypeIndex());
return constNameAndType.getSignature(this);
}
/**
* 获取字段类型签名
*/
public String getFieldSignature(int constantFieldrefIndex) {
ConstantFieldref constantFieldref = getConstantFieldref(constantFieldrefIndex);
return getFieldSignature(constantFieldref);
}
// ConstantMethodref -----------------------------------------------------------------------------------------------
/**
* 获取方法所处于Java类的类名
* 名称使用/分割,例如 haidnor/jvm/test/instruction/references/NEW
*/
public String constantMethodref_ClassName(final ConstantMethodref methodref) {
ConstantClass constClass = getConstant(methodref.getClassIndex());
return (String) constClass.getConstantValue(this);
}
/**
* 获取方法名
*/
public String constantMethodref_MethodName(final ConstantMethodref methodref) {
ConstantNameAndType constNameAndType = getConstant(methodref.getNameAndTypeIndex());
return constNameAndType.getName(this);
}
/**
* 获取方法签名
*/
public String constantMethodref_MethodSignature(final ConstantMethodref methodref) {
ConstantNameAndType constNameAndType = getConstant(methodref.getNameAndTypeIndex());
return constNameAndType.getSignature(this);
}
// ConstantInterfaceMethodref -----------------------------------------------------------------------------------------------
public String constantInterfaceMethodref_ClassName(final ConstantInterfaceMethodref methodref) {
ConstantClass constClass = getConstant(methodref.getClassIndex());
return (String) constClass.getConstantValue(this);
}
/**
* 获取方法名
*/
public String constantInterfaceMethodref_MethodName(final ConstantInterfaceMethodref methodref) {
ConstantNameAndType constNameAndType = getConstant(methodref.getNameAndTypeIndex());
return constNameAndType.getName(this);
}
/**
* 获取方法签名
*/
public String constantInterfaceMethodref_MethodSignature(final ConstantInterfaceMethodref methodref) {
ConstantNameAndType constNameAndType = getConstant(methodref.getNameAndTypeIndex());
return constNameAndType.getSignature(this);
}
// ConstantNameAndType -----------------------------------------------------------------------------------------------
/**
* ConstantNameAndType
*/
public ConstantNameAndType constantNameAndType(int constantNameAndTypeIndex) {
return getConstant(constantNameAndTypeIndex);
}
public String constantNameAndType_name(int constantNameAndTypeIndex) {
ConstantNameAndType constantNameAndType = constantNameAndType(constantNameAndTypeIndex);
return constantNameAndType.getName(this);
}
public String constantNameAndType_signature(int constantNameAndTypeIndex) {
ConstantNameAndType constantNameAndType = constantNameAndType(constantNameAndTypeIndex);
return constantNameAndType.getSignature(this);
}
} }

View File

@@ -57,47 +57,53 @@ import java.util.Objects;
*/ */
public final class ConstantUtf8 extends Constant { public final class ConstantUtf8 extends Constant {
private static class Cache { private static final String SYS_PROP_CACHE_MAX_ENTRIES = "bcel.maxcached";
private static final String SYS_PROP_CACHE_MAX_ENTRY_SIZE = "bcel.maxcached.size";
private static final boolean BCEL_STATISTICS = Boolean.getBoolean(SYS_PROP_STATISTICS); private static final String SYS_PROP_STATISTICS = "bcel.statistics";
private static final int MAX_ENTRIES = Integer.getInteger(SYS_PROP_CACHE_MAX_ENTRIES, 0).intValue();
private static final int INITIAL_CAPACITY = (int) (MAX_ENTRIES / 0.75);
private static final HashMap<String, ConstantUtf8> CACHE = new LinkedHashMap<String, ConstantUtf8>(INITIAL_CAPACITY, 0.75f, true) {
private static final long serialVersionUID = -8506975356158971766L;
@Override
protected boolean removeEldestEntry(final Map.Entry<String, ConstantUtf8> eldest) {
return size() > MAX_ENTRIES;
}
};
// Set the size to 0 or below to skip caching entirely
private static final int MAX_ENTRY_SIZE = Integer.getInteger(SYS_PROP_CACHE_MAX_ENTRY_SIZE, 200).intValue();
static boolean isEnabled() {
return Cache.MAX_ENTRIES > 0 && MAX_ENTRY_SIZE > 0;
}
}
// TODO these should perhaps be AtomicInt? // TODO these should perhaps be AtomicInt?
private static volatile int considered; private static volatile int considered;
private static volatile int created; private static volatile int created;
private static volatile int hits; private static volatile int hits;
private static volatile int skipped; private static volatile int skipped;
private static final String SYS_PROP_CACHE_MAX_ENTRIES = "bcel.maxcached";
private static final String SYS_PROP_CACHE_MAX_ENTRY_SIZE = "bcel.maxcached.size";
private static final String SYS_PROP_STATISTICS = "bcel.statistics";
static { static {
if (Cache.BCEL_STATISTICS) { if (Cache.BCEL_STATISTICS) {
Runtime.getRuntime().addShutdownHook(new Thread(ConstantUtf8::printStats)); Runtime.getRuntime().addShutdownHook(new Thread(ConstantUtf8::printStats));
} }
} }
private final String value;
/**
* Initializes from another object.
*
* @param constantUtf8 the value.
*/
public ConstantUtf8(final ConstantUtf8 constantUtf8) {
this(constantUtf8.getBytes());
}
/**
* Initializes instance from file data.
*
* @param dataInput Input stream
* @throws IOException if an I/O error occurs.
*/
ConstantUtf8(final DataInput dataInput) throws IOException {
super(Const.CONSTANT_Utf8);
value = dataInput.readUTF();
created++;
}
/**
* @param value Data
*/
public ConstantUtf8(final String value) {
super(Const.CONSTANT_Utf8);
this.value = Objects.requireNonNull(value, "value");
created++;
}
/** /**
* Clears the cache. * Clears the cache.
* *
@@ -178,38 +184,6 @@ public final class ConstantUtf8 extends Constant {
Cache.MAX_ENTRY_SIZE); Cache.MAX_ENTRY_SIZE);
} }
private final String value;
/**
* Initializes from another object.
*
* @param constantUtf8 the value.
*/
public ConstantUtf8(final ConstantUtf8 constantUtf8) {
this(constantUtf8.getBytes());
}
/**
* Initializes instance from file data.
*
* @param dataInput Input stream
* @throws IOException if an I/O error occurs.
*/
ConstantUtf8(final DataInput dataInput) throws IOException {
super(Const.CONSTANT_Utf8);
value = dataInput.readUTF();
created++;
}
/**
* @param value Data
*/
public ConstantUtf8(final String value) {
super(Const.CONSTANT_Utf8);
this.value = Objects.requireNonNull(value, "value");
created++;
}
/** /**
* Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
* I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.
@@ -256,4 +230,29 @@ public final class ConstantUtf8 extends Constant {
public String toString() { public String toString() {
return super.toString() + "(\"" + Utility.replace(value, "\n", "\\n") + "\")"; return super.toString() + "(\"" + Utility.replace(value, "\n", "\\n") + "\")";
} }
private static class Cache {
private static final boolean BCEL_STATISTICS = Boolean.getBoolean(SYS_PROP_STATISTICS);
private static final int MAX_ENTRIES = Integer.getInteger(SYS_PROP_CACHE_MAX_ENTRIES, 0).intValue();
private static final int INITIAL_CAPACITY = (int) (MAX_ENTRIES / 0.75);
private static final HashMap<String, ConstantUtf8> CACHE = new LinkedHashMap<String, ConstantUtf8>(INITIAL_CAPACITY, 0.75f, true) {
private static final long serialVersionUID = -8506975356158971766L;
@Override
protected boolean removeEldestEntry(final Map.Entry<String, ConstantUtf8> eldest) {
return size() > MAX_ENTRIES;
}
};
// Set the size to 0 or below to skip caching entirely
private static final int MAX_ENTRY_SIZE = Integer.getInteger(SYS_PROP_CACHE_MAX_ENTRY_SIZE, 200).intValue();
static boolean isEnabled() {
return Cache.MAX_ENTRIES > 0 && MAX_ENTRY_SIZE > 0;
}
}
} }

View File

@@ -34,6 +34,7 @@ import java.io.IOException;
* u2 constantvalue_index; * u2 constantvalue_index;
* } * }
* </pre> * </pre>
*
* @see Attribute * @see Attribute
*/ */
public final class ConstantValue extends Attribute { public final class ConstantValue extends Attribute {

View File

@@ -153,7 +153,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.3 */ /**
* @since 6.3
*/
@Override @Override
public void visitConstantDynamic(final ConstantDynamic obj) { public void visitConstantDynamic(final ConstantDynamic obj) {
stack.push(obj); stack.push(obj);
@@ -206,7 +208,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.0 */ /**
* @since 6.0
*/
@Override @Override
public void visitConstantMethodHandle(final ConstantMethodHandle obj) { public void visitConstantMethodHandle(final ConstantMethodHandle obj) {
stack.push(obj); stack.push(obj);
@@ -221,7 +225,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.0 */ /**
* @since 6.0
*/
@Override @Override
public void visitConstantMethodType(final ConstantMethodType obj) { public void visitConstantMethodType(final ConstantMethodType obj) {
stack.push(obj); stack.push(obj);
@@ -229,7 +235,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.1 */ /**
* @since 6.1
*/
@Override @Override
public void visitConstantModule(final ConstantModule obj) { public void visitConstantModule(final ConstantModule obj) {
stack.push(obj); stack.push(obj);
@@ -244,7 +252,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.1 */ /**
* @since 6.1
*/
@Override @Override
public void visitConstantPackage(final ConstantPackage obj) { public void visitConstantPackage(final ConstantPackage obj) {
stack.push(obj); stack.push(obj);
@@ -408,7 +418,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModule(final Module obj) { public void visitModule(final Module obj) {
stack.push(obj); stack.push(obj);
@@ -420,7 +432,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleExports(final ModuleExports obj) { public void visitModuleExports(final ModuleExports obj) {
stack.push(obj); stack.push(obj);
@@ -428,7 +442,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleMainClass(final ModuleMainClass obj) { public void visitModuleMainClass(final ModuleMainClass obj) {
stack.push(obj); stack.push(obj);
@@ -436,7 +452,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleOpens(final ModuleOpens obj) { public void visitModuleOpens(final ModuleOpens obj) {
stack.push(obj); stack.push(obj);
@@ -444,7 +462,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModulePackages(final ModulePackages obj) { public void visitModulePackages(final ModulePackages obj) {
stack.push(obj); stack.push(obj);
@@ -452,7 +472,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleProvides(final ModuleProvides obj) { public void visitModuleProvides(final ModuleProvides obj) {
stack.push(obj); stack.push(obj);
@@ -460,7 +482,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleRequires(final ModuleRequires obj) { public void visitModuleRequires(final ModuleRequires obj) {
stack.push(obj); stack.push(obj);
@@ -468,7 +492,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitNestHost(final NestHost obj) { public void visitNestHost(final NestHost obj) {
stack.push(obj); stack.push(obj);
@@ -476,7 +502,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitNestMembers(final NestMembers obj) { public void visitNestMembers(final NestMembers obj) {
stack.push(obj); stack.push(obj);
@@ -494,7 +522,9 @@ public class DescendingVisitor implements Visitor {
stack.pop(); stack.pop();
} }
/** @since 6.0 */ /**
* @since 6.0
*/
@Override @Override
public void visitParameterAnnotationEntry(final ParameterAnnotationEntry obj) { public void visitParameterAnnotationEntry(final ParameterAnnotationEntry obj) {
stack.push(obj); stack.push(obj);

View File

@@ -46,6 +46,7 @@ import java.io.IOException;
* } value; * } value;
* } * }
* </pre> * </pre>
*
* @since 6.0 * @since 6.0
*/ */
public abstract class ElementValue { public abstract class ElementValue {
@@ -63,6 +64,21 @@ public abstract class ElementValue {
public static final byte PRIMITIVE_LONG = 'J'; public static final byte PRIMITIVE_LONG = 'J';
public static final byte PRIMITIVE_SHORT = 'S'; public static final byte PRIMITIVE_SHORT = 'S';
public static final byte PRIMITIVE_BOOLEAN = 'Z'; public static final byte PRIMITIVE_BOOLEAN = 'Z';
/**
* @deprecated (since 6.0) will be made private and final; do not access directly, use getter
*/
@java.lang.Deprecated
protected int type; // TODO should be final
/**
* @deprecated (since 6.0) will be made private and final; do not access directly, use getter
*/
@java.lang.Deprecated
protected ConstantPool cpool; // TODO should be final
protected ElementValue(final int type, final ConstantPool cpool) {
this.type = type;
this.cpool = cpool;
}
/** /**
* Reads an {@code element_value} as an {@code ElementValue}. * Reads an {@code element_value} as an {@code ElementValue}.
@@ -129,25 +145,11 @@ public abstract class ElementValue {
} }
} }
/**
* @deprecated (since 6.0) will be made private and final; do not access directly, use getter
*/
@java.lang.Deprecated
protected int type; // TODO should be final
/**
* @deprecated (since 6.0) will be made private and final; do not access directly, use getter
*/
@java.lang.Deprecated
protected ConstantPool cpool; // TODO should be final
protected ElementValue(final int type, final ConstantPool cpool) {
this.type = type;
this.cpool = cpool;
}
public abstract void dump(DataOutputStream dos) throws IOException; public abstract void dump(DataOutputStream dos) throws IOException;
/** @since 6.0 */ /**
* @since 6.0
*/
final ConstantPool getConstantPool() { final ConstantPool getConstantPool() {
return cpool; return cpool;
} }
@@ -156,7 +158,9 @@ public abstract class ElementValue {
return type; return type;
} }
/** @since 6.0 */ /**
* @since 6.0
*/
final int getType() { final int getType() {
return type; return type;
} }

View File

@@ -235,47 +235,65 @@ public class EmptyVisitor implements Visitor {
public void visitMethodParameters(final MethodParameters obj) { public void visitMethodParameters(final MethodParameters obj) {
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModule(final Module obj) { public void visitModule(final Module obj) {
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleExports(final ModuleExports obj) { public void visitModuleExports(final ModuleExports obj) {
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleMainClass(final ModuleMainClass obj) { public void visitModuleMainClass(final ModuleMainClass obj) {
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleOpens(final ModuleOpens obj) { public void visitModuleOpens(final ModuleOpens obj) {
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModulePackages(final ModulePackages obj) { public void visitModulePackages(final ModulePackages obj) {
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleProvides(final ModuleProvides obj) { public void visitModuleProvides(final ModuleProvides obj) {
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitModuleRequires(final ModuleRequires obj) { public void visitModuleRequires(final ModuleRequires obj) {
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitNestHost(final NestHost obj) { public void visitNestHost(final NestHost obj) {
} }
/** @since 6.4.0 */ /**
* @since 6.4.0
*/
@Override @Override
public void visitNestMembers(final NestMembers obj) { public void visitNestMembers(final NestMembers obj) {
} }

View File

@@ -5,9 +5,9 @@
* The ASF licenses this file to You under the Apache License, Version 2.0 * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* * <p>
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* * <p>
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -81,6 +81,10 @@ public class EnclosingMethod extends Attribute {
return classIndex; return classIndex;
} }
public final void setEnclosingClassIndex(final int idx) {
classIndex = idx;
}
public final ConstantNameAndType getEnclosingMethod() { public final ConstantNameAndType getEnclosingMethod() {
if (methodIndex == 0) { if (methodIndex == 0) {
return null; return null;
@@ -92,10 +96,6 @@ public class EnclosingMethod extends Attribute {
return methodIndex; return methodIndex;
} }
public final void setEnclosingClassIndex(final int idx) {
classIndex = idx;
}
public final void setEnclosingMethodIndex(final int idx) { public final void setEnclosingMethodIndex(final int idx) {
methodIndex = idx; methodIndex = idx;
} }

View File

@@ -40,6 +40,7 @@ import java.util.Arrays;
* u2 exception_index_table[number_of_exceptions]; * u2 exception_index_table[number_of_exceptions];
* } * }
* </pre> * </pre>
*
* @see Code * @see Code
*/ */
public final class ExceptionTable extends Attribute { public final class ExceptionTable extends Attribute {
@@ -132,6 +133,14 @@ public final class ExceptionTable extends Attribute {
return exceptionIndexTable; return exceptionIndexTable;
} }
/**
* @param exceptionIndexTable the list of exception indexes Also redefines number_of_exceptions according to table
* length.
*/
public void setExceptionIndexTable(final int[] exceptionIndexTable) {
this.exceptionIndexTable = exceptionIndexTable != null ? exceptionIndexTable : ArrayUtils.EMPTY_INT_ARRAY;
}
/** /**
* @return class names of thrown exceptions * @return class names of thrown exceptions
*/ */
@@ -148,14 +157,6 @@ public final class ExceptionTable extends Attribute {
return exceptionIndexTable == null ? 0 : exceptionIndexTable.length; return exceptionIndexTable == null ? 0 : exceptionIndexTable.length;
} }
/**
* @param exceptionIndexTable the list of exception indexes Also redefines number_of_exceptions according to table
* length.
*/
public void setExceptionIndexTable(final int[] exceptionIndexTable) {
this.exceptionIndexTable = exceptionIndexTable != null ? exceptionIndexTable : ArrayUtils.EMPTY_INT_ARRAY;
}
/** /**
* @return String representation, i.e., a list of thrown exceptions. * @return String representation, i.e., a list of thrown exceptions.
*/ */

View File

@@ -50,16 +50,13 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No
*/ */
@java.lang.Deprecated @java.lang.Deprecated
protected int attributes_count; // No. of attributes protected int attributes_count; // No. of attributes
// @since 6.0
private AnnotationEntry[] annotationEntries; // annotations defined on the field or method
/** /**
* @deprecated (since 6.0) will be made private; do not access directly, use getter/setter * @deprecated (since 6.0) will be made private; do not access directly, use getter/setter
*/ */
@java.lang.Deprecated @java.lang.Deprecated
protected ConstantPool constant_pool; protected ConstantPool constant_pool;
// @since 6.0
private AnnotationEntry[] annotationEntries; // annotations defined on the field or method
private String signatureAttributeString; private String signatureAttributeString;
private boolean searchedForSignatureAttribute; private boolean searchedForSignatureAttribute;
@@ -173,6 +170,14 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No
return attributes; return attributes;
} }
/**
* @param attributes Collection of object attributes.
*/
public final void setAttributes(final Attribute[] attributes) {
this.attributes = attributes;
this.attributes_count = attributes != null ? attributes.length : 0; // init deprecated field
}
/** /**
* @return Constant pool used by this object. * @return Constant pool used by this object.
*/ */
@@ -180,6 +185,13 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No
return constant_pool; return constant_pool;
} }
/**
* @param constantPool Constant pool to be used for this object.
*/
public final void setConstantPool(final ConstantPool constantPool) {
this.constant_pool = constantPool;
}
/** /**
* Hunts for a signature attribute on the member and returns its contents. So where the 'regular' signature may be * Hunts for a signature attribute on the member and returns its contents. So where the 'regular' signature may be
* (Ljava/util/Vector;)V the signature attribute may in fact say 'Ljava/lang/Vector&lt;Ljava/lang/String&gt;;' Coded for * (Ljava/util/Vector;)V the signature attribute may in fact say 'Ljava/lang/Vector&lt;Ljava/lang/String&gt;;' Coded for
@@ -215,6 +227,13 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No
return name_index; return name_index;
} }
/**
* @param nameIndex Index in constant pool of object's name.
*/
public final void setNameIndex(final int nameIndex) {
this.name_index = nameIndex;
}
/** /**
* @return String representation of object's type signature (java style) * @return String representation of object's type signature (java style)
*/ */
@@ -229,28 +248,6 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No
return signature_index; return signature_index;
} }
/**
* @param attributes Collection of object attributes.
*/
public final void setAttributes(final Attribute[] attributes) {
this.attributes = attributes;
this.attributes_count = attributes != null ? attributes.length : 0; // init deprecated field
}
/**
* @param constantPool Constant pool to be used for this object.
*/
public final void setConstantPool(final ConstantPool constantPool) {
this.constant_pool = constantPool;
}
/**
* @param nameIndex Index in constant pool of object's name.
*/
public final void setNameIndex(final int nameIndex) {
this.name_index = nameIndex;
}
/** /**
* @param signatureIndex Index in constant pool of field signature. * @param signatureIndex Index in constant pool of field signature.
*/ */

View File

@@ -110,27 +110,6 @@ public final class InnerClass implements Cloneable, Node {
return innerAccessFlags; return innerAccessFlags;
} }
/**
* @return class index of inner class.
*/
public int getInnerClassIndex() {
return innerClassIndex;
}
/**
* @return name index of inner class.
*/
public int getInnerNameIndex() {
return innerNameIndex;
}
/**
* @return class index of outer class.
*/
public int getOuterClassIndex() {
return outerClassIndex;
}
/** /**
* @param innerAccessFlags access flags for this inner class * @param innerAccessFlags access flags for this inner class
*/ */
@@ -138,6 +117,13 @@ public final class InnerClass implements Cloneable, Node {
this.innerAccessFlags = innerAccessFlags; this.innerAccessFlags = innerAccessFlags;
} }
/**
* @return class index of inner class.
*/
public int getInnerClassIndex() {
return innerClassIndex;
}
/** /**
* @param innerClassIndex index into the constant pool for this class * @param innerClassIndex index into the constant pool for this class
*/ */
@@ -145,6 +131,13 @@ public final class InnerClass implements Cloneable, Node {
this.innerClassIndex = innerClassIndex; this.innerClassIndex = innerClassIndex;
} }
/**
* @return name index of inner class.
*/
public int getInnerNameIndex() {
return innerNameIndex;
}
/** /**
* @param innerNameIndex index into the constant pool for this class's name * @param innerNameIndex index into the constant pool for this class's name
*/ */
@@ -152,6 +145,13 @@ public final class InnerClass implements Cloneable, Node {
this.innerNameIndex = innerNameIndex; this.innerNameIndex = innerNameIndex;
} }
/**
* @return class index of outer class.
*/
public int getOuterClassIndex() {
return outerClassIndex;
}
/** /**
* @param outerClassIndex index into the constant pool for the owning class * @param outerClassIndex index into the constant pool for the owning class
*/ */

View File

@@ -127,11 +127,6 @@ public final class InnerClasses extends Attribute implements Iterable<InnerClass
return innerClasses; return innerClasses;
} }
@Override
public Iterator<InnerClass> iterator() {
return Stream.of(innerClasses).iterator();
}
/** /**
* @param innerClasses the array of inner classes * @param innerClasses the array of inner classes
*/ */
@@ -139,6 +134,11 @@ public final class InnerClasses extends Attribute implements Iterable<InnerClass
this.innerClasses = innerClasses != null ? innerClasses : EMPTY_INNER_CLASSE_ARRAY; this.innerClasses = innerClasses != null ? innerClasses : EMPTY_INNER_CLASSE_ARRAY;
} }
@Override
public Iterator<InnerClass> iterator() {
return Stream.of(innerClasses).iterator();
}
/** /**
* @return String representation. * @return String representation.
*/ */

View File

@@ -23,6 +23,9 @@ import haidnor.jvm.bcel.util.BCELComparator;
import haidnor.jvm.bcel.util.ClassQueue; import haidnor.jvm.bcel.util.ClassQueue;
import haidnor.jvm.bcel.util.Repository; import haidnor.jvm.bcel.util.Repository;
import haidnor.jvm.bcel.util.SyntheticRepository; import haidnor.jvm.bcel.util.SyntheticRepository;
import haidnor.jvm.classloader.JVMClassLoader;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import java.io.*; import java.io.*;
@@ -71,41 +74,10 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return THIS.getClassName().hashCode(); return THIS.getClassName().hashCode();
} }
}; };
/*
* Print debug information depending on 'JavaClass.debug'
*/
static void Debug(final String str) {
if (debug) {
System.out.println(str);
}
}
/**
* @return Comparison strategy object
*/
public static BCELComparator getComparator() {
return bcelComparator;
}
private static String indent(final Object obj) {
final StringTokenizer tokenizer = new StringTokenizer(obj.toString(), "\n");
final StringBuilder buf = new StringBuilder();
while (tokenizer.hasMoreTokens()) {
buf.append("\t").append(tokenizer.nextToken()).append("\n");
}
return buf.toString();
}
/**
* @param comparator Comparison strategy object
*/
public static void setComparator(final BCELComparator comparator) {
bcelComparator = comparator;
}
private String fileName;
private final String packageName; private final String packageName;
@Getter
private final Map<String, JavaField> staticJavaFieldMap = new HashMap<>();
private String fileName;
private String sourceFileName = "<Unknown>"; private String sourceFileName = "<Unknown>";
private int classNameIndex; private int classNameIndex;
private int superclassNameIndex; private int superclassNameIndex;
@@ -119,21 +91,23 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
private JavaField[] fields; // Fields, i.e., variables of class private JavaField[] fields; // Fields, i.e., variables of class
private JavaMethod[] methods; // methods defined in the class private JavaMethod[] methods; // methods defined in the class
private Attribute[] attributes; // attributes defined in the class private Attribute[] attributes; // attributes defined in the class
private AnnotationEntry[] annotations; // annotations defined on the class private AnnotationEntry[] annotations; // annotations defined on the class
private byte source = HEAP; // Generated in memory private byte source = HEAP; // Generated in memory
private boolean isAnonymous; private boolean isAnonymous;
private boolean isNested; private boolean isNested;
private boolean computedNestedTypeStatus; private boolean computedNestedTypeStatus;
// ---------------------------------------------- haidnorJVM >
/** /**
* In cases where we go ahead and create something, use the default SyntheticRepository, because we don't know any * In cases where we go ahead and create something, use the default SyntheticRepository, because we don't know any
* better. * better.
*/ */
private transient Repository repository = SyntheticRepository.getInstance(); private transient Repository repository = SyntheticRepository.getInstance();
@Getter
@Setter
private JVMClassLoader JVMClassLoader;
// ---------------------------------------------- haidnorJVM <
/** /**
* Constructor gets all contents as arguments. * Constructor gets all contents as arguments.
@@ -229,6 +203,45 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
final String str = constantPool.getConstantString(interfaces[i], Const.CONSTANT_Class); final String str = constantPool.getConstantString(interfaces[i], Const.CONSTANT_Class);
interfaceNames[i] = Utility.compactClassName(str, false); interfaceNames[i] = Utility.compactClassName(str, false);
} }
// 初始化静态字段
for (JavaField field : getFields()) {
if (field.isStatic()) {
staticJavaFieldMap.put(field.getName(), field);
}
}
}
/*
* Print debug information depending on 'JavaClass.debug'
*/
static void Debug(final String str) {
if (debug) {
System.out.println(str);
}
}
/**
* @return Comparison strategy object
*/
public static BCELComparator getComparator() {
return bcelComparator;
}
/**
* @param comparator Comparison strategy object
*/
public static void setComparator(final BCELComparator comparator) {
bcelComparator = comparator;
}
private static String indent(final Object obj) {
final StringTokenizer tokenizer = new StringTokenizer(obj.toString(), "\n");
final StringBuilder buf = new StringBuilder();
while (tokenizer.hasMoreTokens()) {
buf.append("\t").append(tokenizer.nextToken()).append("\n");
}
return buf.toString();
} }
/** /**
@@ -429,6 +442,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return attributes; return attributes;
} }
/**
* @param attributes .
*/
public void setAttributes(final Attribute[] attributes) {
this.attributes = attributes;
}
/** /**
* @return class in binary format * @return class in binary format
*/ */
@@ -449,6 +469,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return className; return className;
} }
/**
* @param className .
*/
public void setClassName(final String className) {
this.className = className;
}
/** /**
* @return Class name index. * @return Class name index.
*/ */
@@ -456,6 +483,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return classNameIndex; return classNameIndex;
} }
/**
* @param classNameIndex .
*/
public void setClassNameIndex(final int classNameIndex) {
this.classNameIndex = classNameIndex;
}
/** /**
* @return Constant pool. * @return Constant pool.
*/ */
@@ -463,6 +497,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return constantPool; return constantPool;
} }
/**
* @param constantPool .
*/
public void setConstantPool(final ConstantPool constantPool) {
this.constantPool = constantPool;
}
/** /**
* @return Fields, i.e., variables of the class. Like the JVM spec mandates for the classfile format, these fields are * @return Fields, i.e., variables of the class. Like the JVM spec mandates for the classfile format, these fields are
* those specific to this class, and not those of the superclass or superinterfaces. * those specific to this class, and not those of the superclass or superinterfaces.
@@ -471,6 +512,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return fields; return fields;
} }
/**
* @param fields .
*/
public void setFields(final JavaField[] fields) {
this.fields = fields;
}
/** /**
* @return File name of class, aka SourceFile attribute value * @return File name of class, aka SourceFile attribute value
*/ */
@@ -478,6 +526,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return fileName; return fileName;
} }
/**
* Set File name of class, aka SourceFile attribute value
*/
public void setFileName(final String fileName) {
this.fileName = fileName;
}
/** /**
* @return Indices in constant pool of implemented interfaces. * @return Indices in constant pool of implemented interfaces.
*/ */
@@ -492,6 +547,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return interfaceNames; return interfaceNames;
} }
/**
* @param interfaceNames .
*/
public void setInterfaceNames(final String[] interfaceNames) {
this.interfaceNames = interfaceNames;
}
/** /**
* Get interfaces directly implemented by this JavaClass. * Get interfaces directly implemented by this JavaClass.
* *
@@ -506,6 +568,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return classes; return classes;
} }
/**
* @param interfaces .
*/
public void setInterfaces(final int[] interfaces) {
this.interfaces = interfaces;
}
/** /**
* @return Major number of class file version. * @return Major number of class file version.
*/ */
@@ -513,6 +582,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return major; return major;
} }
/**
* @param major .
*/
public void setMajor(final int major) {
this.major = major;
}
/** /**
* @return A {@link JavaMethod} corresponding to java.lang.reflect.Method if any * @return A {@link JavaMethod} corresponding to java.lang.reflect.Method if any
*/ */
@@ -532,6 +608,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return methods; return methods;
} }
/**
* @param methods .
*/
public void setMethods(final JavaMethod[] methods) {
this.methods = methods;
}
/** /**
* @return Minor number of class file version. * @return Minor number of class file version.
*/ */
@@ -539,6 +622,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return minor; return minor;
} }
/**
* @param minor .
*/
public void setMinor(final int minor) {
this.minor = minor;
}
/** /**
* @return Package name. * @return Package name.
*/ */
@@ -554,6 +644,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return repository; return repository;
} }
/**
* Sets the ClassRepository which loaded the JavaClass. Should be called immediately after parsing is done.
*/
public void setRepository(final Repository repository) { // TODO make protected?
this.repository = repository;
}
/** /**
* @return returns either HEAP (generated), FILE, or ZIP * @return returns either HEAP (generated), FILE, or ZIP
*/ */
@@ -568,6 +665,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return sourceFileName; return sourceFileName;
} }
/**
* Set absolute path to file this class was read from.
*/
public void setSourceFileName(final String sourceFileName) {
this.sourceFileName = sourceFileName;
}
/** /**
* Gets the source file path including the package path. * Gets the source file path including the package path.
* *
@@ -618,6 +722,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return superclassName; return superclassName;
} }
/**
* @param superclassName .
*/
public void setSuperclassName(final String superclassName) {
this.superclassName = superclassName;
}
/** /**
* @return Class name index. * @return Class name index.
*/ */
@@ -625,6 +736,17 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return superclassNameIndex; return superclassNameIndex;
} }
/**
* @param superclassNameIndex .
*/
public void setSuperclassNameIndex(final int superclassNameIndex) {
this.superclassNameIndex = superclassNameIndex;
}
public JavaField getStaticField(String filedName) {
return staticJavaFieldMap.get(filedName);
}
/** /**
* Return value as defined by given BCELComparator strategy. By default return the hashcode of the class name. * Return value as defined by given BCELComparator strategy. By default return the hashcode of the class name.
* *
@@ -700,111 +822,6 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
return (super.getAccessFlags() & Const.ACC_SUPER) != 0; return (super.getAccessFlags() & Const.ACC_SUPER) != 0;
} }
/**
* @param attributes .
*/
public void setAttributes(final Attribute[] attributes) {
this.attributes = attributes;
}
/**
* @param className .
*/
public void setClassName(final String className) {
this.className = className;
}
/**
* @param classNameIndex .
*/
public void setClassNameIndex(final int classNameIndex) {
this.classNameIndex = classNameIndex;
}
/**
* @param constantPool .
*/
public void setConstantPool(final ConstantPool constantPool) {
this.constantPool = constantPool;
}
/**
* @param fields .
*/
public void setFields(final JavaField[] fields) {
this.fields = fields;
}
/**
* Set File name of class, aka SourceFile attribute value
*/
public void setFileName(final String fileName) {
this.fileName = fileName;
}
/**
* @param interfaceNames .
*/
public void setInterfaceNames(final String[] interfaceNames) {
this.interfaceNames = interfaceNames;
}
/**
* @param interfaces .
*/
public void setInterfaces(final int[] interfaces) {
this.interfaces = interfaces;
}
/**
* @param major .
*/
public void setMajor(final int major) {
this.major = major;
}
/**
* @param methods .
*/
public void setMethods(final JavaMethod[] methods) {
this.methods = methods;
}
/**
* @param minor .
*/
public void setMinor(final int minor) {
this.minor = minor;
}
/**
* Sets the ClassRepository which loaded the JavaClass. Should be called immediately after parsing is done.
*/
public void setRepository(final Repository repository) { // TODO make protected?
this.repository = repository;
}
/**
* Set absolute path to file this class was read from.
*/
public void setSourceFileName(final String sourceFileName) {
this.sourceFileName = sourceFileName;
}
/**
* @param superclassName .
*/
public void setSuperclassName(final String superclassName) {
this.superclassName = superclassName;
}
/**
* @param superclassNameIndex .
*/
public void setSuperclassNameIndex(final int superclassNameIndex) {
this.superclassNameIndex = superclassNameIndex;
}
/** /**
* @return String representing class contents. * @return String representing class contents.
*/ */
@@ -859,4 +876,20 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl
} }
return buf.toString(); return buf.toString();
} }
// ---------------------------------------------- haidnorJVM
/**
* 获取 main 方法
*/
public JavaMethod getMainMethod() {
for (JavaMethod javaMethod : getMethods()) {
if (javaMethod.toString().startsWith("public static void main(String[] args)")) {
return javaMethod;
}
}
return null;
}
} }

View File

@@ -28,7 +28,7 @@ import java.util.Objects;
* This class represents the field info structure, i.e., the representation for a variable in the class. See JVM * This class represents the field info structure, i.e., the representation for a variable in the class. See JVM
* specification for details. * specification for details.
*/ */
public final class JavaField extends FieldOrMethod { public class JavaField extends FieldOrMethod {
/** /**
* Empty array constant. * Empty array constant.
@@ -36,7 +36,10 @@ public final class JavaField extends FieldOrMethod {
* @since 6.6.0 * @since 6.6.0
*/ */
public static final JavaField[] EMPTY_ARRAY = {}; public static final JavaField[] EMPTY_ARRAY = {};
/**
* Empty array.
*/
static final JavaField[] EMPTY_FIELD_ARRAY = {};
private static BCELComparator bcelComparator = new BCELComparator() { private static BCELComparator bcelComparator = new BCELComparator() {
@Override @Override
@@ -52,25 +55,14 @@ public final class JavaField extends FieldOrMethod {
return THIS.getSignature().hashCode() ^ THIS.getName().hashCode(); return THIS.getSignature().hashCode() ^ THIS.getName().hashCode();
} }
}; };
/** /**
* Empty array. * 值类型
*/ */
static final JavaField[] EMPTY_FIELD_ARRAY = {}; private int valueType;
/** /**
* @return Comparison strategy object *
*/ */
public static BCELComparator getComparator() { private Object value;
return bcelComparator;
}
/**
* @param comparator Comparison strategy object
*/
public static void setComparator(final BCELComparator comparator) {
bcelComparator = comparator;
}
/** /**
* Construct object from file stream. * Construct object from file stream.
@@ -102,6 +94,20 @@ public final class JavaField extends FieldOrMethod {
super(accessFlags, nameIndex, signatureIndex, attributes, constantPool); super(accessFlags, nameIndex, signatureIndex, attributes, constantPool);
} }
/**
* @return Comparison strategy object
*/
public static BCELComparator getComparator() {
return bcelComparator;
}
/**
* @param comparator Comparison strategy object
*/
public static void setComparator(final BCELComparator comparator) {
bcelComparator = comparator;
}
/** /**
* Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
* I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.
@@ -150,6 +156,22 @@ public final class JavaField extends FieldOrMethod {
return Type.getReturnType(getSignature()); return Type.getReturnType(getSignature());
} }
public int getValueType() {
return valueType;
}
public void setValueType(int valueType) {
this.valueType = valueType;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
/** /**
* Return value as defined by given BCELComparator strategy. By default return the hashcode of the field's name XOR * Return value as defined by given BCELComparator strategy. By default return the hashcode of the field's name XOR
* signature. * signature.

View File

@@ -27,7 +27,7 @@ import java.util.Objects;
* This class represents the method info structure, i.e., the representation for a method in the class. See JVM * This class represents the method info structure, i.e., the representation for a method in the class. See JVM
* specification for details. A method has access flags, a name, a signature and a number of attributes. * specification for details. A method has access flags, a name, a signature and a number of attributes.
*/ */
public final class JavaMethod extends FieldOrMethod { public class JavaMethod extends FieldOrMethod {
/** /**
* Empty array constant. * Empty array constant.
@@ -35,7 +35,10 @@ public final class JavaMethod extends FieldOrMethod {
* @since 6.6.0 * @since 6.6.0
*/ */
public static final JavaMethod[] EMPTY_ARRAY = {}; public static final JavaMethod[] EMPTY_ARRAY = {};
/**
* Empty array.
*/
static final JavaMethod[] EMPTY_METHOD_ARRAY = {};
private static BCELComparator bcelComparator = new BCELComparator() { private static BCELComparator bcelComparator = new BCELComparator() {
@Override @Override
@@ -51,26 +54,6 @@ public final class JavaMethod extends FieldOrMethod {
return THIS.getSignature().hashCode() ^ THIS.getName().hashCode(); return THIS.getSignature().hashCode() ^ THIS.getName().hashCode();
} }
}; };
/**
* Empty array.
*/
static final JavaMethod[] EMPTY_METHOD_ARRAY = {};
/**
* @return Comparison strategy object
*/
public static BCELComparator getComparator() {
return bcelComparator;
}
/**
* @param comparator Comparison strategy object
*/
public static void setComparator(final BCELComparator comparator) {
bcelComparator = comparator;
}
// annotations defined on the parameters of a method // annotations defined on the parameters of a method
private ParameterAnnotationEntry[] parameterAnnotationEntries; private ParameterAnnotationEntry[] parameterAnnotationEntries;
@@ -112,6 +95,20 @@ public final class JavaMethod extends FieldOrMethod {
super(c); super(c);
} }
/**
* @return Comparison strategy object
*/
public static BCELComparator getComparator() {
return bcelComparator;
}
/**
* @param comparator Comparison strategy object
*/
public static void setComparator(final BCELComparator comparator) {
bcelComparator = comparator;
}
/** /**
* Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
* I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.

View File

@@ -32,10 +32,14 @@ public final class LineNumber implements Cloneable, Node {
static final LineNumber[] EMPTY_ARRAY = {}; static final LineNumber[] EMPTY_ARRAY = {};
/** Program Counter (PC) corresponds to line */ /**
* Program Counter (PC) corresponds to line
*/
private int startPc; private int startPc;
/** number in source file */ /**
* number in source file
*/
private int lineNumber; private int lineNumber;
/** /**
@@ -107,13 +111,6 @@ public final class LineNumber implements Cloneable, Node {
return lineNumber & 0xffff; return lineNumber & 0xffff;
} }
/**
* @return PC in code
*/
public int getStartPC() {
return startPc & 0xffff;
}
/** /**
* @param lineNumber the source line number * @param lineNumber the source line number
*/ */
@@ -121,6 +118,13 @@ public final class LineNumber implements Cloneable, Node {
this.lineNumber = (short) lineNumber; this.lineNumber = (short) lineNumber;
} }
/**
* @return PC in code
*/
public int getStartPC() {
return startPc & 0xffff;
}
/** /**
* @param startPc the pc for this line number * @param startPc the pc for this line number
*/ */

View File

@@ -126,6 +126,13 @@ public final class LineNumberTable extends Attribute implements Iterable<LineNum
return lineNumberTable; return lineNumberTable;
} }
/**
* @param lineNumberTable the line number entries for this table
*/
public void setLineNumberTable(final LineNumber[] lineNumberTable) {
this.lineNumberTable = lineNumberTable;
}
/** /**
* Map byte code positions to source code lines. * Map byte code positions to source code lines.
* *
@@ -181,13 +188,6 @@ public final class LineNumberTable extends Attribute implements Iterable<LineNum
return Stream.of(lineNumberTable).iterator(); return Stream.of(lineNumberTable).iterator();
} }
/**
* @param lineNumberTable the line number entries for this table
*/
public void setLineNumberTable(final LineNumber[] lineNumberTable) {
this.lineNumberTable = lineNumberTable;
}
/** /**
* @return String representation. * @return String representation.
*/ */

View File

@@ -36,35 +36,28 @@ import java.io.IOException;
public final class LocalVariable implements Cloneable, Node { public final class LocalVariable implements Cloneable, Node {
static final LocalVariable[] EMPTY_ARRAY = {}; static final LocalVariable[] EMPTY_ARRAY = {};
/**
* Range in which the variable is valid.
*/
private int startPc;
private int length;
/**
* Index in constant pool of variable name.
*/
private int nameIndex;
/**
* Technically, a decscriptor_index for a local variable table entry and a signatureIndex for a local variable type table entry. Index of variable signature
*/
private int signatureIndex;
/*
* Variable is index'th local variable on this method's frame.
*/
private int index;
private ConstantPool constantPool;
/** /**
* Never changes; used to match up with LocalVariableTypeTable entries. * Never changes; used to match up with LocalVariableTypeTable entries.
*/ */
private final int origIndex; private final int origIndex;
/**
* Range in which the variable is valid.
*/
private int startPc;
private int length;
/**
* Index in constant pool of variable name.
*/
private int nameIndex;
/**
* Technically, a decscriptor_index for a local variable table entry and a signatureIndex for a local variable type table entry. Index of variable signature
*/
private int signatureIndex;
/*
* Variable is index'th local variable on this method's frame.
*/
private int index;
private ConstantPool constantPool;
/** /**
* Constructs object from file stream. * Constructs object from file stream.
@@ -164,6 +157,13 @@ public final class LocalVariable implements Cloneable, Node {
return constantPool; return constantPool;
} }
/**
* @param constantPool Constant pool to be used for this object.
*/
public void setConstantPool(final ConstantPool constantPool) {
this.constantPool = constantPool;
}
/** /**
* @return index of register where variable is stored * @return index of register where variable is stored
*/ */
@@ -171,6 +171,13 @@ public final class LocalVariable implements Cloneable, Node {
return index; return index;
} }
/**
* @param index the index in the local variable table of this variable
*/
public void setIndex(final int index) { // TODO unused
this.index = index;
}
/** /**
* @return Variable is valid within getStartPC() .. getStartPC()+getLength() * @return Variable is valid within getStartPC() .. getStartPC()+getLength()
*/ */
@@ -178,6 +185,13 @@ public final class LocalVariable implements Cloneable, Node {
return length; return length;
} }
/**
* @param length the length of this local variable
*/
public void setLength(final int length) {
this.length = length;
}
/** /**
* @return Variable name. * @return Variable name.
*/ */
@@ -192,6 +206,13 @@ public final class LocalVariable implements Cloneable, Node {
return nameIndex; return nameIndex;
} }
/**
* @param nameIndex the index into the constant pool for the name of this variable
*/
public void setNameIndex(final int nameIndex) { // TODO unused
this.nameIndex = nameIndex;
}
/** /**
* @return index of register where variable was originally stored * @return index of register where variable was originally stored
*/ */
@@ -213,41 +234,6 @@ public final class LocalVariable implements Cloneable, Node {
return signatureIndex; return signatureIndex;
} }
/**
* @return Start of range where the variable is valid
*/
public int getStartPC() {
return startPc;
}
/**
* @param constantPool Constant pool to be used for this object.
*/
public void setConstantPool(final ConstantPool constantPool) {
this.constantPool = constantPool;
}
/**
* @param index the index in the local variable table of this variable
*/
public void setIndex(final int index) { // TODO unused
this.index = index;
}
/**
* @param length the length of this local variable
*/
public void setLength(final int length) {
this.length = length;
}
/**
* @param nameIndex the index into the constant pool for the name of this variable
*/
public void setNameIndex(final int nameIndex) { // TODO unused
this.nameIndex = nameIndex;
}
/** /**
* @param signatureIndex the index into the constant pool for the signature of this variable * @param signatureIndex the index into the constant pool for the signature of this variable
*/ */
@@ -255,6 +241,13 @@ public final class LocalVariable implements Cloneable, Node {
this.signatureIndex = signatureIndex; this.signatureIndex = signatureIndex;
} }
/**
* @return Start of range where the variable is valid
*/
public int getStartPC() {
return startPc;
}
/** /**
* @param startPc Specify range where the local variable is valid. * @param startPc Specify range where the local variable is valid.
*/ */

View File

@@ -116,11 +116,8 @@ public class LocalVariableTable extends Attribute implements Iterable<LocalVaria
} }
/** /**
*
* @param index the variable slot * @param index the variable slot
*
* @return the first LocalVariable that matches the slot or null if not found * @return the first LocalVariable that matches the slot or null if not found
*
* @deprecated since 5.2 because multiple variables can share the same slot, use getLocalVariable(int index, int pc) * @deprecated since 5.2 because multiple variables can share the same slot, use getLocalVariable(int index, int pc)
* instead. * instead.
*/ */
@@ -135,10 +132,8 @@ public class LocalVariableTable extends Attribute implements Iterable<LocalVaria
} }
/** /**
*
* @param index the variable slot * @param index the variable slot
* @param pc the current pc that this variable is alive * @param pc the current pc that this variable is alive
*
* @return the LocalVariable that matches or null if not found * @return the LocalVariable that matches or null if not found
*/ */
public final LocalVariable getLocalVariable(final int index, final int pc) { public final LocalVariable getLocalVariable(final int index, final int pc) {
@@ -161,6 +156,10 @@ public class LocalVariableTable extends Attribute implements Iterable<LocalVaria
return localVariableTable; return localVariableTable;
} }
public final void setLocalVariableTable(final LocalVariable[] localVariableTable) {
this.localVariableTable = localVariableTable;
}
public final int getTableLength() { public final int getTableLength() {
return localVariableTable == null ? 0 : localVariableTable.length; return localVariableTable == null ? 0 : localVariableTable.length;
} }
@@ -170,10 +169,6 @@ public class LocalVariableTable extends Attribute implements Iterable<LocalVaria
return Stream.of(localVariableTable).iterator(); return Stream.of(localVariableTable).iterator();
} }
public final void setLocalVariableTable(final LocalVariable[] localVariableTable) {
this.localVariableTable = localVariableTable;
}
/** /**
* @return String representation. * @return String representation.
*/ */

View File

@@ -5,9 +5,9 @@
* The ASF licenses this file to You under the Apache License, Version 2.0 * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* * <p>
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* * <p>
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

@@ -32,10 +32,14 @@ import java.io.IOException;
*/ */
public class MethodParameter implements Cloneable, Node { public class MethodParameter implements Cloneable, Node {
/** Index of the CONSTANT_Utf8_info structure in the constant_pool table representing the name of the parameter */ /**
* Index of the CONSTANT_Utf8_info structure in the constant_pool table representing the name of the parameter
*/
private int nameIndex; private int nameIndex;
/** The access flags */ /**
* The access flags
*/
private int accessFlags; private int accessFlags;
public MethodParameter() { public MethodParameter() {
@@ -85,10 +89,18 @@ public class MethodParameter implements Cloneable, Node {
return accessFlags; return accessFlags;
} }
public void setAccessFlags(final int accessFlags) {
this.accessFlags = accessFlags;
}
public int getNameIndex() { public int getNameIndex() {
return nameIndex; return nameIndex;
} }
public void setNameIndex(final int nameIndex) {
this.nameIndex = nameIndex;
}
/** /**
* Returns the name of the parameter. * Returns the name of the parameter.
*/ */
@@ -110,12 +122,4 @@ public class MethodParameter implements Cloneable, Node {
public boolean isSynthetic() { public boolean isSynthetic() {
return (accessFlags & Const.ACC_SYNTHETIC) != 0; return (accessFlags & Const.ACC_SYNTHETIC) != 0;
} }
public void setAccessFlags(final int accessFlags) {
this.accessFlags = accessFlags;
}
public void setNameIndex(final int nameIndex) {
this.nameIndex = nameIndex;
}
} }

View File

@@ -86,12 +86,12 @@ public class MethodParameters extends Attribute implements Iterable<MethodParame
return parameters; return parameters;
} }
public void setParameters(final MethodParameter[] parameters) {
this.parameters = parameters;
}
@Override @Override
public Iterator<MethodParameter> iterator() { public Iterator<MethodParameter> iterator() {
return Stream.of(parameters).iterator(); return Stream.of(parameters).iterator();
} }
public void setParameters(final MethodParameter[] parameters) {
this.parameters = parameters;
}
} }

View File

@@ -43,12 +43,11 @@ public final class Module extends Attribute {
private final int moduleNameIndex; private final int moduleNameIndex;
private final int moduleFlags; private final int moduleFlags;
private final int moduleVersionIndex; private final int moduleVersionIndex;
private final int usesCount;
private final int[] usesIndex;
private ModuleRequires[] requiresTable; private ModuleRequires[] requiresTable;
private ModuleExports[] exportsTable; private ModuleExports[] exportsTable;
private ModuleOpens[] opensTable; private ModuleOpens[] opensTable;
private final int usesCount;
private final int[] usesIndex;
private ModuleProvides[] providesTable; private ModuleProvides[] providesTable;
/** /**

View File

@@ -129,6 +129,13 @@ public final class ModulePackages extends Attribute {
return packageIndexTable; return packageIndexTable;
} }
/**
* @param packageIndexTable the list of package indexes Also redefines number_of_packages according to table length.
*/
public void setPackageIndexTable(final int[] packageIndexTable) {
this.packageIndexTable = packageIndexTable != null ? packageIndexTable : ArrayUtils.EMPTY_INT_ARRAY;
}
/** /**
* @return string array of package names * @return string array of package names
*/ */
@@ -138,13 +145,6 @@ public final class ModulePackages extends Attribute {
return names; return names;
} }
/**
* @param packageIndexTable the list of package indexes Also redefines number_of_packages according to table length.
*/
public void setPackageIndexTable(final int[] packageIndexTable) {
this.packageIndexTable = packageIndexTable != null ? packageIndexTable : ArrayUtils.EMPTY_INT_ARRAY;
}
/** /**
* @return String representation, i.e., a list of packages. * @return String representation, i.e., a list of packages.
*/ */

View File

@@ -123,6 +123,13 @@ public final class NestMembers extends Attribute {
return classes; return classes;
} }
/**
* @param classes the list of class indexes Also redefines number_of_classes according to table length.
*/
public void setClasses(final int[] classes) {
this.classes = classes != null ? classes : ArrayUtils.EMPTY_INT_ARRAY;
}
/** /**
* @return string array of class names * @return string array of class names
*/ */
@@ -139,13 +146,6 @@ public final class NestMembers extends Attribute {
return classes.length; return classes.length;
} }
/**
* @param classes the list of class indexes Also redefines number_of_classes according to table length.
*/
public void setClasses(final int[] classes) {
this.classes = classes != null ? classes : ArrayUtils.EMPTY_INT_ARRAY;
}
/** /**
* @return String representation, i.e., a list of classes. * @return String representation, i.e., a list of classes.
*/ */

View File

@@ -107,6 +107,13 @@ public final class PMGClass extends Attribute {
return pmgClassIndex; return pmgClassIndex;
} }
/**
* @param pmgClassIndex
*/
public void setPMGClassIndex(final int pmgClassIndex) {
this.pmgClassIndex = pmgClassIndex;
}
/** /**
* @return PMG class name. * @return PMG class name.
*/ */
@@ -121,20 +128,6 @@ public final class PMGClass extends Attribute {
return pmgIndex; return pmgIndex;
} }
/**
* @return PMG name.
*/
public String getPMGName() {
return super.getConstantPool().getConstantUtf8(pmgIndex).getBytes();
}
/**
* @param pmgClassIndex
*/
public void setPMGClassIndex(final int pmgClassIndex) {
this.pmgClassIndex = pmgClassIndex;
}
/** /**
* @param pmgIndex * @param pmgIndex
*/ */
@@ -142,6 +135,13 @@ public final class PMGClass extends Attribute {
this.pmgIndex = pmgIndex; this.pmgIndex = pmgIndex;
} }
/**
* @return PMG name.
*/
public String getPMGName() {
return super.getConstantPool().getConstantUtf8(pmgIndex).getBytes();
}
/** /**
* @return String representation * @return String representation
*/ */

View File

@@ -31,19 +31,6 @@ import java.util.List;
public class ParameterAnnotationEntry implements Node { public class ParameterAnnotationEntry implements Node {
static final ParameterAnnotationEntry[] EMPTY_ARRAY = {}; static final ParameterAnnotationEntry[] EMPTY_ARRAY = {};
public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final Attribute[] attrs) {
// Find attributes that contain parameter annotation data
final List<ParameterAnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length);
for (final Attribute attribute : attrs) {
if (attribute instanceof ParameterAnnotations) {
final ParameterAnnotations runtimeAnnotations = (ParameterAnnotations) attribute;
Collections.addAll(accumulatedAnnotations, runtimeAnnotations.getParameterAnnotationEntries());
}
}
return accumulatedAnnotations.toArray(ParameterAnnotationEntry.EMPTY_ARRAY);
}
private final AnnotationEntry[] annotationTable; private final AnnotationEntry[] annotationTable;
/** /**
@@ -61,6 +48,18 @@ public class ParameterAnnotationEntry implements Node {
} }
} }
public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final Attribute[] attrs) {
// Find attributes that contain parameter annotation data
final List<ParameterAnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length);
for (final Attribute attribute : attrs) {
if (attribute instanceof ParameterAnnotations) {
final ParameterAnnotations runtimeAnnotations = (ParameterAnnotations) attribute;
Collections.addAll(accumulatedAnnotations, runtimeAnnotations.getParameterAnnotationEntries());
}
}
return accumulatedAnnotations.toArray(ParameterAnnotationEntry.EMPTY_ARRAY);
}
/** /**
* Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
* I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.

Some files were not shown because too many files have changed in this diff Show More