/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. 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 obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.bcel.classfile;
import java.io.DataInput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.bcel.Const;
import org.apache.bcel.util.Args;
import org.apache.commons.lang3.ArrayUtils;
/**
* 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 information about operand stack, local
* variables, byte code and the exceptions handled within this method.
*
* 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.
*
* <pre>
* Code_attribute {
* u2 attribute_name_index;
* u4 attribute_length;
* u2 max_stack;
* u2 max_locals;
* u4 code_length;
* u1 code[code_length];
* u2 exception_table_length;
* {
* u2 start_pc;
* u2 end_pc;
* u2 handler_pc;
* u2 catch_type;
* } exception_table[exception_table_length];
* u2 attributes_count;
* attribute_info attributes[attributes_count];
* }
* </pre>
*
* <p>
* The layout above uses the standard Code header. This class also supports compact Code headers found in historical class file versions 45.0 through 45.2.
* Here, "compact" describes the narrower encoding of three fields: {@code max_stack} and {@code max_locals} each use {@code u1}, and {@code code_length}
* uses {@code u2}, instead of {@code u2}, {@code u2}, and {@code u4}, respectively. The notation {@code u1}, {@code u2}, and {@code u4} denotes unsigned
* one-, two-, and four-byte values. These three fields therefore occupy 4 bytes instead of 8, excluding the common six-byte attribute prefix.
* The layout of that prefix and the remaining Code fields is unchanged; the bytecode itself is not compressed.
* {@link #isCompactCodeHeader()} identifies this narrower layout.
* </p>
*
* <p>
* Class file versions 45.0 through 45.2 also occur with standard Code headers accepted by modern JVMs, so the version alone does not identify the layout.
* {@link ClassParser} uses standard headers by default; {@link ClassParser#setCompactCodeHeaderEnabled(boolean)} explicitly selects compact headers
* for those versions.
* </p>
*
* @see Attribute
* @see CodeException
* @see LineNumberTable
* @see LocalVariableTable
*/
public final class Code extends Attribute {
/**
* Whether {@code max_stack}, {@code max_locals}, and {@code code_length} use {@code u1/u1/u2} (4 bytes) instead of {@code u2/u2/u4} (8 bytes).
* Compact describes these field widths, not compression of the bytecode or the rest of the attribute.
*/
private boolean compactCodeHeader;
private int maxStack; // Maximum size of stack used by this method // TODO this could be made final (setter is not used)
private int maxLocals; // Number of local variables // TODO this could be made final (setter is not used)
private byte[] code; // Actual byte code
private CodeException[] exceptionTable; // Table of handled exceptions
private Attribute[] attributes; // or LocalVariable
/**
* Initialize from another object. Note that both objects use the same references (shallow copy). Use copy() for a
* physical copy.
*
* @param code The source Code.
*/
public Code(final Code code) {
this(code.getNameIndex(), code.getLength(), code.getMaxStack(), code.getMaxLocals(), code.getCode(), code.getExceptionTable(), code.getAttributes(), code.getConstantPool(), code.compactCodeHeader); }
/**
* Constructs a Code attribute object from a DataInput.
*
* @param nameIndex Index pointing to the name <em>Code</em>.
* @param length Content length in bytes.
* @param dataInput Data input.
* @param constantPool Array of constants.
* @throws ClassFormatException Thrown if the code array read from {@code file} is greater than {@link Const#MAX_CODE_SIZE}.
*/
Code(final int nameIndex, final int length, final DataInput dataInput, final ConstantPool constantPool) throws IOException {
this(nameIndex, length, dataInput, constantPool, false); }
/**
* Reads a Code attribute using the selected header layout.
*/
Code(final int nameIndex, final int length, final DataInput dataInput, final ConstantPool constantPool, final boolean compactCodeHeader) throws IOException {
// Compact headers encode max_stack/max_locals/code_length as u1/u1/u2; standard headers use u2/u2/u4.
// Initialize the remaining fields with default values, then read them below.
this(nameIndex, length, compactCodeHeader ? dataInput.readUnsignedByte() : dataInput.readUnsignedShort(), compactCodeHeader ? dataInput.readUnsignedByte() : dataInput.readUnsignedShort(), null, null, null, constantPool, compactCodeHeader); final int codeLength = Args.requireU4(compactCodeHeader ? dataInput.readUnsignedShort() : dataInput.readInt(), 0, Const.MAX_CODE_SIZE,
"Code length attribute");
code = new byte[codeLength]; // Read byte code dataInput.readFully(code);
/*
* Read exception table that contains all regions where an exception handler is active, that is, a try { ... } catch () block.
*/
final int exceptionTableLength = dataInput.readUnsignedShort(); exceptionTable = new CodeException[exceptionTableLength]; for (int i = 0; i < exceptionTableLength; i++) { exceptionTable[i] = new CodeException(dataInput);
}
/*
* Read all attributes, currently 'LineNumberTable' and 'LocalVariableTable'
*/
final int attributesCount = dataInput.readUnsignedShort(); attributes = new Attribute[attributesCount]; for (int i = 0; i < attributesCount; i++) { attributes[i] = readAttribute(dataInput, constantPool, compactCodeHeader);
}
/*
* Adjust length, because of setAttributes in this(), s.b. length is incorrect, because it didn't take the internal attributes into account yet! Very
* subtle bug, fixed in 3.1.1.
*/
super.setLength(length); }
/**
* Constructs a Code attribute using a standard eight-byte header.
*
* <p>
* Use {@link #setCompactCodeHeader(boolean)} to select the compact four-byte header after construction.
* </p>
*
* @param nameIndex Index pointing to the name <em>Code</em>.
* @param length Content length in bytes.
* @param maxStack Maximum size of stack.
* @param maxLocals Number of local variables.
* @param code Actual byte code.
* @param exceptionTable of handled exceptions.
* @param attributes Attributes of code: LineNumber or LocalVariable.
* @param constantPool Array of constants.
* @throws ClassFormatException Thrown if the code array is greater than {@link Const#MAX_CODE_SIZE}.
*/
public Code(final int nameIndex, final int length, final int maxStack, final int maxLocals, final byte[] code, final CodeException[] exceptionTable,
final Attribute[] attributes, final ConstantPool constantPool) {
this(nameIndex, length, maxStack, maxLocals, code, exceptionTable, attributes, constantPool, false); }
private Code(final int nameIndex, final int length, final int maxStack, final int maxLocals, final byte[] code, final CodeException[] exceptionTable,
final Attribute[] attributes, final ConstantPool constantPool, final boolean compactCodeHeader) {
super(Const.ATTR_CODE, nameIndex, length, constantPool); this.compactCodeHeader = compactCodeHeader; this.maxStack = Args.requireU2(maxStack, "maxStack"); this.maxLocals = Args.requireU2(maxLocals, "maxLocals"); this.code = ArrayUtils.nullToEmpty(code); Args.requireU4(this.code.length, 0, Const.MAX_CODE_SIZE, "Code length attribute"); this.exceptionTable = ArrayUtils.nullToEmpty(exceptionTable, CodeException[].class); Args.requireU2(this.exceptionTable.length, "exceptionTable.length"); this.attributes = attributes != null ? attributes : EMPTY_ARRAY; super.setLength(calculateLength()); // Adjust length }
/**
* Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
* That is, the hierarchy of methods, fields, attributes, and other elements forms a tree of objects.
*
* @param v Visitor object.
*/
@Override
public void accept(final Visitor v) {
v.visitCode(this); }
/**
* @return The full size of this code attribute, minus its first 6 bytes, including the size of all its contained attributes.
*/
private int calculateLength() {
int len = 0; if (attributes != null) { for (final Attribute attribute : attributes) { len += attribute.getLength() + 6 /* attribute header size */;
}
}
return len + getInternalLength();
}
/**
* Creates a deep copy of this attribute.
*
* @param constantPool The constant pool to duplicate.
* @return deep copy of this attribute.
*/
@Override
public Attribute copy(final ConstantPool constantPool) {
final Code c = (Code) clone(); if (code != null) { c.code = code.clone();
}
c.setConstantPool(constantPool); c.exceptionTable = new CodeException[exceptionTable.length]; Arrays.setAll(c.exceptionTable, i -> exceptionTable[i].copy()); c.attributes = new Attribute[attributes.length]; Arrays.setAll(c.attributes, i -> attributes[i].copy(constantPool)); return c;
}
/**
* Dumps code attribute to file stream in binary format.
*
* @param file Output file stream.
* @throws IOException Thrown if an I/O error occurs.
* @throws ClassFormatException Thrown if a compact header's {@code max_stack} or {@code max_locals} is outside 0 through 255,
* or its code length exceeds 65535 bytes.
*/
@Override
public void dump(final DataOutputStream file) throws IOException {
if (compactCodeHeader) { Args.requireU1(maxStack, "maxStack"); Args.requireU1(maxLocals, "maxLocals"); Args.requireU2(code.length, "Code length attribute");
}
super.dump(file); if (compactCodeHeader) { file.writeByte(maxStack); file.writeByte(maxLocals); file.writeShort(code.length);
} else {
file.writeShort(maxStack); file.writeShort(maxLocals); file.writeInt(code.length);
}
file.write(code, 0, code.length); file.writeShort(Args.requireU2(exceptionTable.length, "exceptionTable.length")); for (final CodeException exception : exceptionTable) { exception.dump(file);
}
file.writeShort(Args.requireU2(attributes.length, "attributes.length")); for (final Attribute attribute : attributes) { attribute.dump(file);
}
}
/**
* Gets the collection of code attributes.
*
* @return Collection of code attributes.
* @see Attribute
*/
public Attribute[] getAttributes() {
return attributes;
}
/**
* Gets the actual byte code of the method.
*
* @return Actual byte code of the method.
*/
public byte[] getCode() {
return code;
}
/**
* Gets the table of handled exceptions.
*
* @return Table of handled exceptions.
* @see CodeException
*/
public CodeException[] getExceptionTable() {
return exceptionTable;
}
/**
* Gets 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.
*/
private int getInternalLength() {
// Only max_stack, max_locals, and code_length differ: 1 + 1 + 2 compact bytes versus 2 + 2 + 4 standard bytes.
return (compactCodeHeader ? 4 : 8)
+ code.length /* byte-code */
+ 2 /* exception-table length */
+ 8 * (exceptionTable == null ? 0 : exceptionTable.length) /* exception table */
+ 2 /* attributes count */;
}
/**
* Gets the LineNumberTable of Code, if it has one.
*
* @return LineNumberTable of Code, if it has one.
*/
public LineNumberTable getLineNumberTable() {
for (final Attribute attribute : attributes) { if (attribute instanceof LineNumberTable) { return (LineNumberTable) attribute;
}
}
return null;
}
/**
* Gets the LocalVariableTable of Code, if it has one.
*
* @return LocalVariableTable of Code, if it has one.
*/
public LocalVariableTable getLocalVariableTable() {
for (final Attribute attribute : attributes) { if (attribute instanceof LocalVariableTable) { return (LocalVariableTable) attribute;
}
}
return null;
}
/**
* Gets the local variable type table attribute {@link LocalVariableTypeTable}.
*
* @return LocalVariableTypeTable of Code, if it has one, null otherwise.
* @since 6.10.0
*/
public LocalVariableTypeTable getLocalVariableTypeTable() {
for (final Attribute attribute : attributes) { if (attribute instanceof LocalVariableTypeTable) { return (LocalVariableTypeTable) attribute;
}
}
return null;
}
/**
* Gets the number of local variables.
*
* @return Number of local variables.
*/
public int getMaxLocals() {
return maxLocals;
}
/**
* Gets the maximum size of stack used by this method.
*
* @return Maximum size of stack used by this method.
*/
public int getMaxStack() {
return maxStack;
}
/**
* Gets the {@link StackMap} attribute.
*
* @return StackMap of Code, if it has one, else null.
* @since 6.8.0
*/
public StackMap getStackMap() {
for (final Attribute attribute : attributes) { if (attribute instanceof StackMap) { return (StackMap) attribute;
}
}
return null;
}
/**
* Gets whether this attribute uses the compact four-byte Code header.
*
* @return Whether {@code max_stack}, {@code max_locals}, and {@code code_length} use {@code u1}, {@code u1}, and {@code u2}, respectively,
* instead of the standard {@code u2}, {@code u2}, and {@code u4}.
* @since 6.14.0
* @see #setCompactCodeHeader(boolean)
*/
public boolean isCompactCodeHeader() {
return compactCodeHeader;
}
/**
* Sets the attributes for this Code.
*
* @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 }
/**
* Sets the byte code.
*
* @param code byte code.
* @throws ClassFormatException Thrown if the code array is greater than {@link Const#MAX_CODE_SIZE}.
*/
public void setCode(final byte[] code) {
this.code = ArrayUtils.nullToEmpty(code); Args.requireU4(this.code.length, 0, Const.MAX_CODE_SIZE, "Code length attribute"); super.setLength(calculateLength()); // Adjust length }
/**
* Sets the Code header layout and recalculates the attribute length.
*
* <p>
* Compact headers encode {@code max_stack}, {@code max_locals}, and {@code code_length} as {@code u1}, {@code u1}, and {@code u2}, respectively,
* totaling 4 bytes instead of the standard 8. This limits {@code max_stack} and {@code max_locals} to 0 through 255 and the code length to 65535 bytes.
* The remaining attribute layout is unchanged. Compact headers are intended for historical class file versions 45.0 through 45.2.
* Enabling compact headers validates these values before changing the layout. Subsequent changes to them are checked by {@link #dump(DataOutputStream)}.
* </p>
*
* <p>
* This setting controls this attribute's own dump. When dumping an entire class, {@link JavaClass#dump(DataOutputStream)} selects one layout for
* all method Code attributes based on the class version and the methods' header settings, without changing this attribute's setting.
* </p>
*
* @param compactCodeHeader Whether to use a compact four-byte header ({@code true}) or a standard eight-byte header ({@code false}).
* @throws ClassFormatException Thrown if {@code compactCodeHeader} is {@code true} and the current values do not fit in a compact header.
* @since 6.14.0
*/
public void setCompactCodeHeader(final boolean compactCodeHeader) {
if (compactCodeHeader) { Args.requireU1(maxStack, "maxStack"); Args.requireU1(maxLocals, "maxLocals"); Args.requireU2(code.length, "Code length attribute");
}
this.compactCodeHeader = compactCodeHeader; super.setLength(calculateLength()); }
/**
* Sets the exception table.
*
* @param exceptionTable exception table.
*/
public void setExceptionTable(final CodeException[] exceptionTable) {
this.exceptionTable = exceptionTable != null ? exceptionTable : CodeException.EMPTY_ARRAY; Args.requireU2(this.exceptionTable.length, "exceptionTable.length"); super.setLength(calculateLength()); // Adjust length }
/**
* Sets the maximum number of local variables.
*
* @param maxLocals maximum number of local variables.
*/
public void setMaxLocals(final int maxLocals) {
this.maxLocals = maxLocals; }
/**
* Sets the maximum stack size.
*
* @param maxStack maximum stack size.
*/
public void setMaxStack(final int maxStack) {
this.maxStack = maxStack; }
/**
* @return String representation of code chunk.
*/
@Override
public String toString() {
return toString(true);
}
/**
* Converts this object to a String.
*
* @param verbose Provides verbose output when true.
* @return String representation of code chunk.
*/
public String toString(final boolean verbose) {
final StringBuilder buf = new StringBuilder(100); // CHECKSTYLE IGNORE MagicNumber buf.append("Code(maxStack = ").append(maxStack).append(", maxLocals = ").append(maxLocals).append(", code_length = ").append(code.length).append(")\n") .append(Utility.codeToString(code, super.getConstantPool(), 0, -1, verbose)); if (exceptionTable.length > 0) { buf.append("\nException handler(s) = \n").append("From\tTo\tHandler\tType\n"); for (final CodeException exception : exceptionTable) { buf.append(exception.toString(super.getConstantPool(), verbose)).append("\n");
}
}
if (attributes.length > 0) { buf.append("\nAttribute(s) = "); for (final Attribute attribute : attributes) { buf.append("\n").append(attribute.getName()).append(":"); buf.append("\n").append(attribute);
}
}
return buf.toString();
}
}