repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/Constants.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/**
* This interface defines a bunch of constants from the JVM spec. It also defines some constants we
* need for other purposes.
*
* <p>Here are the JVM constants:
*
* <ul>
* <li>The OP_ constants define the JVM instruction opcodes.
* <li>The ACC_ constants define the accessibility flags for classes, fields and methods.
* <li>The CONSTANT_ constants define the constant pool item types.
* <li>The T_ constants define the types of arrays that can be created by OP_newarray.
* <li>The TYPE_ constants define the string representations of various JVM types. Two special
* non-JVM types are defined, TYPE_null and TYPE_unknown, as noted below.
* </ul>
*
* Non-JVM constants:
*
* <ul>
* <li>The OPR_ constants define the set of operators present in JVM instructions.
* <li>The operatorNames array gives the string names of those operators.
* <li>The TYPE_..._index constants define numeric representations of the JVM base types.
* <li>The indexedTypes array maps those numeric representations to their official string
* representations.
* <li>The indexedTypes_T array maps those numeric representations to the corresponding T_
* constant.
* </ul>
*/
public interface Constants {
short OP_nop = 0;
short OP_aconst_null = 1;
short OP_iconst_m1 = 2;
short OP_iconst_0 = 3;
short OP_iconst_1 = 4;
short OP_iconst_2 = 5;
short OP_iconst_3 = 6;
short OP_iconst_4 = 7;
short OP_iconst_5 = 8;
short OP_lconst_0 = 9;
short OP_lconst_1 = 10;
short OP_fconst_0 = 11;
short OP_fconst_1 = 12;
short OP_fconst_2 = 13;
short OP_dconst_0 = 14;
short OP_dconst_1 = 15;
short OP_bipush = 16;
short OP_sipush = 17;
short OP_ldc = 18;
short OP_ldc_w = 19;
short OP_ldc2_w = 20;
short OP_iload = 21;
short OP_lload = 22;
short OP_fload = 23;
short OP_dload = 24;
short OP_aload = 25;
short OP_iload_0 = 26;
short OP_iload_1 = 27;
short OP_iload_2 = 28;
short OP_iload_3 = 29;
short OP_lload_0 = 30;
short OP_lload_1 = 31;
short OP_lload_2 = 32;
short OP_lload_3 = 33;
short OP_fload_0 = 34;
short OP_fload_1 = 35;
short OP_fload_2 = 36;
short OP_fload_3 = 37;
short OP_dload_0 = 38;
short OP_dload_1 = 39;
short OP_dload_2 = 40;
short OP_dload_3 = 41;
short OP_aload_0 = 42;
short OP_aload_1 = 43;
short OP_aload_2 = 44;
short OP_aload_3 = 45;
short OP_iaload = 46;
short OP_laload = 47;
short OP_faload = 48;
short OP_daload = 49;
short OP_aaload = 50;
short OP_baload = 51;
short OP_caload = 52;
short OP_saload = 53;
short OP_istore = 54;
short OP_lstore = 55;
short OP_fstore = 56;
short OP_dstore = 57;
short OP_astore = 58;
short OP_istore_0 = 59;
short OP_istore_1 = 60;
short OP_istore_2 = 61;
short OP_istore_3 = 62;
short OP_lstore_0 = 63;
short OP_lstore_1 = 64;
short OP_lstore_2 = 65;
short OP_lstore_3 = 66;
short OP_fstore_0 = 67;
short OP_fstore_1 = 68;
short OP_fstore_2 = 69;
short OP_fstore_3 = 70;
short OP_dstore_0 = 71;
short OP_dstore_1 = 72;
short OP_dstore_2 = 73;
short OP_dstore_3 = 74;
short OP_astore_0 = 75;
short OP_astore_1 = 76;
short OP_astore_2 = 77;
short OP_astore_3 = 78;
short OP_iastore = 79;
short OP_lastore = 80;
short OP_fastore = 81;
short OP_dastore = 82;
short OP_aastore = 83;
short OP_bastore = 84;
short OP_castore = 85;
short OP_sastore = 86;
short OP_pop = 87;
short OP_pop2 = 88;
short OP_dup = 89;
short OP_dup_x1 = 90;
short OP_dup_x2 = 91;
short OP_dup2 = 92;
short OP_dup2_x1 = 93;
short OP_dup2_x2 = 94;
short OP_swap = 95;
short OP_iadd = 96;
short OP_ladd = 97;
short OP_fadd = 98;
short OP_dadd = 99;
short OP_isub = 100;
short OP_lsub = 101;
short OP_fsub = 102;
short OP_dsub = 103;
short OP_imul = 104;
short OP_lmul = 105;
short OP_fmul = 106;
short OP_dmul = 107;
short OP_idiv = 108;
short OP_ldiv = 109;
short OP_fdiv = 110;
short OP_ddiv = 111;
short OP_irem = 112;
short OP_lrem = 113;
short OP_frem = 114;
short OP_drem = 115;
short OP_ineg = 116;
short OP_lneg = 117;
short OP_fneg = 118;
short OP_dneg = 119;
short OP_ishl = 120;
short OP_lshl = 121;
short OP_ishr = 122;
short OP_lshr = 123;
short OP_iushr = 124;
short OP_lushr = 125;
short OP_iand = 126;
short OP_land = 127;
short OP_ior = 128;
short OP_lor = 129;
short OP_ixor = 130;
short OP_lxor = 131;
short OP_iinc = 132;
short OP_i2l = 133;
short OP_i2f = 134;
short OP_i2d = 135;
short OP_l2i = 136;
short OP_l2f = 137;
short OP_l2d = 138;
short OP_f2i = 139;
short OP_f2l = 140;
short OP_f2d = 141;
short OP_d2i = 142;
short OP_d2l = 143;
short OP_d2f = 144;
short OP_i2b = 145;
short OP_i2c = 146;
short OP_i2s = 147;
short OP_lcmp = 148;
short OP_fcmpl = 149;
short OP_fcmpg = 150;
short OP_dcmpl = 151;
short OP_dcmpg = 152;
short OP_ifeq = 153;
short OP_ifne = 154;
short OP_iflt = 155;
short OP_ifge = 156;
short OP_ifgt = 157;
short OP_ifle = 158;
short OP_if_icmpeq = 159;
short OP_if_icmpne = 160;
short OP_if_icmplt = 161;
short OP_if_icmpge = 162;
short OP_if_icmpgt = 163;
short OP_if_icmple = 164;
short OP_if_acmpeq = 165;
short OP_if_acmpne = 166;
short OP_goto = 167;
short OP_jsr = 168;
short OP_ret = 169;
short OP_tableswitch = 170;
short OP_lookupswitch = 171;
short OP_ireturn = 172;
short OP_lreturn = 173;
short OP_freturn = 174;
short OP_dreturn = 175;
short OP_areturn = 176;
short OP_return = 177;
short OP_getstatic = 178;
short OP_putstatic = 179;
short OP_getfield = 180;
short OP_putfield = 181;
short OP_invokevirtual = 182;
short OP_invokespecial = 183;
short OP_invokestatic = 184;
short OP_invokeinterface = 185;
short OP_invokedynamic = 186;
short OP_new = 187;
short OP_newarray = 188;
short OP_anewarray = 189;
short OP_arraylength = 190;
short OP_athrow = 191;
short OP_checkcast = 192;
short OP_instanceof = 193;
short OP_monitorenter = 194;
short OP_monitorexit = 195;
short OP_wide = 196;
short OP_multianewarray = 197;
short OP_ifnull = 198;
short OP_ifnonnull = 199;
short OP_goto_w = 200;
short OP_jsr_w = 201;
char ACC_PUBLIC = 0x1;
char ACC_PRIVATE = 0x2;
char ACC_PROTECTED = 0x4;
char ACC_STATIC = 0x8;
char ACC_FINAL = 0x10;
char ACC_SYNCHRONIZED = 0x20;
char ACC_SUPER = 0x20;
char ACC_VOLATILE = 0x40;
char ACC_TRANSIENT = 0x80;
char ACC_NATIVE = 0x100;
char ACC_INTERFACE = 0x200;
char ACC_ABSTRACT = 0x400;
char ACC_STRICT = 0x800;
char ACC_SYNTHETIC = 0x1000;
char ACC_ANNOTATION = 0x2000;
char ACC_ENUM = 0x4000;
char ACC_MODULE = 0x8000;
byte CONSTANT_Utf8 = 1;
byte CONSTANT_Integer = 3;
byte CONSTANT_Float = 4;
byte CONSTANT_Long = 5;
byte CONSTANT_Double = 6;
byte CONSTANT_Class = 7;
byte CONSTANT_String = 8;
byte CONSTANT_FieldRef = 9;
byte CONSTANT_MethodRef = 10;
byte CONSTANT_InterfaceMethodRef = 11;
byte CONSTANT_NameAndType = 12;
byte CONSTANT_MethodHandle = 15;
byte CONSTANT_MethodType = 16;
byte CONSTANT_InvokeDynamic = 18;
byte T_BOOLEAN = 4;
byte T_CHAR = 5;
byte T_FLOAT = 6;
byte T_DOUBLE = 7;
byte T_BYTE = 8;
byte T_SHORT = 9;
byte T_INT = 10;
byte T_LONG = 11;
String TYPE_boolean = "Z";
String TYPE_byte = "B";
String TYPE_int = "I";
String TYPE_short = "S";
String TYPE_long = "J";
String TYPE_float = "F";
String TYPE_double = "D";
String TYPE_char = "C";
String TYPE_void = "V";
String TYPE_String = "Ljava/lang/String;";
String TYPE_MethodHandle = "Ljava/lang/invoke/MethodHandle;";
String TYPE_MethodType = "Ljava/lang/invoke/MethodType;";
String TYPE_Object = "Ljava/lang/Object;";
String TYPE_Throwable = "Ljava/lang/Throwable;";
String TYPE_Class = "Ljava/lang/Class;";
String TYPE_Exception = "Ljava/lang/Exception;";
String TYPE_RuntimeException = "Ljava/lang/RuntimeException;";
String TYPE_Error = "Ljava/lang/Error;";
/**
* This represents the type of "null", which can be any object. It is not defined by the JVM spec.
*/
String TYPE_null = "L;";
/** This represents a type which is unknown. It is not defined by the JVM spec. */
String TYPE_unknown = "L?;";
byte TYPE_int_index = 0;
byte TYPE_long_index = 1;
byte TYPE_float_index = 2;
byte TYPE_double_index = 3;
byte TYPE_Object_index = 4;
byte TYPE_byte_index = 5;
byte TYPE_char_index = 6;
byte TYPE_short_index = 7;
byte TYPE_boolean_index = 8;
String[] indexedTypes = {
TYPE_int,
TYPE_long,
TYPE_float,
TYPE_double,
TYPE_Object,
TYPE_byte,
TYPE_char,
TYPE_short,
TYPE_boolean
};
byte[] indexedTypes_T = {T_INT, T_LONG, T_FLOAT, T_DOUBLE, 0, T_BYTE, T_CHAR, T_SHORT, T_BOOLEAN};
// these constants are used by analyses to report results
int NO = 1;
int YES = 2;
int MAYBE = 3;
}
| 9,594
| 14.807249
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ConversionInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents instructions that convert from one primitive type to another. */
public final class ConversionInstruction extends Instruction implements IConversionInstruction {
private final String fromType;
private final String toType;
private ConversionInstruction(short opcode) {
super(opcode);
if (opcode < OP_i2b) {
int k = opcode - OP_i2l;
toType = indexedTypes[skip(k % 3, k / 3)];
} else {
toType = indexedTypes[(opcode - OP_i2b) + TYPE_byte_index];
}
if (opcode < OP_i2b) {
fromType = indexedTypes[(opcode - OP_i2l) / 3];
} else {
fromType = TYPE_int;
}
}
private static final ConversionInstruction[] preallocated = preallocate();
private static ConversionInstruction[] preallocate() {
ConversionInstruction[] r = new ConversionInstruction[OP_i2s - OP_i2l + 1];
for (short i = OP_i2l; i <= OP_i2s; i++) {
r[i - OP_i2l] = new ConversionInstruction(i);
}
return r;
}
public static ConversionInstruction make(String fromType, String toType)
throws IllegalArgumentException {
int from = Util.getTypeIndex(fromType);
int to = Util.getTypeIndex(toType);
if (from < 0 || from > TYPE_double_index) {
throw new IllegalArgumentException("Cannot convert from type " + fromType);
}
if (from == TYPE_int_index && (to >= TYPE_byte_index && to <= TYPE_short_index)) {
return preallocated[(OP_i2b - OP_i2l) + (to - TYPE_byte_index)];
} else {
if (to < 0 || to > TYPE_double_index) {
throw new IllegalArgumentException(
"Cannot convert from type " + fromType + " to type " + toType);
}
if (to == from) {
throw new IllegalArgumentException(
"Cannot convert from type " + fromType + " to same type");
}
return preallocated[from * 3 + (to > from ? to - 1 : to)];
}
}
@Override
public int getPoppedCount() {
return 1;
}
@Override
public String getFromType() {
return fromType;
}
private static int skip(int a, int b) {
return a < b ? a : a + 1;
}
@Override
public String getToType() {
return toType;
}
@Override
public String getPushedType(String[] types) {
return getToType();
}
@Override
public byte getPushedWordSize() {
return Util.getWordSize(getToType());
}
@Override
public boolean equals(Object o) {
if (o instanceof ConversionInstruction) {
ConversionInstruction i = (ConversionInstruction) o;
return i.opcode == opcode;
} else {
return false;
}
}
@Override
public int hashCode() {
return opcode * 143111;
}
@Override
public String toString() {
return "Conversion(" + getFromType() + ',' + getToType() + ')';
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitConversion(this);
}
@Override
public boolean isPEI() {
return false;
}
@Override
public boolean throwsExceptionOnOverflow() {
return false;
}
}
| 3,441
| 25.075758
| 96
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/Decoder.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction.Operator;
import java.util.ArrayList;
import java.util.Arrays;
/**
* A Decoder translates a method's Java bytecode into shrikeBT code, i.e. an array of Instruction
* objects and an array of lists of ExceptionHandlers.
*
* <p>This class implements basic decoding functionality. A toolkit for reading class files must
* specialize this class with particular constant pool reader implementation.
*
* <p>Normal usage of this class looks like this:
*
* <pre>
*
* Decoder d = new MyToolkitDecoder(...);
* try {
* d.decode();
* } catch (Decoder.InvalidBytecodeException ex) {
* ...
* }
* Instruction[] myInstructions = d.getInstructions();
* ExceptionHandler[][] exnHandlers = d.getHandlers();
*
* </pre>
*/
public abstract class Decoder implements Constants {
private static final int UNSEEN = -1;
private static final int INSIDE_INSTRUCTION = -2;
private static int skip(int a, int b) {
return a < b ? a : a + 1;
}
private static final ExceptionHandler[] noHandlers = new ExceptionHandler[0];
/** This holds predecoded instructions for the single-byte instructions. */
private static final Instruction[] simpleInstructions = makeSimpleInstructions();
private static Instruction[] makeSimpleInstructions() {
Instruction[] table = new Instruction[256];
table[OP_aconst_null] = ConstantInstruction.make(TYPE_null, null);
for (int i = OP_iconst_m1; i <= OP_iconst_5; i++) {
table[i] = ConstantInstruction.make(TYPE_int, i - OP_iconst_m1 - 1);
}
for (int i = OP_lconst_0; i <= OP_lconst_1; i++) {
table[i] = ConstantInstruction.make(TYPE_long, (long) (i - OP_lconst_0));
}
for (int i = OP_fconst_0; i <= OP_fconst_2; i++) {
table[i] = ConstantInstruction.make(TYPE_float, (float) (i - OP_fconst_0));
}
for (int i = OP_dconst_0; i <= OP_dconst_1; i++) {
table[i] = ConstantInstruction.make(TYPE_double, (double) (i - OP_dconst_0));
}
for (int i = OP_iload_0; i <= OP_aload_3; i++) {
table[i] = LoadInstruction.make(indexedTypes[(i - OP_iload_0) / 4], (i - OP_iload_0) % 4);
}
for (int i = OP_iaload; i <= OP_saload; i++) {
table[i] = ArrayLoadInstruction.make(indexedTypes[i - OP_iaload]);
}
for (int i = OP_istore_0; i <= OP_astore_3; i++) {
table[i] = StoreInstruction.make(indexedTypes[(i - OP_istore_0) / 4], (i - OP_istore_0) % 4);
}
for (int i = OP_iastore; i <= OP_sastore; i++) {
table[i] = ArrayStoreInstruction.make(indexedTypes[i - OP_iastore]);
}
table[OP_pop] = PopInstruction.make(1);
table[OP_dup] = DupInstruction.make(1, 0);
table[OP_dup_x1] = DupInstruction.make(1, 1);
table[OP_swap] = SwapInstruction.make();
for (int i = OP_iadd; i <= OP_drem; i++) {
table[i] =
BinaryOpInstruction.make(
indexedTypes[(i - OP_iadd) % 4],
BinaryOpInstruction.Operator.values()[(i - OP_iadd) / 4]);
}
for (int i = OP_ineg; i <= OP_dneg; i++) {
table[i] = UnaryOpInstruction.make(indexedTypes[i - OP_ineg]);
}
for (int i = OP_ishl; i <= OP_lushr; i++) {
table[i] =
ShiftInstruction.make(
indexedTypes[(i - OP_ishl) % 2],
ShiftInstruction.Operator.values()[(i - OP_ishl) / 2]);
}
for (int i = OP_iand; i <= OP_lxor; i++) {
table[i] =
BinaryOpInstruction.make(
indexedTypes[(i - OP_iand) % 2],
BinaryOpInstruction.Operator.values()[
BinaryOpInstruction.Operator.AND.ordinal() + (i - OP_iand) / 2]);
}
for (int i = OP_i2l; i <= OP_d2f; i++) {
table[i] =
ConversionInstruction.make(
indexedTypes[(i - OP_i2l) / 3],
indexedTypes[skip((i - OP_i2l) % 3, (i - OP_i2l) / 3)]);
}
for (int i = OP_i2b; i <= OP_i2s; i++) {
table[i] = ConversionInstruction.make(TYPE_int, indexedTypes[5 + (i - OP_i2b)]);
}
table[OP_lcmp] = ComparisonInstruction.make(TYPE_long, ComparisonInstruction.Operator.CMP);
for (int i = OP_fcmpl; i <= OP_dcmpg; i++) {
table[i] =
ComparisonInstruction.make(
indexedTypes[2 + (i - OP_fcmpl) / 2],
ComparisonInstruction.Operator.values()[
ComparisonInstruction.Operator.CMPL.ordinal() + (i - OP_fcmpl) % 2]);
}
for (int i = OP_ireturn; i <= OP_areturn; i++) {
table[i] = ReturnInstruction.make(indexedTypes[i - OP_ireturn]);
}
table[OP_return] = ReturnInstruction.make(TYPE_void);
table[OP_athrow] = ThrowInstruction.make(false);
table[OP_monitorenter] = MonitorInstruction.make(true);
table[OP_monitorexit] = MonitorInstruction.make(false);
table[OP_arraylength] = ArrayLengthInstruction.make();
return table;
}
private static final Instruction makeZero = ConstantInstruction.make(0);
// Holds the result of decoding
private IInstruction[] instructions;
private ExceptionHandler[][] handlers;
private int[] instructionsToBytecodes;
private final ConstantPoolReader constantPool;
// Holds the input to decode
private final byte[] code;
private final int[] rawHandlers;
// Temporary working data
private int[] decodedOffset;
private byte[] decodedSize;
private ArrayList<Instruction> decoded;
private int[] belongsToSub;
private int[] JSRs;
private RetInfo[] retInfo;
/**
* This constructor is only supposed to be used by subclasses.
*
* @param code the bytecodes for a method as per JVM spec
* @param rawHandlers flattened array of (startPC, endPC, targetPC, classIndex) tuples defined as
* per the JVM spec
*/
protected Decoder(byte[] code, int[] rawHandlers, ConstantPoolReader cp) {
this.code = code;
this.rawHandlers = rawHandlers;
this.constantPool = cp;
}
public ConstantPoolReader getConstantPool() {
return constantPool;
}
private int decodeShort(int index) {
return (code[index] << 8) | (code[index + 1] & 0xFF);
}
private int decodeUShort(int index) {
return ((code[index] & 0xFF) << 8) | (code[index + 1] & 0xFF);
}
private int decodeInt(int index) {
return (code[index] << 24)
| ((code[index + 1] & 0xFF) << 16)
| ((code[index + 2] & 0xFF) << 8)
| (code[index + 3] & 0xFF);
}
private Instruction makeConstantPoolLoad(int index) throws InvalidBytecodeException {
ConstantInstruction ci = ConstantInstruction.make(constantPool, index);
if (ci == null) {
throw new InvalidBytecodeException(
"Constant pool item at index "
+ index
+ " (type "
+ constantPool.getConstantPoolItemType(index)
+ ") cannot be loaded");
}
return ci;
}
private static int elemCount(byte[] stack, int stackPtr) throws InvalidBytecodeException {
if (stackPtr < 0) {
throw new InvalidBytecodeException("Stack underflow");
}
if (stack[stackPtr] == 2) {
return 1;
} else {
if (stackPtr < 1) {
throw new InvalidBytecodeException("Stack underflow");
}
if (stack[stackPtr - 1] != 1) {
throw new InvalidBytecodeException(
"Trying to manipulate a pair of " + "one-word items but one of them is two words");
}
return 2;
}
}
private static String getPrimitiveType(int t) throws InvalidBytecodeException {
switch (t) {
case T_BOOLEAN:
return TYPE_boolean;
case T_CHAR:
return TYPE_char;
case T_FLOAT:
return TYPE_float;
case T_DOUBLE:
return TYPE_double;
case T_BYTE:
return TYPE_byte;
case T_SHORT:
return TYPE_short;
case T_INT:
return TYPE_int;
case T_LONG:
return TYPE_long;
default:
throw new InvalidBytecodeException("Unknown primitive type " + t);
}
}
private static class RetInfo {
int sub;
final int retVar;
final int stackLen;
final byte[] stackWords;
RetInfo(int sub, int retVar, int stackLen, byte[] stackWords) {
this.sub = sub;
this.retVar = retVar;
this.stackLen = stackLen;
this.stackWords = stackWords;
}
}
private boolean doesSubroutineReturn(int sub) {
for (RetInfo element : retInfo) {
if (element != null && element.sub == sub) {
return true;
}
}
return false;
}
private int findReturnToVar(int v, int addr, boolean[] visited) throws InvalidBytecodeException {
while (true) {
if (visited[addr]) {
return 0;
} else if (retInfo[addr] != null && retInfo[addr].retVar == v) {
return addr;
} else {
int offset = decodedOffset[addr];
if (offset == UNSEEN) {
return 0;
}
int size = decodedSize[addr];
Instruction instr = null;
visited[addr] = true;
for (int j = 0; j < rawHandlers.length; j += 4) {
if (rawHandlers[j] <= addr && addr < rawHandlers[j + 1]) {
int handlerAddr = rawHandlers[j + 2];
if (decodedOffset[handlerAddr] < 0) {
byte[] stackWords = new byte[code.length * 2];
// the bottom element on the stack must be a return address.
stackWords[0] = 1;
decodeAt(handlerAddr, 1, stackWords);
}
int r = findReturnToVar(v, handlerAddr, visited);
if (r != 0) {
return r;
}
}
}
// If there's a JSR here, see if it ever returns. If it does not
// then this instruction does not fall through and so we should
// stop searching.
if (JSRs[addr] != 0) {
if (!doesSubroutineReturn(JSRs[addr])) {
return 0;
}
} else {
for (int j = 0; j < size; j++) {
instr = decoded.get(offset + j);
if (instr instanceof StoreInstruction
&& ((StoreInstruction) instr).getVarIndex() == v) {
return 0;
}
int[] targets = instr.getBranchTargets();
for (int target : targets) {
if (target >= 0) {
int r = findReturnToVar(v, target, visited);
if (r != 0) {
return r;
}
}
}
}
if (instr != null && !instr.isFallThrough()) {
return 0;
}
}
do {
addr++;
} while (decodedOffset[addr] == INSIDE_INSTRUCTION);
}
}
}
/** Locate an instruction that returns from this subroutine; return 0 if one cannot be found. */
private int findReturn(int subAddr) throws InvalidBytecodeException {
if (decodedSize[subAddr] < 1) {
throw new InvalidBytecodeException(
"Subroutine at " + subAddr + " does not start with an astore or pop instruction");
}
Instruction instr = decoded.get(decodedOffset[subAddr]);
if (instr instanceof PopInstruction) {
// this subroutine can't return
return 0;
}
if (!(instr instanceof StoreInstruction)) {
throw new InvalidBytecodeException(
"Subroutine at " + subAddr + " does not start with an astore or pop instruction");
}
int localIndex = ((StoreInstruction) instr).getVarIndex();
do {
subAddr++;
} while (decodedOffset[subAddr] == INSIDE_INSTRUCTION);
return findReturnToVar(localIndex, subAddr, new boolean[code.length]);
}
private void decodeSubroutine(
int jsrAddr, int retToAddr, int subAddr, int stackLen, byte[] stackWords)
throws InvalidBytecodeException {
if (JSRs == null) {
JSRs = new int[code.length];
retInfo = new RetInfo[code.length];
}
JSRs[jsrAddr] = subAddr;
if (decodedOffset[subAddr] < 0) {
stackWords[stackLen] = 1;
stackLen++;
decodeAt(subAddr, stackLen, stackWords);
}
int retAddr = findReturn(subAddr);
if (retAddr > 0) {
RetInfo r = retInfo[retAddr];
r.sub = subAddr;
byte[] cloneStackWords = new byte[r.stackWords.length];
System.arraycopy(r.stackWords, 0, cloneStackWords, 0, cloneStackWords.length);
decodeAt(retToAddr, r.stackLen, cloneStackWords);
}
}
private void assignReachablesToSubroutine(int addr, int sub) {
while (belongsToSub[addr] < 0) {
int size = decodedSize[addr];
belongsToSub[addr] = sub;
for (int j = 0; j < rawHandlers.length; j += 4) {
if (rawHandlers[j] <= addr && addr < rawHandlers[j + 1]) {
assignReachablesToSubroutine(rawHandlers[j + 2], sub);
}
}
Instruction instr = null;
if (size > 0 && JSRs[addr] == 0) {
int offset = decodedOffset[addr];
instr = decoded.get(offset + size - 1);
int[] targets = instr.getBranchTargets();
for (int target : targets) {
if (target >= 0) {
// only chase real gotos; ignore rets
assignReachablesToSubroutine(target, sub);
}
}
}
if (instr != null && !instr.isFallThrough()) {
return;
}
if (JSRs[addr] != 0 && !doesSubroutineReturn(JSRs[addr])) {
return;
}
do {
addr++;
} while (decodedOffset[addr] < 0);
}
}
private void assignSubroutine(int sub) {
assignReachablesToSubroutine(sub, sub);
for (int i = 0; i < belongsToSub.length; i++) {
if (JSRs[i] > 0 && belongsToSub[i] == sub && belongsToSub[JSRs[i]] < 0) {
assignSubroutine(JSRs[i]);
}
}
}
private void computeSubroutineMap() {
belongsToSub = new int[code.length];
Arrays.fill(belongsToSub, -1);
assignSubroutine(0);
}
private int decodeBytecodeInstruction(int index, int stackLen, byte[] stackWords)
throws InvalidBytecodeException {
int opcode = code[index] & 0xFF;
Instruction i = simpleInstructions[opcode];
if (i != null) {
decoded.add(i);
return index + 1;
}
boolean wide = false;
while (true) {
index++;
switch (opcode) {
case OP_nop:
break;
case OP_bipush:
i = ConstantInstruction.make(code[index]);
index++;
break;
case OP_sipush:
i = ConstantInstruction.make(decodeShort(index));
index += 2;
break;
case OP_ldc:
i = makeConstantPoolLoad(code[index] & 0xFF);
index++;
break;
case OP_ldc_w:
i = makeConstantPoolLoad(decodeUShort(index));
index += 2;
break;
case OP_ldc2_w:
i = makeConstantPoolLoad(decodeUShort(index));
index += 2;
break;
case OP_iload:
case OP_lload:
case OP_fload:
case OP_dload:
case OP_aload:
i =
LoadInstruction.make(
indexedTypes[opcode - OP_iload],
wide ? decodeUShort(index) : (code[index] & 0xFF));
index += wide ? 2 : 1;
break;
case OP_istore:
case OP_lstore:
case OP_fstore:
case OP_dstore:
case OP_astore:
i =
StoreInstruction.make(
indexedTypes[opcode - OP_istore],
wide ? decodeUShort(index) : (code[index] & 0xFF));
index += wide ? 2 : 1;
break;
case OP_pop2:
i = PopInstruction.make(elemCount(stackWords, stackLen - 1));
break;
case OP_dup_x2:
i = DupInstruction.make(1, elemCount(stackWords, stackLen - 2));
break;
case OP_dup2:
i = DupInstruction.make(elemCount(stackWords, stackLen - 1), 0);
break;
case OP_dup2_x1:
i = DupInstruction.make(elemCount(stackWords, stackLen - 1), 1);
break;
case OP_dup2_x2:
{
int twoDown = elemCount(stackWords, stackLen - 1);
i = DupInstruction.make(twoDown, elemCount(stackWords, stackLen - twoDown - 1));
break;
}
case OP_iinc:
{
int v = wide ? decodeUShort(index) : (code[index] & 0xFF);
int c = wide ? decodeShort(index + 2) : code[index + 1];
decoded.add(LoadInstruction.make(TYPE_int, v));
decoded.add(ConstantInstruction.make(c));
decoded.add(BinaryOpInstruction.make(TYPE_int, Operator.ADD));
i = StoreInstruction.make(TYPE_int, v);
index += wide ? 4 : 2;
break;
}
case OP_ifeq:
case OP_ifne:
case OP_iflt:
case OP_ifle:
case OP_ifgt:
case OP_ifge:
decoded.add(makeZero);
i =
ConditionalBranchInstruction.make(
TYPE_int,
ConditionalBranchInstruction.Operator.values()[opcode - OP_ifeq],
(index - 1) + decodeShort(index));
index += 2;
break;
case OP_if_icmpeq:
case OP_if_icmpne:
case OP_if_icmplt:
case OP_if_icmple:
case OP_if_icmpgt:
case OP_if_icmpge:
i = ConditionalBranchInstruction.make((short) opcode, (index - 1) + decodeShort(index));
index += 2;
break;
case OP_if_acmpeq:
case OP_if_acmpne:
i =
ConditionalBranchInstruction.make(
TYPE_Object,
ConditionalBranchInstruction.Operator.values()[opcode - OP_if_acmpeq],
(index - 1) + decodeShort(index));
index += 2;
break;
case OP_goto:
i = GotoInstruction.make((index - 1) + decodeShort(index));
index += 2;
break;
case OP_jsr:
{
index += 2;
break;
}
case OP_jsr_w:
{
index += 4;
break;
}
case OP_ret:
int v = wide ? decodeUShort(index) : (code[index] & 0xFF);
i = GotoInstruction.make(-1 - v);
if (retInfo == null) {
throw new InvalidBytecodeException("'ret' outside of subroutine");
}
retInfo[index - (wide ? 2 : 1)] = new RetInfo(-1, v, stackLen, stackWords);
index += wide ? 2 : 1;
break;
case OP_tableswitch:
{
int start = index - 1;
while ((index & 3) != 0) {
index++;
}
int def = start + decodeInt(index);
int low = decodeInt(index + 4);
int high = decodeInt(index + 8);
int[] t = new int[(high - low + 1) * 2];
for (int j = 0; j < t.length; j += 2) {
t[j] = j / 2 + low;
t[j + 1] = start + decodeInt(index + 12 + j * 2);
}
i = SwitchInstruction.make(t, def);
index += 12 + (high - low + 1) * 4;
break;
}
case OP_lookupswitch:
{
int start = index - 1;
while ((index & 3) != 0) {
index++;
}
int def = start + decodeInt(index);
int n = decodeInt(index + 4);
int[] t = new int[n * 2];
for (int j = 0; j < t.length; j += 2) {
t[j] = decodeInt(index + 8 + j * 4);
t[j + 1] = start + decodeInt(index + 12 + j * 4);
}
i = SwitchInstruction.make(t, def);
index += 8 + n * 8;
break;
}
case OP_getstatic:
case OP_getfield:
{
int f = decodeUShort(index);
i = GetInstruction.make(constantPool, f, opcode == OP_getstatic);
index += 2;
break;
}
case OP_putstatic:
case OP_putfield:
{
int f = decodeUShort(index);
i = PutInstruction.make(constantPool, f, opcode == OP_putstatic);
index += 2;
break;
}
case OP_invokevirtual:
case OP_invokespecial:
case OP_invokestatic:
{
int m = decodeUShort(index);
i = InvokeInstruction.make(constantPool, m, opcode);
index += 2;
break;
}
case OP_invokeinterface:
{
int m = decodeUShort(index);
i = InvokeInstruction.make(constantPool, m, opcode);
index += 4;
break;
}
case OP_invokedynamic:
{
int m = decodeUShort(index);
i = InvokeDynamicInstruction.make(constantPool, m, opcode);
index += 4;
break;
}
case OP_new:
i = NewInstruction.make(constantPool.getConstantPoolClassType(decodeUShort(index)), 0);
index += 2;
break;
case OP_newarray:
i = NewInstruction.make(Util.makeArray(getPrimitiveType(code[index])), 1);
index++;
break;
case OP_anewarray:
i =
NewInstruction.make(
Util.makeArray(constantPool.getConstantPoolClassType(decodeUShort(index))), 1);
index += 2;
break;
case OP_checkcast:
i = CheckCastInstruction.make(constantPool.getConstantPoolClassType(decodeUShort(index)));
index += 2;
break;
case OP_instanceof:
i =
InstanceofInstruction.make(
constantPool.getConstantPoolClassType(decodeUShort(index)));
index += 2;
break;
case OP_wide:
wide = true;
opcode = code[index] & 0xFF;
continue;
case OP_multianewarray:
i =
NewInstruction.make(
constantPool.getConstantPoolClassType(decodeUShort(index)),
code[index + 2] & 0xFF);
index += 3;
break;
case OP_ifnull:
case OP_ifnonnull:
decoded.add(ConstantInstruction.make(TYPE_Object, null));
i =
ConditionalBranchInstruction.make(
TYPE_Object,
ConditionalBranchInstruction.Operator.values()[opcode - OP_ifnull],
(index - 1) + decodeShort(index));
index += 2;
break;
case OP_goto_w:
i = GotoInstruction.make((index - 1) + decodeInt(index));
index += 4;
break;
default:
throw new InvalidBytecodeException("Unknown opcode " + opcode);
}
break;
}
if (i != null) {
decoded.add(i);
}
return index;
}
private static int applyInstructionToStack(Instruction i, int stackLen, byte[] stackWords)
throws InvalidBytecodeException {
stackLen -= i.getPoppedCount();
if (stackLen < 0) {
throw new InvalidBytecodeException("Stack underflow");
}
if (i instanceof DupInstruction) {
DupInstruction d = (DupInstruction) i;
int delta = d.getDelta();
int size = d.getSize();
System.arraycopy(stackWords, stackLen + delta, stackWords, stackLen + size + delta, size);
System.arraycopy(stackWords, stackLen, stackWords, stackLen + size, delta);
System.arraycopy(stackWords, stackLen + size + delta, stackWords, stackLen, size);
stackLen += size * 2 + delta;
} else if (i instanceof SwapInstruction) {
if (stackWords[stackLen] != stackWords[stackLen + 1]) {
throw new Error("OP_swap must always be swapping the same size, 1");
}
stackLen += 2;
} else {
byte pushedWords = i.getPushedWordSize();
if (pushedWords > 0) {
stackWords[stackLen] = pushedWords;
stackLen++;
}
}
return stackLen;
}
private void decodeAt(int index, int stackLen, byte[] stackWords)
throws InvalidBytecodeException {
if (index < 0 || index >= decodedOffset.length) {
throw new InvalidBytecodeException(index, "Branch index " + index + " out of range");
}
while (decodedOffset[index] < 0) {
int s = decoded.size();
decodedOffset[index] = s;
int newIndex;
try {
newIndex = decodeBytecodeInstruction(index, stackLen, stackWords);
int instrCount = decoded.size() - s;
decodedSize[index] = (byte) instrCount;
// mark invalid offsets
for (int i = index + 1; i < newIndex; i++) {
decodedOffset[i] = INSIDE_INSTRUCTION;
}
if (instrCount > 0) {
for (int i = s; i < s + instrCount; i++) {
stackLen = applyInstructionToStack(decoded.get(i), stackLen, stackWords);
}
Instruction instr = decoded.get(s + instrCount - 1);
int[] targets = instr.getBranchTargets();
for (int t : targets) {
if (t >= 0) {
decodeAt(t, stackLen, stackWords.clone());
}
}
if (!instr.isFallThrough()) {
return;
}
} else { // possibly the jsr case
int jIndex = index;
int opcode = code[jIndex] & 0xFF;
if (opcode == OP_wide) {
jIndex++;
opcode = code[jIndex] & 0xFF;
}
if (opcode == OP_jsr || opcode == OP_jsr_w) {
jIndex++;
int offset = opcode == OP_jsr_w ? decodeInt(jIndex) : decodeShort(jIndex);
decoded.add(GotoInstruction.make(0));
decodedSize[index] = 1;
decodeSubroutine(index, newIndex, index + offset, stackLen, stackWords);
return;
}
}
} catch (InvalidBytecodeException ex) {
ex.setIndex(index);
throw ex;
} catch (Error | RuntimeException ex) {
System.err.println("Fatal error at index " + index);
throw ex;
}
index = newIndex;
if (index >= decodedOffset.length) {
throw new InvalidBytecodeException(index, "Fell off end of bytecode array");
}
}
}
/**
* This exception is thrown when the Decoder detects invalid incoming bytecode (code that would
* not pass the Java verifier). We don't guarantee to perform full verification in the Decoder,
* however.
*/
public static class InvalidBytecodeException extends Exception {
private static final long serialVersionUID = -8807125136613458111L;
private int index;
InvalidBytecodeException(String s) {
super(s);
index = -1;
}
InvalidBytecodeException(int i, String s) {
super(s);
index = i;
}
void setIndex(int i) {
if (index < 0) {
index = i;
}
}
/** @return the offset of the bytecode instruction deemed to be invalid */
public int getIndex() {
return index;
}
}
private ExceptionHandler[] makeHandlers(int i, int[] addrMap) {
int numHandlers = 0;
for (int j = 0; j < rawHandlers.length; j += 4) {
if (rawHandlers[j] <= i && i < rawHandlers[j + 1]) {
numHandlers++;
}
}
return makeHandlers(i, numHandlers, addrMap);
}
private ExceptionHandler[] makeHandlers(int i, int numHandlers, int[] addrMap) {
if (numHandlers == 0) {
return noHandlers;
} else {
ExceptionHandler[] hs = new ExceptionHandler[numHandlers];
numHandlers = 0;
for (int j = 0; j < rawHandlers.length; j += 4) {
if (rawHandlers[j] <= i && i < rawHandlers[j + 1]) {
int classIndex = rawHandlers[j + 3];
String catchClass =
classIndex == 0 ? null : constantPool.getConstantPoolClassType(classIndex);
hs[numHandlers] = new ExceptionHandler(addrMap[rawHandlers[j + 2]], catchClass);
numHandlers++;
}
}
return hs;
}
}
private int computeSubroutineLength(int sub) {
int len = 1; // extra instruction for "push null"
for (int i = sub; i < belongsToSub.length; i++) {
if (belongsToSub[i] == sub) {
len += decodedSize[i];
if (JSRs[i] > 0) {
len += computeSubroutineLength(JSRs[i]);
}
}
}
return len;
}
private int appendSubroutineCode(int callSite, int newCodeIndex, int[] callerMap) {
instructions[callerMap[callSite]] = GotoInstruction.make(newCodeIndex);
instructions[newCodeIndex] = ConstantInstruction.make(TYPE_Object, null);
newCodeIndex++;
int subStart = newCodeIndex;
int[] map = callerMap.clone();
int sub = JSRs[callSite];
// emit the subroutine code
for (int i = sub; i < belongsToSub.length; i++) {
if (belongsToSub[i] == sub) {
int s = decodedSize[i];
int offset = decodedOffset[i];
map[i] = newCodeIndex;
for (int j = 0; j < s; j++) {
Instruction instr = decoded.get(offset + j);
instructions[newCodeIndex] = instr;
instructionsToBytecodes[newCodeIndex] = i;
newCodeIndex++;
}
}
}
// fix up branch targets within emitted subroutine
for (int i = subStart; i < newCodeIndex; i++) {
IInstruction instr = instructions[i];
if (instr instanceof GotoInstruction && ((GotoInstruction) instr).getLabel() < 0) {
// fix up 'ret' instruction to branch back to return address
instructions[i] = GotoInstruction.make(callerMap[callSite] + 1);
} else {
instructions[i] = instr.redirectTargets(map);
}
handlers[i] = makeHandlers(instructionsToBytecodes[i], map);
}
// extend handlers to cover the fake "push null"
handlers[subStart - 1] = handlers[subStart];
// resolve callee subroutines
for (int i = sub; i < belongsToSub.length; i++) {
if (belongsToSub[i] == sub && JSRs[i] > 0) {
newCodeIndex = appendSubroutineCode(i, newCodeIndex, map);
}
}
return newCodeIndex;
}
/**
* Perform the decoding.
*
* @throws InvalidBytecodeException the incoming code is invalid and would fail Java bytecode
* verification
*/
public final void decode() throws InvalidBytecodeException {
byte[] stackWords = new byte[code.length * 2];
decoded = new ArrayList<>();
decodedOffset = new int[code.length];
Arrays.fill(decodedOffset, UNSEEN);
decodedSize = new byte[code.length];
decodeAt(0, 0, stackWords);
// Decode code that's only reachable through exception handlers
for (int i = 0; i < rawHandlers.length; i += 4) {
stackWords[0] = 1;
decodeAt(rawHandlers[i + 2], 1, stackWords);
}
if (retInfo != null) {
computeSubroutineMap();
retInfo = null;
}
int instructionsLen = decoded.size();
if (belongsToSub != null) {
for (int i = 0; i < belongsToSub.length; i++) {
if (belongsToSub[i] == 0) {
if (JSRs[i] > 0) {
instructionsLen += computeSubroutineLength(JSRs[i]);
}
} else if (belongsToSub[i] > 0) {
instructionsLen -= decodedSize[i];
}
}
}
instructions = new Instruction[instructionsLen];
instructionsToBytecodes = new int[instructionsLen];
handlers = new ExceptionHandler[instructionsLen][];
// shuffle decoded instructions into method order
int p = 0;
for (int i = 0; i < decodedOffset.length; i++) {
int offset = decodedOffset[i];
if (offset >= 0 && (belongsToSub == null || belongsToSub[i] == 0)) {
decodedOffset[i] = p;
int s = decodedSize[i];
for (int j = 0; j < s; j++) {
instructions[p] = decoded.get(offset + j);
instructionsToBytecodes[p] = i;
p++;
}
}
}
// fix up instructions to refer to the instruction vector instead of
// bytecode offsets
for (int i = 0; i < p; i++) {
instructions[i] = instructions[i].redirectTargets(decodedOffset);
}
// emit subroutines
if (JSRs != null) {
for (int i = 0; i < JSRs.length; i++) {
if (JSRs[i] > 0 && belongsToSub[i] == 0) {
p = appendSubroutineCode(i, p, decodedOffset);
}
}
}
// generate exception handlers
if (rawHandlers.length > 0) {
ExceptionHandler[] hs = null;
int handlersValidBefore = -1;
p = 0;
for (int i = 0; i < decodedOffset.length; i++) {
if (decodedOffset[i] >= 0 && (belongsToSub == null || belongsToSub[i] == 0)) {
if (i >= handlersValidBefore) {
// We just crossed a handler range boundary
// compute new exception handler array
int numHandlers = 0;
handlersValidBefore = Integer.MAX_VALUE;
for (int j = 0; j < rawHandlers.length; j += 4) {
if (rawHandlers[j] <= i) {
if (i < rawHandlers[j + 1]) {
numHandlers++;
handlersValidBefore = Math.min(handlersValidBefore, rawHandlers[j + 1]);
}
} else {
handlersValidBefore = Math.min(handlersValidBefore, rawHandlers[j]);
}
}
hs = makeHandlers(i, numHandlers, decodedOffset);
}
int s = decodedSize[i];
for (int j = 0; j < s; j++) {
handlers[p] = hs;
p++;
}
}
}
} else {
Arrays.fill(handlers, noHandlers);
}
decoded = null;
decodedOffset = null;
decodedSize = null;
belongsToSub = null;
JSRs = null;
}
/**
* Get the decoded instructions.
*
* @return array of decoded instructions
*/
public final IInstruction[] getInstructions() {
if (instructions == null) {
throw new Error("Call decode() before calling getInstructions()");
}
return instructions;
}
/**
* Get the decoded exception handlers.
*
* @return array of exception handler lists
*/
public final ExceptionHandler[][] getHandlers() {
if (handlers == null) {
throw new Error("Call decode() before calling getHandlers()");
}
return handlers;
}
/**
* Get the mapping between instructions and input bytecodes.
*
* @return an array m such that m[i] is the offset of the bytecode instruction which gave rise to
* the Instruction referenced in the instructions array at offset i
*/
public final int[] getInstructionsToBytecodes() {
if (instructionsToBytecodes == null) {
throw new Error("Call decode() before calling getInstructionsToBytecodes()");
}
return instructionsToBytecodes;
}
/** @return true iff the method decoded by this Decoder contains subroutines (JSRs) */
public final boolean containsSubroutines() {
if (instructions == null) {
throw new Error("Call decode() before calling containsSubroutines()");
}
return JSRs != null;
}
}
| 35,233
| 29.217839
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/Disassembler.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import java.io.IOException;
import java.io.Writer;
/**
* This is a very simple component to disassemble a ShrikeBT method. The disassembly is just the
* list of ShrikeBT instructions, annotated with exception handler blocks and the mapping back to
* the original bytecodes.
*/
public class Disassembler {
private final IInstruction[] instructions;
private final ExceptionHandler[][] handlers;
private final int[] instructionsToBytecodes;
/** Create a disassembler for a method. */
public Disassembler(
IInstruction[] instructions, ExceptionHandler[][] handlers, int[] instructionsToBytecodes) {
this.instructions = instructions;
this.handlers = handlers;
this.instructionsToBytecodes = instructionsToBytecodes;
}
/**
* Create a disassembler for a method.
*
* @throws NullPointerException if data is null
*/
public Disassembler(MethodData data) throws NullPointerException {
this(data.getInstructions(), data.getHandlers(), data.getInstructionsToBytecodes());
}
/** Write the disassembly to a stream. Each line is prefixed with 'prefix'. */
public void disassembleTo(String prefix, Writer w) throws IOException {
for (int j = 0; j < instructions.length; j++) {
w.write(prefix + j + ": " + instructions[j] + " (" + instructionsToBytecodes[j] + ")\n");
for (int k = 0; k < handlers[j].length; k++) {
w.write(
prefix
+ " Handles "
+ handlers[j][k].catchClass
+ " at "
+ handlers[j][k].handler
+ '\n');
}
}
}
/** Write the disassembly to a stream. */
public void disassembleTo(Writer w) throws IOException {
disassembleTo("", w);
}
}
| 2,149
| 31.575758
| 98
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/DupInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import java.util.Arrays;
/**
* This class represents dup instructions. There are two kinds of dup instructions, dup and dup_x1:
*
* <p>dup: a::rest => a::a::rest dup_x1: a::b::rest => a::b::a::rest
*/
public final class DupInstruction extends Instruction {
private final int size;
private final byte delta;
private DupInstruction(byte size, byte delta) {
super((short) -1);
this.size = size;
this.delta = delta;
}
private static final DupInstruction[] preallocated = preallocate();
private static DupInstruction[] preallocate() {
DupInstruction[] r = new DupInstruction[9];
Arrays.setAll(r, i -> new DupInstruction((byte) (i / 3), (byte) (i % 3)));
return r;
}
/**
* DupInstructions with size or delta 2 might cause code generation failures when the working
* stack contains long or double values, when these DupInstructions cannot be easily translated
* into Java bytecode instructions. For safety, avoid using DupInstructions with size or delta 2.
*
* <p>Don't create these outside the shrikeBT decoder.
*/
static DupInstruction make(int size, int delta) {
if (size < 0 || size > 2) {
throw new IllegalArgumentException("Invalid dup size: " + size);
}
if (delta < 0 || delta > 2) {
throw new IllegalArgumentException("Invalid dup delta: " + delta);
}
return preallocated[size * 3 + delta];
}
/** @param delta 0 for dup, 1 for dup_x1 */
public static DupInstruction make(int delta) {
if (delta < 0 || delta > 1) {
throw new IllegalArgumentException("Invalid dup delta: " + delta);
}
return make(1, delta);
}
@Override
public boolean equals(Object o) {
if (o instanceof DupInstruction) {
DupInstruction i = (DupInstruction) o;
return i.size == size && i.delta == delta;
} else {
return false;
}
}
public int getSize() {
return size;
}
public int getDelta() {
return delta;
}
@Override
public int hashCode() {
return size + 8431890 + 10 * delta;
}
@Override
public int getPoppedCount() {
return size + delta;
}
@Override
public String toString() {
return "Dup(" + size + ',' + delta + ')';
}
@Override
public void visit(IInstruction.Visitor v) {
if (v == null) {
throw new IllegalArgumentException("illegal null visitor");
}
v.visitDup(this);
}
@Override
public boolean isPEI() {
return false;
}
}
| 2,869
| 24.855856
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ExceptionHandler.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import java.util.Objects;
/**
* An ExceptionHandler represents a single handler covering a single instruction. It simply tells us
* what kind of exception to catch and where to dispatch the exception to.
*
* <p>ExceptionHandlers are immutable. It is quite legal to save a reference to an exception handler
* and use it in any other context. We also treat arrays of ExceptionHandlers as immutable.
* Therefore the following code can be used to build an exception handler table that specifies two
* handlers covering an entire block of code:
*
* <pre>
*
* ExceptionHandler[] hs = {
* new ExceptionHandler(110, "Ljava.lang.NullPointerException;"),
* new ExceptionHandler(220, "Ljava.io.IOException;");
* };
* for (int i = 0; i < 100; i++) {
* handlers[i] = hs;
* }
* </pre>
*/
public final class ExceptionHandler {
int handler;
final String catchClass;
final Object catchClassLoader;
/**
* @param handler the label for the handler code
* @param catchClass the type of exception that should be caught (in JVM format), or null if all
* exceptions should be caught (as with 'finally')
*/
public ExceptionHandler(int handler, String catchClass, Object catchClassLoader) {
this.handler = handler;
this.catchClass = catchClass;
this.catchClassLoader = catchClassLoader;
}
public ExceptionHandler(int handler, String catchClass) {
this(handler, catchClass, null);
}
/** @return the label of the handler code */
public int getHandler() {
return handler;
}
public Object getCatchClassLoader() {
return catchClassLoader;
}
/** @return the type of exceptions to be caught, or null if all exceptions should be caught */
public String getCatchClass() {
return catchClass;
}
public boolean equals(ExceptionHandler h) {
if (h == null) {
throw new IllegalArgumentException("h is null");
}
return h.handler == handler && Objects.equals(catchClass, h.catchClass);
}
@Override
public int hashCode() {
return 1069 * handler + ((catchClass == null) ? 0 : catchClass.hashCode());
}
@Override
public boolean equals(Object o) {
if (o instanceof ExceptionHandler) {
return equals((ExceptionHandler) o);
} else {
return false;
}
}
}
| 2,728
| 28.344086
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/GetInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents get and getstatic instructions. */
public class GetInstruction extends Instruction implements IGetInstruction {
protected String type;
protected String classType;
protected String fieldName;
GetInstruction(short opcode, String type, String classType, String fieldName) {
super(opcode);
this.type = type;
this.classType = classType;
this.fieldName = fieldName;
}
ConstantPoolReader getLazyConstantPool() {
return null;
}
static final class Lazy extends GetInstruction {
private final ConstantPoolReader cp;
private final int index;
Lazy(short opcode, ConstantPoolReader cp, int index) {
super(opcode, null, null, null);
this.index = index;
this.cp = cp;
}
@Override
ConstantPoolReader getLazyConstantPool() {
return cp;
}
int getCPIndex() {
return index;
}
@Override
public String getClassType() {
if (classType == null) {
classType = cp.getConstantPoolMemberClassType(index);
}
return classType;
}
@Override
public String getFieldName() {
if (fieldName == null) {
fieldName = cp.getConstantPoolMemberName(index);
}
return fieldName;
}
@Override
public String getFieldType() {
if (type == null) {
type = cp.getConstantPoolMemberType(index);
}
return type;
}
}
static GetInstruction make(ConstantPoolReader cp, int index, boolean isStatic) {
return new Lazy(isStatic ? OP_getstatic : OP_getfield, cp, index);
}
public static GetInstruction make(
String type, String className, String fieldName, boolean isStatic) {
if (type == null) {
throw new IllegalArgumentException("type must not be null");
}
if (className == null) {
throw new IllegalArgumentException("className must not be null");
}
if (fieldName == null) {
throw new IllegalArgumentException("fieldName must not be null");
}
return new GetInstruction(isStatic ? OP_getstatic : OP_getfield, type, className, fieldName);
}
@Override
public final boolean equals(Object o) {
if (o instanceof GetInstruction) {
GetInstruction i = (GetInstruction) o;
return i.getFieldType().equals(getFieldType())
&& i.getClassType().equals(getClassType())
&& i.getFieldName().equals(getFieldName())
&& i.opcode == opcode;
} else {
return false;
}
}
@Override
public String getClassType() {
return classType;
}
@Override
public String getFieldName() {
return fieldName;
}
@Override
public String getFieldType() {
return type;
}
@Override
public final boolean isStatic() {
return opcode == OP_getstatic;
}
@Override
public final int hashCode() {
return getClassType().hashCode()
+ 11113 * getFieldType().hashCode()
+ 398011 * getFieldName().hashCode()
+ opcode;
}
@Override
public final int getPoppedCount() {
return isStatic() ? 0 : 1;
}
@Override
public final String getPushedType(String[] types) {
return getFieldType();
}
@Override
public final byte getPushedWordSize() {
return Util.getWordSize(getFieldType());
}
@Override
public String toString() {
return "Get("
+ getFieldType()
+ ','
+ (isStatic() ? "STATIC" : "NONSTATIC")
+ ','
+ getClassType()
+ ','
+ getFieldName()
+ ')';
}
@Override
public void visit(IInstruction.Visitor v) throws IllegalArgumentException {
if (v == null) {
throw new IllegalArgumentException();
}
v.visitGet(this);
}
@Override
public boolean isPEI() {
return !isStatic();
}
/** Java does not permit this */
@Override
public boolean isAddressOf() {
return false;
}
}
| 4,271
| 22.344262
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/GotoInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import java.util.Arrays;
/** This class represents goto and goto_w instructions. */
public final class GotoInstruction extends Instruction {
private final int[] label;
private GotoInstruction(int label) {
super(OP_goto);
int[] l = {label};
this.label = l;
}
private static final GotoInstruction[] preallocated = preallocate();
private static GotoInstruction[] preallocate() {
GotoInstruction[] r = new GotoInstruction[256];
Arrays.setAll(r, GotoInstruction::new);
return r;
}
public static GotoInstruction make(int label) {
if (0 <= label && label < preallocated.length) {
return preallocated[label];
} else {
return new GotoInstruction(label);
}
}
@Override
public boolean isFallThrough() {
return false;
}
@Override
public int[] getBranchTargets() {
return label;
}
public int getLabel() {
return label[0];
}
@Override
public IInstruction redirectTargets(int[] targetMap) throws IllegalArgumentException {
if (targetMap == null) {
throw new IllegalArgumentException("targetMap is null");
}
try {
return make(targetMap[label[0]]);
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Illegal target map", e);
}
}
@Override
public boolean equals(Object o) {
if (o instanceof GotoInstruction) {
GotoInstruction i = (GotoInstruction) o;
return i.label == label;
} else {
return false;
}
}
@Override
public int hashCode() {
return label[0] * 1348091 + 18301;
}
@Override
public String toString() {
return "Goto(" + getLabel() + ')';
}
@Override
public void visit(IInstruction.Visitor v) throws IllegalArgumentException {
if (v == null) {
throw new IllegalArgumentException();
}
v.visitGoto(this);
}
@Override
public boolean isPEI() {
return false;
}
}
| 2,329
| 22.3
| 88
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IArrayLoadInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IArrayLoadInstruction extends IInstruction, IMemoryOperation {
String getType();
}
| 510
| 29.058824
| 79
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IArrayStoreInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IArrayStoreInstruction extends IInstruction {
String getType();
}
| 493
| 28.058824
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IBinaryOpInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IBinaryOpInstruction extends IInstruction {
interface IOperator {}
IBinaryOpInstruction.IOperator getOperator();
String getType();
enum Operator implements IBinaryOpInstruction.IOperator {
ADD,
SUB,
MUL,
DIV,
REM,
AND,
OR,
XOR;
@Override
public String toString() {
return super.toString().toLowerCase();
}
}
boolean throwsExceptionOnOverflow();
boolean isUnsigned();
}
| 864
| 20.097561
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IComparisonInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IComparisonInstruction extends IInstruction {
enum Operator {
CMP,
CMPL,
CMPG;
@Override
public String toString() {
return super.toString().toLowerCase();
}
}
Operator getOperator();
String getType();
}
| 669
| 21.333333
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IConditionalBranchInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IConditionalBranchInstruction extends IInstruction {
interface IOperator {}
enum Operator implements IConditionalBranchInstruction.IOperator {
EQ,
NE,
LT,
GE,
GT,
LE;
@Override
public String toString() {
return super.toString().toLowerCase();
}
}
int getTarget();
IOperator getOperator();
String getType();
}
| 793
| 20.459459
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IConversionInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IConversionInstruction extends IInstruction {
String getFromType();
String getToType();
boolean throwsExceptionOnOverflow();
}
| 560
| 25.714286
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IGetInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IGetInstruction extends IInstruction, IMemoryOperation {
String getClassType();
String getFieldName();
String getFieldType();
boolean isStatic();
}
| 584
| 24.434783
| 73
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IInstanceofInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IInstanceofInstruction extends IInstruction {
boolean firstClassType();
String getType();
}
| 522
| 26.526316
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/**
* @author sfink
* <p>Basic functionality we expect of any instruction implementation
*/
public interface IInstruction {
/** This class is used by IInstruction.visit to dispatch based on the instruction type. */
@SuppressWarnings("unused")
abstract class Visitor {
public void visitConstant(ConstantInstruction instruction) {}
public void visitGoto(GotoInstruction instruction) {}
public void visitLocalLoad(ILoadInstruction instruction) {}
public void visitLocalStore(IStoreInstruction instruction) {}
public void visitArrayLoad(IArrayLoadInstruction instruction) {}
public void visitArrayStore(IArrayStoreInstruction instruction) {}
public void visitPop(PopInstruction instruction) {}
public void visitDup(DupInstruction instruction) {}
public void visitSwap(SwapInstruction instruction) {}
public void visitBinaryOp(IBinaryOpInstruction instruction) {}
public void visitUnaryOp(IUnaryOpInstruction instruction) {}
public void visitShift(IShiftInstruction instruction) {}
public void visitConversion(IConversionInstruction instruction) {}
public void visitComparison(IComparisonInstruction instruction) {}
public void visitConditionalBranch(IConditionalBranchInstruction instruction) {}
public void visitSwitch(SwitchInstruction instruction) {}
public void visitReturn(ReturnInstruction instruction) {}
public void visitGet(IGetInstruction instruction) {}
public void visitPut(IPutInstruction instruction) {}
public void visitInvoke(IInvokeInstruction instruction) {}
public void visitNew(NewInstruction instruction) {}
public void visitArrayLength(ArrayLengthInstruction instruction) {}
public void visitThrow(ThrowInstruction instruction) {}
public void visitMonitor(MonitorInstruction instruction) {}
public void visitCheckCast(ITypeTestInstruction instruction) {}
public void visitInstanceof(IInstanceofInstruction instruction) {}
public void visitLoadIndirect(ILoadIndirectInstruction instruction) {}
public void visitStoreIndirect(IStoreIndirectInstruction instruction) {}
}
/** @return true if the instruction can "fall through" to the following instruction */
boolean isFallThrough();
/**
* @return an array containing the labels this instruction can branch to (not including the
* following instruction if this instruction 'falls through')
*/
int[] getBranchTargets();
/**
* @return an Instruction equivalent to this one but with any branch labels updated by looking
* them up in the targetMap array
*/
IInstruction redirectTargets(int[] targetMap);
/** @return the number of values this instruction pops off the working stack */
int getPoppedCount();
/**
* Computes the type of data pushed onto the stack, or null if none is pushed.
*
* @param poppedTypesToCheck the types of the data popped off the stack by this instruction; if
* poppedTypes is null, then we don't know the incoming stack types and the result of this
* method may be less accurate
*/
String getPushedType(String[] poppedTypesToCheck);
/**
* @return the JVM word size of the value this instruction pushes onto the stack, or 0 if this
* instruction doesn't push anything onto the stack.
*/
byte getPushedWordSize();
/**
* Apply a Visitor to this instruction. We invoke the appropriate Visitor method according to the
* type of this instruction.
*/
void visit(IInstruction.Visitor v);
/** Subclasses must implement toString. */
@Override
String toString();
/**
* PEI == "Potentially excepting instruction"
*
* @return true iff this instruction might throw an exception
*/
boolean isPEI();
}
| 4,172
| 31.348837
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IInvokeInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/**
* @author sfink
* <p>Basic functionality any invoke instruction should provide
*/
public interface IInvokeInstruction extends IInstruction {
/** @return one of BytecodeConstants.INVOKE[SPECIAL|VIRTUAL|STATIC|INTERFACE] */
IDispatch getInvocationCode();
String getMethodSignature();
String getMethodName();
String getClassType();
interface IDispatch {
boolean hasImplicitThis();
}
enum Dispatch implements IDispatch {
VIRTUAL,
SPECIAL,
INTERFACE,
STATIC {
@Override
public boolean hasImplicitThis() {
return false;
}
};
@Override
public boolean hasImplicitThis() {
return true;
}
}
}
| 1,100
| 21.02
| 82
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ILoadIndirectInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface ILoadIndirectInstruction extends IInstruction {}
| 473
| 32.857143
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ILoadInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface ILoadInstruction extends IInstruction, IMemoryOperation {
int getVarIndex();
String getType();
}
| 527
| 26.789474
| 74
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IMemoryOperation.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IMemoryOperation {
/**
* Denotes whether this instruction is taking the address of whatever location it refers to.
*
* @return whether this instruction is taking the address of a location
*/
boolean isAddressOf();
}
| 657
| 28.909091
| 94
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IPutInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IPutInstruction extends IInstruction {
String getClassType();
String getFieldType();
String getFieldName();
boolean isStatic();
}
| 566
| 23.652174
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IShiftInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IShiftInstruction extends IInstruction {
enum Operator implements IBinaryOpInstruction.IOperator {
SHL,
SHR,
USHR;
}
Operator getOperator();
String getType();
boolean isUnsigned();
}
| 633
| 22.481481
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IStoreIndirectInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IStoreIndirectInstruction extends IInstruction {
String getType();
}
| 496
| 28.235294
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IStoreInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IStoreInstruction extends IInstruction {
int getVarIndex();
String getType();
}
| 510
| 25.894737
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ITypeTestInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface ITypeTestInstruction extends IInstruction {
boolean firstClassTypes();
String[] getTypes();
}
| 524
| 26.631579
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IUnaryOpInstruction.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IUnaryOpInstruction extends IInstruction {
interface IOperator {}
enum Operator implements IOperator {
NEG;
@Override
public String toString() {
return super.toString().toLowerCase();
}
}
IOperator getOperator();
String getType();
}
| 694
| 22.166667
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/IndirectionData.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public interface IndirectionData {
int[] indirectlyReadLocals(int instructionIndex);
int[] indirectlyWrittenLocals(int instructionIndex);
}
| 553
| 28.157895
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/InstanceofInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents instanceof instructions. */
public final class InstanceofInstruction extends Instruction implements IInstanceofInstruction {
private final String type;
private InstanceofInstruction(String type) {
super(OP_instanceof);
this.type = type;
if (type == null) {
throw new IllegalArgumentException("null type");
}
}
public static InstanceofInstruction make(String type) {
return new InstanceofInstruction(type);
}
@Override
public boolean equals(Object o) {
if (o instanceof InstanceofInstruction) {
InstanceofInstruction i = (InstanceofInstruction) o;
return i.type.equals(type);
} else {
return false;
}
}
@Override
public int hashCode() {
return 31980190 + type.hashCode();
}
@Override
public int getPoppedCount() {
return 1;
}
@Override
public String getType() {
return type;
}
@Override
public String getPushedType(String[] types) {
return TYPE_boolean;
}
@Override
public byte getPushedWordSize() {
return 1;
}
@Override
public void visit(IInstruction.Visitor v) throws IllegalArgumentException {
if (v == null) {
throw new IllegalArgumentException();
}
v.visitInstanceof(this);
}
@Override
public String toString() {
return "Instanceof(" + type + ')';
}
@Override
public boolean isPEI() {
return false;
}
@Override
public boolean firstClassType() {
return false;
}
}
| 1,894
| 20.781609
| 96
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/Instruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/**
* Instructions are immutable objects. It is always legal to take a reference to an instruction and
* use it in any other context. You never need to copy instructions. It is often a good idea to keep
* references to frequently used instructions cached in static fields.
*
* <p>To generate an Instruction, locate the class for the instruction you want to generate, and
* invoke the appropriate "make" static method on that class. The Util class has convenience methods
* for creating some of the more complex instructions using reflection to fill in some of the needed
* information (e.g., makeGet, makePut, makeInvoke).
*
* <p>We simplify the bytecode instruction set a bit using some preprocessing and postprocessing:
*
* <p>There is no 'iinc' instruction. 'iinc' instructions are expanded to 'iload; bipush; iadd;
* istore' during decoding and reassembled during compilation.
*
* <p>There are no 'jsr' or 'ret' instructions. Bytecode subroutines are expanded inline during
* decoding.
*
* <p>There are no 'ifeq', 'ifne', 'ifgt', 'ifge', 'iflt', 'ifle' instructions. These instructions
* are expanded to 'bipush 0; if_icmp' during decoding and reassembled during compilation.
*
* <p>There are no 'ifnull' or 'ifnonnull' instructions. These instructions are expanded to
* 'aconst_null; if_acmp' during decoding and reassembled during compilation.
*
* <p>All Java values, including longs and doubles, occupy just one word on the stack. Places where
* the JVM assumes differently are fixed up during compilation. However, longs and double still take
* up two local variable slots (this usually doesn't matter to instrumentation).
*
* <p>Control transfer instructions refer to target instructions using integers. These integers are
* usually indices into an array of instructions.
*/
public abstract class Instruction implements Constants, Cloneable, IInstruction {
public static final int[] noInstructions = new int[0];
/** Ensure that only this package can subclass Instruction. */
Instruction(short opcode) {
this.opcode = opcode;
}
final short opcode;
/** @return true if the instruction can "fall through" to the following instruction */
@Override
public boolean isFallThrough() {
return true;
}
/**
* @return an array containing the labels this instruction can branch to (not including the
* following instruction if this instruction 'falls through')
*/
@Override
public int[] getBranchTargets() {
return noInstructions;
}
/**
* @return an Instruction equivalent to this one but with any branch labels updated by looking
* them up in the targetMap array
*/
@Override
public IInstruction redirectTargets(int[] targetMap) {
return this;
}
/** @return the number of values this instruction pops off the working stack */
@Override
public int getPoppedCount() {
return 0;
}
/** @return the opcode selected for this instruction, or -1 if we don't know it yet */
public final short getOpcode() {
return opcode;
}
/**
* Computes the type of data pushed onto the stack, or null if none is pushed.
*
* @param poppedTypesToCheck the types of the data popped off the stack by this instruction; if
* poppedTypes is null, then we don't know the incoming stack types and the result of this
* method may be less accurate
*/
@Override
public String getPushedType(String[] poppedTypesToCheck) {
return null;
}
/**
* @return the JVM word size of the value this instruction pushes onto the stack, or 0 if this
* instruction doesn't push anything onto the stack.
*/
@Override
public byte getPushedWordSize() {
return 0;
}
/**
* Apply a Visitor to this instruction. We invoke the appropriate Visitor method according to the
* type of this instruction.
*/
@Override
public abstract void visit(IInstruction.Visitor v);
/** Subclasses must implement toString. */
@Override
public abstract String toString();
/** We're immutable so there's no need to clone any Instruction object. */
@Override
public final Object clone() {
return this;
}
}
| 4,569
| 34.984252
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/InvokeDynamicInstruction.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class InvokeDynamicInstruction extends Instruction implements IInvokeInstruction {
protected BootstrapMethod bootstrap;
protected String methodName;
protected String methodType;
public InvokeDynamicInstruction(
short opcode, BootstrapMethod bootstrap, String methodName, String methodType) {
super(opcode);
this.bootstrap = bootstrap;
this.methodName = methodName;
this.methodType = methodType;
}
ConstantPoolReader getLazyConstantPool() {
return null;
}
@Override
public boolean isPEI() {
return true;
}
@Override
public Dispatch getInvocationCode() {
int invokeType = getBootstrap().invokeType();
switch (invokeType) {
case 5:
return Dispatch.VIRTUAL;
case 6:
return Dispatch.STATIC;
case 7:
return Dispatch.SPECIAL;
case 9:
return Dispatch.INTERFACE;
default:
throw new Error("unexpected dynamic invoke type " + invokeType);
}
}
@Override
public final int getPoppedCount() {
return (getInvocationCode().equals(Dispatch.STATIC) ? 0 : 1)
+ Util.getParamsCount(getMethodSignature());
}
@Override
public final String getPushedType(String[] types) {
String t = Util.getReturnType(getMethodSignature());
if (t.equals(Constants.TYPE_void)) {
return null;
} else {
return t;
}
}
@Override
public final byte getPushedWordSize() {
String t = getMethodSignature();
int index = t.lastIndexOf(')');
return Util.getWordSize(t, index + 1);
}
public BootstrapMethod getBootstrap() {
return bootstrap;
}
@Override
public String getMethodSignature() {
return methodType;
}
@Override
public String getMethodName() {
return methodName;
}
@Override
public String getClassType() {
return 'L' + getBootstrap().methodClass();
}
@Override
public void visit(Visitor v) {
v.visitInvoke(this);
}
@Override
public String toString() {
return "InvokeDynamic [" + getBootstrap() + "] " + getMethodName() + getMethodSignature();
}
static final class Lazy extends InvokeDynamicInstruction {
private final ConstantPoolReader cp;
private final int index;
Lazy(short opcode, ConstantPoolReader cp, int index) {
super(opcode, null, null, null);
this.index = index;
this.cp = cp;
}
int getCPIndex() {
return index;
}
@Override
public BootstrapMethod getBootstrap() {
if (bootstrap == null) {
bootstrap = cp.getConstantPoolDynamicBootstrap(index);
}
return bootstrap;
}
@Override
public String getMethodName() {
if (methodName == null) {
methodName = cp.getConstantPoolDynamicName(index);
}
return methodName;
}
@Override
public String getMethodSignature() {
if (methodType == null) {
methodType = cp.getConstantPoolDynamicType(index);
}
return methodType;
}
@Override
ConstantPoolReader getLazyConstantPool() {
return cp;
}
}
public CallSite bootstrap(Class<?> cl)
throws ClassNotFoundException, NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException,
NoSuchFieldException {
ClassLoader classLoader = cl.getClassLoader();
ClassLoader bootstrapCL = classLoader;
Class<?> bootstrapClass =
Class.forName(getBootstrap().methodClass().replace('/', '.'), false, bootstrapCL);
MethodType bt = makeMethodType(bootstrapCL, bootstrap.methodType());
Method bootstrap =
bootstrapClass.getMethod(
this.bootstrap.methodName(),
bt.parameterList().toArray(new Class[bt.parameterCount()]));
Object[] args = new Object[bt.parameterCount()];
Lookup myLookup = MethodHandles.lookup().in(cl);
Field impl_lookup =
Lookup.class.getDeclaredField("IMPL_LOOKUP"); // get the required field via reflections
impl_lookup.setAccessible(true); // set it accessible
Lookup lutrusted =
(Lookup)
impl_lookup.get(
myLookup); // get the value of IMPL_LOOKUP from the Lookup instance and save it in a
// new Lookup object
args[0] = lutrusted;
args[1] = getMethodName();
args[2] = makeMethodType(classLoader, getMethodSignature());
for (int i = 3; i < bt.parameterCount(); i++) {
args[i] = getBootstrap().callArgument(bootstrapCL, i - 3);
}
bootstrap.setAccessible(true);
System.err.println(cl + " : " + bootstrap);
return (CallSite) bootstrap.invoke(null, args);
}
public static MethodType makeMethodType(ClassLoader classLoader, String descriptor)
throws ClassNotFoundException {
String returnType = Util.makeClass(Util.getReturnType(descriptor));
Class<?> returnClass = Class.forName(returnType, false, classLoader);
String[] paramTypes = Util.getParamsTypes(null, descriptor);
Class<?>[] paramClasses = new Class[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
paramClasses[i] = Class.forName(Util.makeClass(paramTypes[i]), false, classLoader);
}
MethodType mt = MethodType.methodType(returnClass, paramClasses);
return mt;
}
static InvokeDynamicInstruction make(ConstantPoolReader cp, int index, int mode) {
if (mode != OP_invokedynamic) {
throw new IllegalArgumentException("Unknown mode: " + mode);
}
return new Lazy((short) mode, cp, index);
}
}
| 6,277
| 27.798165
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/InvokeInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents method invocation instructions. */
public class InvokeInstruction extends Instruction implements IInvokeInstruction {
protected String type;
protected String classType;
protected String methodName;
InvokeInstruction(short opcode, String type, String classType, String methodName) {
super(opcode);
this.type = type;
this.classType = classType;
this.methodName = methodName;
}
public static InvokeInstruction make(
String type, String className, String methodName, Dispatch mode) throws NullPointerException {
if (type == null) {
throw new NullPointerException("type must not be null");
}
if (className == null) {
throw new NullPointerException("className must not be null");
}
if (methodName == null) {
throw new NullPointerException("methodName must not be null");
}
if (mode == null) {
throw new NullPointerException("mode must not be null");
}
short opcode = 0;
switch (mode) {
case VIRTUAL:
opcode = OP_invokevirtual;
break;
case SPECIAL:
opcode = OP_invokespecial;
break;
case STATIC:
opcode = OP_invokestatic;
break;
case INTERFACE:
opcode = OP_invokeinterface;
break;
default:
assert false;
}
return new InvokeInstruction(opcode, type, className, methodName);
}
ConstantPoolReader getLazyConstantPool() {
return null;
}
static final class Lazy extends InvokeInstruction {
private final ConstantPoolReader cp;
private final int index;
Lazy(short opcode, ConstantPoolReader cp, int index) {
super(opcode, null, null, null);
this.index = index;
this.cp = cp;
}
@Override
ConstantPoolReader getLazyConstantPool() {
return cp;
}
int getCPIndex() {
return index;
}
@Override
public String getClassType() {
if (classType == null) {
classType = cp.getConstantPoolMemberClassType(index);
}
return classType;
}
@Override
public String getMethodName() {
if (methodName == null) {
methodName = cp.getConstantPoolMemberName(index);
}
return methodName;
}
@Override
public String getMethodSignature() {
if (type == null) {
type = cp.getConstantPoolMemberType(index);
}
return type;
}
}
static InvokeInstruction make(ConstantPoolReader cp, int index, int mode) {
if (mode < OP_invokevirtual || mode > OP_invokeinterface) {
throw new IllegalArgumentException("Unknown mode: " + mode);
}
return new Lazy((short) mode, cp, index);
}
@Override
public final boolean equals(Object o) {
if (o instanceof InvokeInstruction) {
InvokeInstruction i = (InvokeInstruction) o;
return i.getMethodSignature().equals(getMethodSignature())
&& i.getClassType().equals(getClassType())
&& i.getMethodName().equals(getMethodName())
&& i.opcode == opcode;
} else {
return false;
}
}
@Override
public String getClassType() {
return classType;
}
@Override
public String getMethodName() {
return methodName;
}
@Override
public String getMethodSignature() {
return type;
}
public final int getInvocationMode() {
return opcode;
}
public final String getInvocationModeString() {
switch (opcode) {
case Constants.OP_invokestatic:
return "STATIC";
case Constants.OP_invokeinterface:
return "INTERFACE";
case Constants.OP_invokespecial:
return "SPECIAL";
case Constants.OP_invokevirtual:
return "VIRTUAL";
default:
throw new Error("Unknown mode: " + opcode);
}
}
@Override
public final int hashCode() {
return getMethodSignature().hashCode()
+ 9011 * getClassType().hashCode()
+ 317 * getMethodName().hashCode()
+ opcode * 3188;
}
@Override
public final int getPoppedCount() {
return (opcode == Constants.OP_invokestatic ? 0 : 1)
+ Util.getParamsCount(getMethodSignature());
}
@Override
public final String getPushedType(String[] types) {
String t = Util.getReturnType(getMethodSignature());
if (t.equals(Constants.TYPE_void)) {
return null;
} else {
return t;
}
}
@Override
public final byte getPushedWordSize() {
String t = getMethodSignature();
int index = t.lastIndexOf(')');
return Util.getWordSize(t, index + 1);
}
@Override
public final void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitInvoke(this);
}
@Override
public final String toString() {
return "Invoke("
+ getInvocationModeString()
+ ','
+ getClassType()
+ ','
+ getMethodName()
+ ','
+ getMethodSignature()
+ ')';
}
@Override
public boolean isPEI() {
return true;
}
@Override
public Dispatch getInvocationCode() {
switch (opcode) {
case Constants.OP_invokestatic:
return Dispatch.STATIC;
case Constants.OP_invokeinterface:
return Dispatch.INTERFACE;
case Constants.OP_invokespecial:
return Dispatch.SPECIAL;
case Constants.OP_invokevirtual:
return Dispatch.VIRTUAL;
default:
throw new Error("Unknown mode: " + opcode);
}
}
}
| 5,831
| 23.817021
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/LoadInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents local variable load instructions. */
public final class LoadInstruction extends Instruction implements ILoadInstruction {
private final int index;
private LoadInstruction(short opcode, int index) {
super(opcode);
this.index = index;
}
private static final LoadInstruction[] preallocated = preallocate();
private static LoadInstruction[] preallocate() {
LoadInstruction[] r = new LoadInstruction[5 * 16];
for (int p = 0; p < 5; p++) {
for (int i = 0; i < 4; i++) {
r[p * 16 + i] = new LoadInstruction((short) (OP_iload_0 + i + p * 4), i);
}
for (int i = 4; i < 16; i++) {
r[p * 16 + i] = new LoadInstruction((short) (OP_iload + p), i);
}
}
return r;
}
public static LoadInstruction make(String type, int index) throws IllegalArgumentException {
int t = Util.getTypeIndex(type);
if (t < 0 || t > TYPE_Object_index) {
throw new IllegalArgumentException("Cannot load local of type " + type);
}
if (index < 16) {
return preallocated[t * 16 + index];
} else {
return new LoadInstruction((short) (OP_iload + t), index);
}
}
/** @return the index of the local variable loaded */
@Override
public int getVarIndex() {
return index;
}
@Override
public String getType() {
if (opcode < OP_iload_0) {
return indexedTypes[opcode - OP_iload];
} else {
return indexedTypes[(opcode - OP_iload_0) / 4];
}
}
@Override
public String getPushedType(String[] types) {
return getType();
}
@Override
public byte getPushedWordSize() {
return Util.getWordSize(getType());
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitLocalLoad(this);
}
@Override
public boolean equals(Object o) {
if (o instanceof LoadInstruction) {
LoadInstruction i = (LoadInstruction) o;
return i.index == index && i.opcode == opcode;
} else {
return false;
}
}
@Override
public int hashCode() {
return opcode + index * 19801901;
}
@Override
public String toString() {
return "LocalLoad(" + getType() + ',' + index + ')';
}
@Override
public boolean isPEI() {
return false;
}
/**
* Java does not permit this.
*
* @see com.ibm.wala.shrike.shrikeBT.IMemoryOperation#isAddressOf()
*/
@Override
public boolean isAddressOf() {
return false;
}
}
| 2,862
| 24.114035
| 94
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/MethodData.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
/**
* This class is a container for a bunch of information that we might know about a method. It's here
* for convenience so users can just pass one MethodData around instead of passing around an array
* of instructions, an array of exception handler lists, etc.
*
* <p>It also provides a place to hang annotations. We provide a table mapping abstract "keys" to
* annotation objects. We also provide an invalidation protocol so that the annotation objects can
* be notified of code changes and react appropriately. This is useful for caching analysis results
* for a method.
*/
public final class MethodData {
private final HashMap<Object, Results> map = new HashMap<>();
private final int access;
private final String classType;
private final String name;
private final String signature;
private IInstruction[] instructions;
private ExceptionHandler[][] handlers;
private int[] instructionsToBytecodes;
private boolean hasChanged = false;
/**
* Create information for a method, with no exception handlers and a dummy mapping of instructions
* to original bytecodes.
*
* @param access the access flags
* @param classType the class in which the method is defined, in JVM type format (e.g.,
* Ljava/lang/Object;)
* @param name the method name
* @param signature the method signature, in JVM type format (e.g., (ILjava/lang/Object;)V)
* @param instructions the instructions making up the method
*/
public static MethodData makeWithDefaultHandlersAndInstToBytecodes(
int access, String classType, String name, String signature, IInstruction[] instructions) {
ExceptionHandler[][] handlers = new ExceptionHandler[instructions.length][];
Arrays.fill(handlers, new ExceptionHandler[0]);
int[] i2b = new int[instructions.length];
Arrays.setAll(i2b, i -> i);
return new MethodData(access, classType, name, signature, instructions, handlers, i2b);
}
/**
* Gather the information for a method "from scratch".
*
* @param access the access flags
* @param classType the class in which the method is defined, in JVM type format (e.g.,
* Ljava/lang/Object;)
* @param name the method name
* @param signature the method signature, in JVM type format (e.g., (ILjava/lang/Object;)V)
* @param instructions the instructions making up the method
* @param handlers a list of exception handlers for each instruction
* @param instructionsToBytecodes a map stating, for each instruction, the offset of the original
* bytecode instruction(s) giving rise to this instruction
*/
public MethodData(
int access,
String classType,
String name,
String signature,
IInstruction[] instructions,
ExceptionHandler[][] handlers,
int[] instructionsToBytecodes) {
this.classType = classType;
this.access = access;
this.name = name;
this.signature = signature;
this.instructions = instructions;
this.handlers = handlers;
this.instructionsToBytecodes = instructionsToBytecodes;
if (instructions == null) {
throw new IllegalArgumentException("Instruction array cannot be null");
}
if (handlers == null) {
throw new IllegalArgumentException("Handler array cannot be null");
}
if (instructionsToBytecodes == null) {
throw new IllegalArgumentException("InstructionToBytecodes array cannot be null");
}
if (instructions.length != handlers.length) {
throw new IllegalArgumentException(
"Handlers array must be the same length as the instructions");
}
if (instructions.length != instructionsToBytecodes.length) {
throw new IllegalArgumentException(
"Bytecode map array must be the same length as the instructions");
}
}
/**
* Gather the information for a method after it has been decoded.
*
* @param d the decoder which has decoded the method
* @param access the access flags
* @param classType the class in which the method is defined, in JVM type format (e.g.,
* Ljava/lang/Object;)
* @param name the method name
* @param signature the method signature, in JVM type format (e.g., (ILjava/lang/Object;)V)
* @throws NullPointerException if d is null
*/
public MethodData(Decoder d, int access, String classType, String name, String signature)
throws NullPointerException {
this(
access,
classType,
name,
signature,
d.getInstructions(),
d.getHandlers(),
d.getInstructionsToBytecodes());
}
public void setHasChanged() {
hasChanged = true;
}
/** @return the method signature, in JVM format */
public String getSignature() {
return signature;
}
/** @return the method name */
public String getName() {
return name;
}
/** @return the method access flags */
public int getAccess() {
return access;
}
/** @return the JVM type for the class defining the method (e.g., Ljava/lang/Object;) */
public String getClassType() {
return classType;
}
/** @return whether or not the method is static */
public boolean getIsStatic() {
return (access & Constants.ACC_STATIC) != 0;
}
/** @return whether or not the method is synchronized */
public boolean getIsSynchronized() {
return (access & Constants.ACC_SYNCHRONIZED) != 0;
}
/** @return the exception handler lists */
public ExceptionHandler[][] getHandlers() {
return handlers;
}
/** @return the instruction array */
public IInstruction[] getInstructions() {
return instructions;
}
/** @return the map from instructions to bytecode offsets */
public int[] getInstructionsToBytecodes() {
return instructionsToBytecodes;
}
/**
* Annotation objects implement this Results interface. The Results interface is used to notify an
* annotation that the method code has been updated.
*/
public interface Results {
/**
* This method is called just before the code for a method changes. The existing instructions,
* handlers, etc can be read from the current info.
*
* @param info the method data this annotation is attached to
* @param newInstructions the instructions the method will change to
* @param newHandlers the handler lists the method will change to
* @param newInstructionMap the instructions-to-bytecodes map the method will change to
* @return true to remove the object from the info set, for example because the annotation is
* now invalid
*/
boolean notifyUpdate(
MethodData info,
IInstruction[] newInstructions,
ExceptionHandler[][] newHandlers,
int[] newInstructionMap);
}
/**
* Get the annotation for the given key.
*
* @return the annotation or null if there isn't one
*/
public Results getInfo(Object key) {
return map.get(key);
}
/** Set the annotation for the given key. */
public void putInfo(Object key, Results value) {
map.put(key, value);
}
void update(
IInstruction[] instructions,
ExceptionHandler[][] handlers,
int[] newInstructionMap,
int[] instructionsToBytecodes) {
for (Iterator<Object> i = map.keySet().iterator(); i.hasNext(); ) {
Object key = i.next();
Results r = map.get(key);
if (r.notifyUpdate(this, instructions, handlers, newInstructionMap)) {
i.remove();
}
}
this.instructions = instructions;
this.handlers = handlers;
this.instructionsToBytecodes = instructionsToBytecodes;
hasChanged = true;
}
/** @return true iff the code has been updated at least once */
public boolean getHasChanged() {
return hasChanged;
}
@Override
public String toString() {
return getClassType() + '.' + getName() + getSignature();
}
}
| 8,304
| 31.956349
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/MethodEditor.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IdentityHashMap;
/**
* The MethodEditor is the core of the ShrikeBT code rewriting mechanism. To rewrite code, construct
* a MethodEditor initialized with the intial code for the method. Then perform a series of passes.
* In each pass you call beginPass(), insert a number of patches using the insert...() or
* replace...() methods, then optionally call applyPatches() to update the code with your changes,
* then call endPass(). The end of each pass updates the code in the MethodData that you passed in,
* so the new code can be extracted from that MethodData object. Note that if applyPatches() is not
* called, or it is called but no patches had been inserted, then the code will not be updated and
* that pass is essentially aborted.
*
* <p>A patch is simply a subclass of MethodEditor.Patch, representing a code sequence to insert
* into the method. Each patch class implements one method, emitTo(), which writes the patch code
* into the code stream using the provided MethodEditor.Output instance. Anonymous inner classes are
* very useful for writing patches.
*
* <p>Patches can be inserted at the following points:
*
* <ul>
* <li>Before the start of the method
* <li>Before or after a particular instruction
* <li>Replacing a particular instruction
* <li>Handling an exception on a particular instruction
* <li>Handling an exception anywhere in the method
* <li>After the end of the method, where code will not normally be executed, but can be branched
* to by another patch
* </ul>
*
* Patch application is deterministic; if two patches are applied at the same point, then the order
* of application determines the order of code generation, in a way specified by the particular
* application point. See the patch application methods below.
*
* <p>MethodEditor relies on labels. A label is an integer representing a point in the code. Labels
* are valid only during a single pass; at the end of each pass, instructions are reordered and old
* labels become invalid. At the beginning of a pass every instruction in the instructions array is
* labelled with the index of that instruction in the array. During instrumentation new labels can
* be allocated by calling MethodEditor.allocateLabel(); control instructions can be created
* referring to these new labels or the existing labels. At the end of a pass, as patch code is
* spliced into the method body, all instructions are updated to refer to the new labels which are
* simply the indices of instructions in the instruction array.
*/
public final class MethodEditor {
private static final ExceptionHandler[] noHandlers = new ExceptionHandler[0];
/** Records which original bytecode instruction each Instruction belongs to. */
private int[] instructionsToBytecodes;
private IInstruction[] instructions;
private ExceptionHandler[][] handlers;
private final MethodData methodInfo;
// working
private static final int BEFORE_PASS = 0x01;
private static final int DURING_PASS = 0x02;
private static final int EMITTING_CODE = 0x04;
private static final int BEFORE_END_PASS = 0x08;
private int state = BEFORE_PASS;
private int patchCount;
private Patch[] beforePatches;
private Patch[] afterPatches;
private Patch[] lastAfterPatches;
private Patch[] replacementPatches;
private Patch methodStartPatches;
private Patch afterMethodPatches;
private HandlerPatch[] instructionHandlerPatches;
private HandlerPatch methodHandlerPatches;
private int nextLabel;
/** This patch lets us stuff an exception handler into the code. */
private static class HandlerPatch {
final HandlerPatch next;
final String catchClass;
final int label;
final Patch patch;
HandlerPatch(HandlerPatch next, String catchClass, int label, Patch patch) {
this.next = next;
this.catchClass = catchClass;
this.label = label;
this.patch = patch;
}
}
/**
* Build an editor for the given method. This editor will write back its changes to the method
* info.
*
* @throws IllegalArgumentException if info is null
*/
public MethodEditor(MethodData info) {
if (info == null) {
throw new IllegalArgumentException("info is null");
}
methodInfo = info;
instructionsToBytecodes = info.getInstructionsToBytecodes();
instructions = info.getInstructions();
handlers = info.getHandlers();
}
/**
* Build an editor for specific method data. After patching the code you can retrieve the new
* code, handlers and instructions-to-bytecode-offsets map.
*/
public MethodEditor(
Instruction[] instructions, ExceptionHandler[][] handlers, int[] instructionsToBytecodes) {
if (instructions == null) {
throw new IllegalArgumentException("null instructions");
}
if (handlers == null) {
throw new IllegalArgumentException("null handlers");
}
methodInfo = null;
this.instructionsToBytecodes = instructionsToBytecodes;
this.instructions = instructions;
this.handlers = handlers;
}
private void verifyState(int state) {
if ((state & this.state) == 0) {
throw new IllegalArgumentException(getStateMessage(state));
}
}
private static String getStateMessage(int state) {
switch (state) {
case BEFORE_PASS:
return "This operation can only be performed before or after an editing pass";
case DURING_PASS:
return "This operation can only be performed during an editing pass";
case EMITTING_CODE:
return "This operation can only be performed while applying patches and emitting code";
case BEFORE_END_PASS:
return "This operation can only be performed after applying patches";
default:
return "This operation cannot be performed in this state";
}
}
/** @return the current handler array */
public ExceptionHandler[][] getHandlers() {
verifyState(BEFORE_PASS | DURING_PASS);
return handlers;
}
/** @return the current instruction array */
public IInstruction[] getInstructions() {
verifyState(BEFORE_PASS | DURING_PASS);
return instructions;
}
/** @return the current instructions-to-bytecode-offsets map */
public int[] getInstructionsToBytecodes() {
verifyState(BEFORE_PASS | DURING_PASS);
return instructionsToBytecodes;
}
static ExceptionHandler[] mergeHandlers(ExceptionHandler[] h1, ExceptionHandler[] h2) {
if (h1.length == 0) {
return h2;
} else if (h2.length == 0) {
return h1;
} else {
ExceptionHandler[] r = Arrays.copyOf(h1, h1.length + h2.length);
System.arraycopy(h2, 0, r, h1.length, h2.length);
return r;
}
}
/** Output is the interface that patches use to emit their code into a method body. */
public static final class Output {
final ArrayList<IInstruction> newInstructions = new ArrayList<>();
final ArrayList<ExceptionHandler[]> newInstructionHandlers = new ArrayList<>();
int[] instructionsToBytecodes = new int[10];
final int[] labelDefs;
ExceptionHandler[] additionalHandlers;
int originalBytecode;
boolean codeChanged = false;
Output(int numLabels) {
labelDefs = new int[numLabels];
}
/**
* Emit a label definition at the current point in the code. The label must have been previously
* allocated using MethodEditor.allocateLabel.
*/
public void emitLabel(int label) {
labelDefs[label] = newInstructions.size();
}
/** Emit an instruction at the current point in the code. */
public void emit(Instruction i) {
codeChanged = true;
internalEmitInstruction(i);
}
/** Emit an instruction with some exception handlers at the current point in the code. */
public void emit(Instruction i, ExceptionHandler[] handlers) {
codeChanged = true;
int s = newInstructions.size();
if (s + 1 > instructionsToBytecodes.length) {
instructionsToBytecodes =
Arrays.copyOf(instructionsToBytecodes, instructionsToBytecodes.length * 2);
}
instructionsToBytecodes[s] = originalBytecode;
newInstructions.add(i);
newInstructionHandlers.add(mergeHandlers(handlers, additionalHandlers));
}
void internalEmitInstruction(IInstruction i) {
int s = newInstructions.size();
if (s + 1 > instructionsToBytecodes.length) {
instructionsToBytecodes =
Arrays.copyOf(instructionsToBytecodes, instructionsToBytecodes.length * 2);
}
instructionsToBytecodes[s] = originalBytecode;
newInstructions.add(i);
newInstructionHandlers.add(additionalHandlers);
}
/** Emit a list of instructions at the current point in the code. */
public void emit(Instruction[] instrs) {
emit(instrs, noHandlers);
}
/**
* Emit a list of instructions with some exception handlers at the current point in the code.
* All the instructions are covered by all the handlers.
*/
public void emit(Instruction[] instrs, ExceptionHandler[] handlers) {
if (instrs.length == 0) {
return;
}
codeChanged = true;
int s = newInstructions.size();
if (s + instrs.length > instructionsToBytecodes.length) {
instructionsToBytecodes =
Arrays.copyOf(
instructionsToBytecodes, instructionsToBytecodes.length * 2 + instrs.length);
}
ExceptionHandler[] hs = mergeHandlers(handlers, additionalHandlers);
for (int i = 0; i < instrs.length; i++) {
instructionsToBytecodes[s + i] = originalBytecode;
newInstructions.add(instrs[i]);
newInstructionHandlers.add(hs);
}
}
}
/** This class is subclassed for each kind of patch that you want to apply. */
public abstract static class Patch {
Patch next;
public Patch() {}
final Patch insert(Patch next) {
this.next = next;
return this;
}
/** Override this method to emit the code for your patch. */
public abstract void emitTo(Output w);
}
/** This must be called before inserting any patches. */
public void beginPass() {
verifyState(BEFORE_PASS);
state = DURING_PASS;
nextLabel = instructions.length;
beforePatches = new Patch[instructions.length];
afterPatches = new Patch[instructions.length];
lastAfterPatches = new Patch[instructions.length];
replacementPatches = new Patch[instructions.length];
instructionHandlerPatches = new HandlerPatch[instructions.length];
methodStartPatches = null;
afterMethodPatches = null;
methodHandlerPatches = null;
patchCount = 0;
}
/** This must be called after inserting any patches. */
public void endPass() {
state = BEFORE_PASS;
// lose references to the stored patches so they can be garbage collected
beforePatches = null;
afterPatches = null;
lastAfterPatches = null;
replacementPatches = null;
instructionHandlerPatches = null;
methodStartPatches = null;
afterMethodPatches = null;
methodHandlerPatches = null;
}
/** Allocate a fresh label. This must be called during a pass and not during code emission. */
public int allocateLabel() throws IllegalArgumentException {
verifyState(DURING_PASS);
return nextLabel++;
}
/**
* Insert code to be executed whenever the method is entered. This code is not protected by any
* exception handlers (other than handlers declared in the patch).
*
* <p>When multiple 'start' patches are given, the last one added is first in execution order.
*
* @throws IllegalArgumentException if p is null
*/
public void insertAtStart(Patch p) {
if (p == null) {
throw new IllegalArgumentException("p is null");
}
verifyState(DURING_PASS);
methodStartPatches = p.insert(methodStartPatches);
patchCount++;
}
/**
* Insert code to be executed before the instruction. Branches to the instruction will branch to
* this code. Exception handlers that cover the instruction will be extended to cover the patch.
*
* <p>When multiple 'before' patches are given, the last one added is first in execution order.
*
* @throws IllegalArgumentException if p is null
*/
public void insertBefore(int i, Patch p) {
if (p == null) {
throw new IllegalArgumentException("p is null");
}
verifyState(DURING_PASS);
beforePatches[i] = p.insert(beforePatches[i]);
patchCount++;
}
/**
* Insert code to be executed after the instruction. This code will only execute if the
* instruction "falls through". For example, code inserted after a "goto" will never be executed.
* Likewise if the instruction throws an execution the 'after' code will not be executed.
* Exception handlers that cover the instruction will be extended to cover the patch.
*
* <p>When multiple 'after' patches are given, the last one added is LAST in execution order.
*/
public void insertAfter(int i, Patch p) {
verifyState(DURING_PASS);
try {
if (afterPatches[i] == null) {
lastAfterPatches[i] = afterPatches[i] = p.insert(null);
} else {
lastAfterPatches[i].next = p;
lastAfterPatches[i] = p.insert(null);
}
patchCount++;
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid i", e);
}
}
/**
* Insert code to replace the instruction. Exception handlers that cover the instruction will
* cover the patch.
*
* <p>Multiple replacements are not allowed.
*
* @throws NullPointerException if p is null
* @throws IllegalArgumentException if p is null
*/
public void replaceWith(int i, Patch p) throws NullPointerException {
if (p == null) {
throw new IllegalArgumentException("p is null");
}
verifyState(DURING_PASS);
if (replacementPatches[i] != null) {
throw new IllegalArgumentException("Instruction " + i + " cannot be replaced more than once");
}
replacementPatches[i] = p.insert(null);
patchCount++;
}
/**
* An "instruction exception handler" handles exceptions generated by a specific instruction
* (including patch code that may be inserted before, after, or instead of the instruction in this
* pass). If the patch code falls through, control resumes with the next instruction. This
* exception handler handles exceptions before any exception handler already attached to the
* instruction. Furthermore, the patch itself is covered by the exception handlers already
* attached to the instruction.
*
* <p>If multiple instruction exception handlers are given, then the last one added handles the
* exception first; if an exception is rethrown, then the next-to-last one added handles that
* exception, etc.
*/
public void addInstructionExceptionHandler(int i, String catchClass, Patch p) {
verifyState(DURING_PASS);
try {
instructionHandlerPatches[i] =
new HandlerPatch(instructionHandlerPatches[i], catchClass, allocateLabel(), p);
patchCount++;
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid i: " + i, e);
}
}
/**
* A "method exception handler" handles exceptions generated anywhere in the method. The patch
* code must not fall through; it must return or throw an exception.
*
* <p>If multiple method exception handlers are given, then the last one added handles the
* exception first; if an exception is rethrown, then the next-to-last one added handles that
* exception, etc.
*/
public void addMethodExceptionHandler(String catchClass, Patch p) {
verifyState(DURING_PASS);
if (p == null) {
throw new IllegalArgumentException("null p");
}
methodHandlerPatches = new HandlerPatch(methodHandlerPatches, catchClass, allocateLabel(), p);
patchCount++;
}
/**
* This method inserts code that will be placed after the method body. This code will not be
* executed normally, but it can emit label definitions that other patches can branch to. No
* exception handlers cover this code (other than exception handlers emitted by patch p itself).
*
* @throws IllegalArgumentException if p is null
*/
public void insertAfterBody(Patch p) {
if (p == null) {
throw new IllegalArgumentException("p is null");
}
verifyState(DURING_PASS);
afterMethodPatches = p.insert(afterMethodPatches);
patchCount++;
}
/**
* @return the MethodData used to create this editor, or null if no MethodData is linked to this
* editor
*/
public MethodData getData() {
return methodInfo;
}
private static ExceptionHandler[] makeExceptionArray(HandlerPatch hp) {
if (hp == null) {
return noHandlers;
} else {
int count = 0;
for (HandlerPatch hpIterator = hp; hpIterator != null; hpIterator = hpIterator.next) {
count++;
}
ExceptionHandler[] patchedHandlers = new ExceptionHandler[count];
count = 0;
for (HandlerPatch hpIterator = hp; hpIterator != null; hpIterator = hpIterator.next) {
patchedHandlers[count] = new ExceptionHandler(hpIterator.label, hpIterator.catchClass);
count++;
}
return patchedHandlers;
}
}
/**
* This method finishes a pass. All code is updated; instructions are reordered and old labels may
* not be valid.
*
* <p>If no patches were issued, we don't need to do anything at all; this case is detected
* quickly and no updates are made.
*
* @return true iff non-trivial patches were applied
*/
public boolean applyPatches() throws IllegalArgumentException {
verifyState(DURING_PASS);
state = EMITTING_CODE;
if (patchCount == 0) {
state = BEFORE_END_PASS;
// no patches issued; drop out
return false;
}
Output w = new Output(nextLabel);
int[] oldInstructionsToNew = new int[instructions.length];
w.additionalHandlers = noHandlers;
w.originalBytecode = 0;
for (Patch p = methodStartPatches; p != null; p = p.next) {
p.emitTo(w);
}
ExceptionHandler[] methodHandlers = makeExceptionArray(methodHandlerPatches);
if (methodHandlers.length > 0) {
// if a method handler is added, the code has changed even though
// the patch might not emit any actual code
w.codeChanged = true;
}
for (int i = 0; i < instructions.length; i++) {
ExceptionHandler[] basicHandlers = mergeHandlers(handlers[i], methodHandlers);
HandlerPatch hp = instructionHandlerPatches[i];
w.emitLabel(i);
w.originalBytecode = instructionsToBytecodes[i];
w.additionalHandlers = basicHandlers;
for (Patch p = beforePatches[i]; p != null; p = p.next) {
p.emitTo(w);
}
w.additionalHandlers = mergeHandlers(makeExceptionArray(hp), basicHandlers);
Patch replace = replacementPatches[i];
if (replace == null) {
oldInstructionsToNew[i] = w.newInstructions.size();
w.internalEmitInstruction(instructions[i]);
} else {
// a patch might delete an instruction, in which case the
// code is definitely modified
w.codeChanged = true;
oldInstructionsToNew[i] = -1;
replace.emitTo(w);
}
w.additionalHandlers = basicHandlers;
for (Patch p = afterPatches[i]; p != null; p = p.next) {
p.emitTo(w);
}
if (hp != null) {
// if an instruction handler is added, the code has changed even though
// the patch might not emit any actual code
w.codeChanged = true;
GotoInstruction branchOver = GotoInstruction.make(i + 1);
w.internalEmitInstruction(branchOver);
for (HandlerPatch hpIterator = hp; hpIterator != null; hpIterator = hpIterator.next) {
w.additionalHandlers = mergeHandlers(makeExceptionArray(hpIterator.next), basicHandlers);
w.emitLabel(hpIterator.label);
hpIterator.patch.emitTo(w);
w.internalEmitInstruction(branchOver);
}
}
}
w.originalBytecode = 0;
for (HandlerPatch hpIterator = methodHandlerPatches;
hpIterator != null;
hpIterator = hpIterator.next) {
w.additionalHandlers = makeExceptionArray(hpIterator.next);
w.emitLabel(hpIterator.label);
hpIterator.patch.emitTo(w);
}
w.additionalHandlers = noHandlers;
for (Patch p = afterMethodPatches; p != null; p = p.next) {
p.emitTo(w);
}
state = BEFORE_END_PASS;
if (!w.codeChanged) {
return false;
}
instructions = new Instruction[w.newInstructions.size()];
handlers = new ExceptionHandler[instructions.length][];
instructionsToBytecodes = new int[instructions.length];
w.newInstructions.toArray(instructions);
w.newInstructionHandlers.toArray(handlers);
System.arraycopy(
w.instructionsToBytecodes, 0, instructionsToBytecodes, 0, instructionsToBytecodes.length);
int[] labelDefs = w.labelDefs;
int[] newInstructionsToOld = new int[instructions.length];
for (int i = 0; i < instructions.length; i++) {
instructions[i] = instructions[i].redirectTargets(labelDefs);
newInstructionsToOld[i] = -1;
}
// We want to update each exception handler array exactly once
IdentityHashMap<ExceptionHandler, Object> adjustedHandlers = null;
for (int i = 0; i < handlers.length; i++) {
ExceptionHandler[] hs = handlers[i];
if (hs.length > 0 && (i == 0 || hs != handlers[i - 1])) {
if (adjustedHandlers == null) {
adjustedHandlers = new IdentityHashMap<>();
}
for (ExceptionHandler element : hs) {
ExceptionHandler h = element;
if (!adjustedHandlers.containsKey(h)) {
adjustedHandlers.put(h, null);
h.handler = labelDefs[h.handler]; // breaks invariant of ExceptionHandler: immutable!
}
}
}
}
if (methodInfo != null) {
for (int i = 0; i < oldInstructionsToNew.length; i++) {
if (oldInstructionsToNew[i] != -1) {
newInstructionsToOld[oldInstructionsToNew[i]] = i;
}
}
methodInfo.update(instructions, handlers, newInstructionsToOld, instructionsToBytecodes);
}
return true;
}
/** Apply Visitor v to each instruction in the code, for the purpose of patching the code. */
public void visitInstructions(Visitor v) {
verifyState(DURING_PASS);
for (int i = 0; i < instructions.length; i++) {
v.setIndex(this, i);
instructions[i].visit(v);
}
}
/**
* A specialized Instruction.Visitor providing convenience methods for inserting patches. In
* particular it maintains a notion of the "current position" in the code array.
*/
public static class Visitor extends IInstruction.Visitor {
private int index;
private MethodEditor editor;
/** Set the current editor and instruction index for this visitor. */
public final void setIndex(MethodEditor e, int i) {
index = i;
editor = e;
}
/** @return the index of the current instruction in the code array */
public final int getIndex() {
return index;
}
/** Insert a patch after the current instruction in the code. */
public final void insertAfter(Patch p) {
editor.insertAfter(index, p);
}
/** Insert a patch before the current instruction in the code. */
public final void insertBefore(Patch p) {
editor.insertBefore(index, p);
}
/** Replace the current instruction in the code with a patch. */
public final void replaceWith(Patch p) {
editor.replaceWith(index, p);
}
/**
* Add an exception handler to the current instruction.
*
* @param catchClass the JVM type for the exception to be caught (e.g., Ljava.io.IOException;),
* or null to catch all exceptions
* @param p the code to handle the exception
*/
public final void addInstructionExceptionHandler(String catchClass, Patch p) {
editor.addInstructionExceptionHandler(index, catchClass, p);
}
}
}
| 24,623
| 33.2
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/MonitorInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents monitorenter and monitorexit instructions. */
public final class MonitorInstruction extends Instruction {
private MonitorInstruction(short opcode) {
super(opcode);
}
private static final MonitorInstruction enter = new MonitorInstruction(OP_monitorenter);
private static final MonitorInstruction exit = new MonitorInstruction(OP_monitorexit);
public static MonitorInstruction make(boolean entering) {
return entering ? enter : exit;
}
@Override
public boolean equals(Object o) {
if (o instanceof MonitorInstruction) {
MonitorInstruction i = (MonitorInstruction) o;
return i.opcode == opcode;
} else {
return false;
}
}
public boolean isEnter() {
return opcode == OP_monitorenter;
}
@Override
public int hashCode() {
return opcode + 1911;
}
@Override
public int getPoppedCount() {
return 1;
}
@Override
public void visit(IInstruction.Visitor v) throws IllegalArgumentException {
if (v == null) {
throw new IllegalArgumentException();
}
v.visitMonitor(this);
}
@Override
public String toString() {
return "Monitor(" + (isEnter() ? "ENTER" : "EXIT") + ')';
}
@Override
public boolean isPEI() {
return true;
}
}
| 1,683
| 23.405797
| 90
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/NewInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
public final class NewInstruction extends Instruction {
private final String type;
private final short arrayBoundsCount;
private NewInstruction(short opcode, String type, short arrayBoundsCount) {
super(opcode);
this.type = type;
this.arrayBoundsCount = arrayBoundsCount;
}
/**
* @param type the type of the object that will be returned (in JVM format, e.g.,
* [Ljava/lang/String;)
* @param arrayBoundsCount the number of array dimensions to preconstruct (equal to the number of
* integer parameters this instruction expects)
* @throws IllegalArgumentException if type is null
*/
public static NewInstruction make(String type, int arrayBoundsCount)
throws IllegalArgumentException {
if (type == null) {
throw new IllegalArgumentException("type is null");
}
if (arrayBoundsCount < 0 || arrayBoundsCount > 255) {
throw new IllegalArgumentException("Too many array bounds: " + arrayBoundsCount);
} else {
if (type.length() < arrayBoundsCount + 1) {
throw new IllegalArgumentException(
"Not enough array nesting in " + type + " for bounds count " + arrayBoundsCount);
}
for (int i = 0; i < arrayBoundsCount; i++) {
if (type.charAt(i) != '[') {
throw new IllegalArgumentException(
"Not enough array nesting in " + type + " for bounds count " + arrayBoundsCount);
}
}
short opcode;
switch (arrayBoundsCount) {
case 0:
opcode = OP_new;
break;
case 1:
char ch = type.charAt(1);
if (ch != 'L' && ch != '[') {
// array of primitive type
opcode = OP_newarray;
} else {
opcode = OP_anewarray;
}
break;
default:
opcode = OP_multianewarray;
break;
}
return new NewInstruction(opcode, type, (short) arrayBoundsCount);
}
}
@Override
public boolean equals(Object o) {
if (o instanceof NewInstruction) {
NewInstruction i = (NewInstruction) o;
return i.type.equals(type) && i.arrayBoundsCount == arrayBoundsCount;
} else {
return false;
}
}
public int getArrayBoundsCount() {
return arrayBoundsCount;
}
@Override
public int hashCode() {
return 13111143 * type.hashCode() + arrayBoundsCount;
}
@Override
public int getPoppedCount() {
return arrayBoundsCount;
}
@Override
public String getPushedType(String[] types) {
return type;
}
@Override
public byte getPushedWordSize() {
return 1;
}
public String getType() {
return type;
}
@Override
public String toString() {
return "New(" + type + ',' + arrayBoundsCount + ')';
}
@Override
public void visit(IInstruction.Visitor v) throws IllegalArgumentException {
if (v == null) {
throw new IllegalArgumentException();
}
v.visitNew(this);
}
@Override
public boolean isPEI() {
return true;
}
}
| 3,427
| 25.573643
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/PopInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** PopInstructions pop one or two elements off the working stack. */
public final class PopInstruction extends Instruction {
private final byte size;
private PopInstruction(byte size) {
super((short) -1);
this.size = size;
}
/** @param size 1 or 2, the number of elements to pop */
public static PopInstruction make(int size) {
if (size < 0 || size > 2) {
throw new IllegalArgumentException("Invalid pop size: " + size);
} else {
return new PopInstruction((byte) size);
}
}
@Override
public boolean equals(Object o) {
if (o instanceof PopInstruction) {
PopInstruction i = (PopInstruction) o;
return i.size == size;
} else {
return false;
}
}
@Override
public int hashCode() {
return size + 8431890;
}
@Override
public int getPoppedCount() {
return size;
}
@Override
public void visit(IInstruction.Visitor v) throws IllegalArgumentException {
if (v == null) {
throw new IllegalArgumentException();
}
v.visitPop(this);
}
@Override
public String toString() {
return "Pop(" + size + ')';
}
@Override
public boolean isPEI() {
return false;
}
}
| 1,604
| 22.26087
| 77
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/PutInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents put and putstatic instructions. */
public class PutInstruction extends Instruction implements IPutInstruction {
protected String type;
protected String classType;
protected String fieldName;
PutInstruction(short opcode, String type, String classType, String fieldName) {
super(opcode);
this.type = type;
this.classType = classType;
this.fieldName = fieldName;
}
ConstantPoolReader getLazyConstantPool() {
return null;
}
static final class Lazy extends PutInstruction {
private final ConstantPoolReader cp;
private final int index;
Lazy(short opcode, ConstantPoolReader cp, int index) {
super(opcode, null, null, null);
this.index = index;
this.cp = cp;
}
@Override
ConstantPoolReader getLazyConstantPool() {
return cp;
}
int getCPIndex() {
return index;
}
@Override
public String getClassType() {
if (classType == null) {
classType = cp.getConstantPoolMemberClassType(index);
}
return classType;
}
@Override
public String getFieldName() {
if (fieldName == null) {
fieldName = cp.getConstantPoolMemberName(index);
}
return fieldName;
}
@Override
public String getFieldType() {
if (type == null) {
type = cp.getConstantPoolMemberType(index);
}
return type;
}
}
static PutInstruction make(ConstantPoolReader cp, int index, boolean isStatic) {
return new Lazy(isStatic ? OP_putstatic : OP_putfield, cp, index);
}
public static PutInstruction make(
String type, String className, String fieldName, boolean isStatic) {
if (type == null) {
throw new IllegalArgumentException("type must not be null");
}
if (className == null) {
throw new IllegalArgumentException("className must not be null");
}
if (fieldName == null) {
throw new IllegalArgumentException("fieldName must not be null");
}
return new PutInstruction(isStatic ? OP_putstatic : OP_putfield, type, className, fieldName);
}
@Override
public final boolean equals(Object o) {
if (o instanceof PutInstruction) {
PutInstruction i = (PutInstruction) o;
return i.getFieldType().equals(getFieldType())
&& i.getClassType().equals(getClassType())
&& i.getFieldName().equals(getFieldName())
&& i.opcode == opcode;
} else {
return false;
}
}
@Override
public String getClassType() {
return classType;
}
@Override
public String getFieldType() {
return type;
}
@Override
public String getFieldName() {
return fieldName;
}
@Override
public final boolean isStatic() {
return opcode == OP_putstatic;
}
@Override
public final int hashCode() {
return getClassType().hashCode()
+ 9011 * getClassType().hashCode()
+ 317 * getFieldName().hashCode()
+ opcode;
}
@Override
public final int getPoppedCount() {
return isStatic() ? 1 : 2;
}
@Override
public final String toString() {
return "Put("
+ getFieldType()
+ ','
+ (isStatic() ? "STATIC" : "NONSTATIC")
+ ','
+ getClassType()
+ ','
+ getFieldName()
+ ')';
}
@Override
public final void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitPut(this);
}
@Override
public boolean isPEI() {
return !isStatic();
}
}
| 3,899
| 22.780488
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ReturnInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This instruction represents all return instructions. */
public final class ReturnInstruction extends Instruction {
private ReturnInstruction(short opcode) {
super(opcode);
}
private static final ReturnInstruction[] preallocated = preallocate();
private static final ReturnInstruction preallocatedVoid = new ReturnInstruction(OP_return);
private static ReturnInstruction[] preallocate() {
ReturnInstruction[] r = new ReturnInstruction[OP_areturn - OP_ireturn + 1];
for (int i = 0; i < r.length; i++) {
r[i] = new ReturnInstruction((short) (OP_ireturn + i));
}
return r;
}
public static ReturnInstruction make(String type) throws IllegalArgumentException {
if (type == null) {
throw new IllegalArgumentException("type is null");
}
if (type.equals(TYPE_void)) {
return preallocatedVoid;
} else {
int t = Util.getTypeIndex(type);
if (t < 0 || t > TYPE_Object_index) {
throw new IllegalArgumentException("Cannot return type " + type);
}
return preallocated[t];
}
}
@Override
public boolean equals(Object o) {
if (o instanceof ReturnInstruction) {
ReturnInstruction i = (ReturnInstruction) o;
return i.opcode == opcode;
} else {
return false;
}
}
@Override
public boolean isFallThrough() {
return false;
}
@Override
public int hashCode() {
return opcode + 31111;
}
@Override
public int getPoppedCount() {
return opcode == OP_return ? 0 : 1;
}
public String getType() {
return opcode == OP_return ? TYPE_void : indexedTypes[opcode - OP_ireturn];
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitReturn(this);
}
@Override
public String toString() {
return "Return(" + getType() + ')';
}
@Override
public boolean isPEI() {
return false;
}
}
| 2,312
| 24.7
| 93
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ShiftInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import java.util.Arrays;
/**
* ShiftInstructions are distinguished from BinaryOpInstructions because most binary operations in
* the JVM require both parameters to be the same type, but shifts always take one int parameter.
*/
public final class ShiftInstruction extends Instruction implements IShiftInstruction {
private ShiftInstruction(short opcode) {
super(opcode);
}
private static final ShiftInstruction[] preallocated = preallocate();
private static ShiftInstruction[] preallocate() {
ShiftInstruction[] r = new ShiftInstruction[OP_lushr - OP_ishl + 1];
Arrays.setAll(r, i -> new ShiftInstruction((short) (i + OP_ishl)));
return r;
}
public static ShiftInstruction make(String type, Operator operator)
throws IllegalArgumentException {
if (operator == null) {
throw new IllegalArgumentException("operator is null");
}
int t = Util.getTypeIndex(type);
if (t < 0 || t > TYPE_long_index) {
throw new IllegalArgumentException("Cannot apply shift to type " + type);
}
return preallocated[(operator.ordinal() - Operator.SHL.ordinal()) * 2 + t];
}
@Override
public boolean equals(Object o) {
if (o instanceof ShiftInstruction) {
ShiftInstruction i = (ShiftInstruction) o;
return i.opcode == opcode;
} else {
return false;
}
}
@Override
public Operator getOperator() {
return Operator.values()[(opcode - OP_ishl) / 2];
}
@Override
public int hashCode() {
return opcode;
}
@Override
public int getPoppedCount() {
return 2;
}
@Override
public String getPushedType(String[] types) {
return getType();
}
@Override
public byte getPushedWordSize() {
return Util.getWordSize(getType());
}
@Override
public String getType() {
return indexedTypes[(opcode - OP_ishl) & 1];
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitShift(this);
}
@Override
public String toString() {
return "Shift(" + getType() + ',' + getOperator() + ')';
}
@Override
public boolean isPEI() {
return false;
}
@Override
public boolean isUnsigned() {
return false;
}
}
| 2,612
| 23.885714
| 98
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/StoreInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents instructions that store to local variables. */
public final class StoreInstruction extends Instruction implements IStoreInstruction {
private final int index;
private StoreInstruction(short opcode, int index) {
super(opcode);
this.index = index;
}
private static final StoreInstruction[] preallocated = preallocate();
private static StoreInstruction[] preallocate() {
StoreInstruction[] r = new StoreInstruction[5 * 16];
for (int p = 0; p < 5; p++) {
for (int i = 0; i < 4; i++) {
r[p * 16 + i] = new StoreInstruction((short) (OP_istore_0 + i + p * 4), i);
}
for (int i = 4; i < 16; i++) {
r[p * 16 + i] = new StoreInstruction((short) (OP_istore + p), i);
}
}
return r;
}
public static StoreInstruction make(String type, int index) throws IllegalArgumentException {
int t = Util.getTypeIndex(type);
if (t < 0 || t > TYPE_Object_index) {
throw new IllegalArgumentException("Cannot store local of type " + type);
}
if (index < 16) {
return preallocated[t * 16 + index];
} else {
return new StoreInstruction((short) (OP_istore + t), index);
}
}
/** @return the index of the local variable stored */
@Override
public int getVarIndex() {
return index;
}
@Override
public String getType() {
if (opcode < OP_istore_0) {
return indexedTypes[opcode - OP_istore];
} else {
return indexedTypes[(opcode - OP_istore_0) / 4];
}
}
@Override
public boolean equals(Object o) {
if (o instanceof StoreInstruction) {
StoreInstruction i = (StoreInstruction) o;
return i.index == index && i.opcode == opcode;
} else {
return false;
}
}
@Override
public int hashCode() {
return opcode + index * 148091891;
}
@Override
public int getPoppedCount() {
return 1;
}
@Override
public String toString() {
return "LocalStore(" + getType() + ',' + index + ')';
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitLocalStore(this);
}
@Override
public boolean isPEI() {
return false;
}
}
| 2,592
| 25.191919
| 95
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/SwapInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/**
* This instruction represents the swap instruction, which swaps the two values on top of the
* working stack.
*/
public final class SwapInstruction extends Instruction {
private SwapInstruction() {
super((short) -1);
}
private static final SwapInstruction preallocated = new SwapInstruction();
public static SwapInstruction make() {
return preallocated;
}
@Override
public boolean equals(Object o) {
if (o instanceof SwapInstruction) {
return true;
} else {
return false;
}
}
@Override
public int hashCode() {
return 84323111;
}
@Override
public int getPoppedCount() {
return 2;
}
@Override
public String toString() {
return "Swap()";
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitSwap(this);
}
@Override
public boolean isPEI() {
return false;
}
}
| 1,318
| 20.274194
| 93
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/SwitchInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import java.util.Arrays;
/** This instruction represents all forms of switch instructions. */
public final class SwitchInstruction extends Instruction {
private final int[] casesAndLabels;
private final int defaultLabel;
private SwitchInstruction(short opcode, int[] casesAndLabels, int defaultLabel) {
super(opcode);
this.casesAndLabels = casesAndLabels;
this.defaultLabel = defaultLabel;
}
/** @return the label which is branched to if none of the cases match */
public int getDefaultLabel() {
return defaultLabel;
}
/** @return an array of flattened (case, label) pairs, sorted in increasing order by case */
public int[] getCasesAndLabels() {
return casesAndLabels;
}
/**
* Make a switch instruction.
*
* @param casesAndLabels an array of flattened (case, label) pairs, sorted in increasing order by
* case
* @param defaultLabel the default label to branch to if no cases match
* @throws IllegalArgumentException if casesAndLabels is null
*/
public static SwitchInstruction make(int[] casesAndLabels, int defaultLabel) {
if (casesAndLabels == null) {
throw new IllegalArgumentException("casesAndLabels is null");
}
short opcode = OP_tableswitch;
for (int i = 2; i < casesAndLabels.length; i += 2) {
int curCase = casesAndLabels[i];
int lastCase = casesAndLabels[i - 2];
if (curCase <= lastCase) {
throw new IllegalArgumentException("Cases and labels array must be sorted by case");
}
if (curCase != lastCase + 1) {
opcode = OP_lookupswitch;
}
}
if (casesAndLabels.length == 0) {
opcode = OP_lookupswitch;
}
return new SwitchInstruction(opcode, casesAndLabels, defaultLabel);
}
@Override
public boolean isFallThrough() {
return false;
}
@Override
public int[] getBranchTargets() {
int[] r = new int[casesAndLabels.length / 2 + 1];
r[0] = defaultLabel;
for (int i = 1; i < r.length; i++) {
r[i] = casesAndLabels[(i - 1) * 2 + 1];
}
return r;
}
@Override
public IInstruction redirectTargets(int[] targetMap) throws IllegalArgumentException {
if (targetMap == null) {
throw new IllegalArgumentException("targetMap is null");
}
try {
int[] cs = new int[casesAndLabels.length];
for (int i = 0; i < cs.length; i += 2) {
cs[i] = casesAndLabels[i];
cs[i + 1] = targetMap[casesAndLabels[i + 1]];
}
return make(cs, targetMap[defaultLabel]);
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Illegal target map", e);
}
}
@Override
public boolean equals(Object o) {
if (o instanceof SwitchInstruction) {
SwitchInstruction i = (SwitchInstruction) o;
return i.defaultLabel == defaultLabel && Arrays.equals(i.casesAndLabels, casesAndLabels);
} else {
return false;
}
}
@Override
public int hashCode() {
int h = defaultLabel * 1348091 + 111311;
for (int i = 0; i < casesAndLabels.length; i++) {
h += (i * 9301 + 38101) * casesAndLabels[i];
}
return h;
}
@Override
public int getPoppedCount() {
return 1;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("Switch(");
b.append(defaultLabel);
for (int casesAndLabel : casesAndLabels) {
b.append(',');
b.append(casesAndLabel);
}
b.append(')');
return b.toString();
}
@Override
public void visit(IInstruction.Visitor v) throws IllegalArgumentException {
if (v == null) {
throw new IllegalArgumentException();
}
v.visitSwitch(this);
}
@Override
public boolean isPEI() {
return false;
}
}
| 4,142
| 26.62
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ThrowInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents the athrow instruction. */
public final class ThrowInstruction extends Instruction {
private static final ThrowInstruction preallocated = new ThrowInstruction(false);
private static final ThrowInstruction preallocatedRethrow = new ThrowInstruction(true);
private final boolean rethrow;
private ThrowInstruction(boolean rethrow) {
super(OP_athrow);
this.rethrow = rethrow;
}
public static ThrowInstruction make(boolean isRethrow) {
if (isRethrow) {
return preallocatedRethrow;
} else {
return preallocated;
}
}
@Override
public boolean equals(Object o) {
return o instanceof ThrowInstruction;
}
public boolean isRethrow() {
return rethrow;
}
@Override
public boolean isFallThrough() {
return false;
}
@Override
public int hashCode() {
return 99651;
}
@Override
public int getPoppedCount() {
return 1;
}
@Override
public void visit(IInstruction.Visitor v) throws IllegalArgumentException {
if (v == null) {
throw new IllegalArgumentException();
}
v.visitThrow(this);
}
@Override
public String toString() {
return "Throw()";
}
@Override
public boolean isPEI() {
return true;
}
}
| 1,664
| 20.907895
| 89
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/UnaryOpInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import java.util.Arrays;
/** This class represents unary operators where the result is the same type as the operand. */
public final class UnaryOpInstruction extends Instruction implements IUnaryOpInstruction {
private UnaryOpInstruction(short opcode) {
super(opcode);
}
private static final UnaryOpInstruction[] preallocated = preallocate();
private static UnaryOpInstruction[] preallocate() {
UnaryOpInstruction[] r = new UnaryOpInstruction[OP_dneg - OP_ineg + 1];
Arrays.setAll(r, i -> new UnaryOpInstruction((short) (OP_ineg + i)));
return r;
}
public static UnaryOpInstruction make(String type) throws IllegalArgumentException {
int t = Util.getTypeIndex(type);
if (t < 0 || t > TYPE_double_index) {
throw new IllegalArgumentException("Type " + type + " cannot have a unary operator applied");
}
return preallocated[t];
}
@Override
public boolean equals(Object o) {
if (o instanceof UnaryOpInstruction) {
UnaryOpInstruction i = (UnaryOpInstruction) o;
return i.opcode == opcode;
} else {
return false;
}
}
@Override
public IUnaryOpInstruction.Operator getOperator() {
return IUnaryOpInstruction.Operator.NEG;
}
@Override
public int hashCode() {
return opcode;
}
@Override
public int getPoppedCount() {
return 1;
}
@Override
public String getPushedType(String[] types) {
return getType();
}
@Override
public byte getPushedWordSize() {
return Util.getWordSize(getType());
}
@Override
public String getType() {
return indexedTypes[opcode - OP_ineg];
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitUnaryOp(this);
}
@Override
public String toString() {
return "UnaryOp(" + getType() + ',' + getOperator() + ')';
}
@Override
public boolean isPEI() {
return false;
}
}
| 2,315
| 24.173913
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/Util.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.Dispatch;
import com.ibm.wala.util.collections.Pair;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
/**
* This class contains miscellaneous useful functions.
*
* <p>In the documentation below, we refer to a 'Java class name'. These are formatted according to
* the rules for Class.forName() and Class.getName(). A Java class name must use '$' to separate
* inner class names from their containing class. There is no way to for Shrike to disambiguate
* 'A.B' otherwise.
*/
public final class Util {
private Util() {
// prevent instantiation
}
/**
* @return the JVM "stack word size" for the given JVM type
* @throws IllegalArgumentException if s is null
*/
public static byte getWordSize(String s) {
if (s == null || s.length() == 0) {
throw new IllegalArgumentException("invalid s: " + s);
}
return getWordSize(s, 0);
}
/** @return the JVM "stack word size" for the given JVM type, looking at index 'index' */
static byte getWordSize(String s, int index) {
switch (s.charAt(index)) {
case 'V':
return 0;
case 'J':
case 'D':
return 2;
default:
return 1;
}
}
/** Computes the character length of the internal JVM type given by s.substring(i). */
private static int getTypeLength(String s, int i) {
switch (s.charAt(i)) {
case 'L':
return s.indexOf(';', i) - i + 1;
case '[':
return getTypeLength(s, i + 1) + 1;
default:
return 1;
}
}
/**
* Compute the total number of JVM "stack words" occupied by the method parameters for method
* signature "type". Any "this" parameter is not included.
*
* @throws IllegalArgumentException if type is null
*/
public static int getParamsWordSize(String type) throws IllegalArgumentException {
if (type == null) {
throw new IllegalArgumentException("type is null");
}
int index = 1;
int count = 0;
if (type.indexOf(')', 1) < 0) {
throw new IllegalArgumentException("Invalid method descriptor (missing ')'): " + type);
}
while (type.charAt(index) != ')') {
count += getWordSize(type, index);
index += getTypeLength(type, index);
}
return count;
}
/**
* Convert a fully-qualified Java class name ('.' separated) into an internal JVM type name ('/'
* separated, starting with 'L' and ending with ';').
*
* @throws IllegalArgumentException if c is null
*/
public static String makeType(String c) {
if (c == null) {
throw new IllegalArgumentException("c is null");
}
if (c.startsWith("[")) {
return c.replace('.', '/');
} else if (!c.endsWith(";")) {
return 'L' + c.replace('.', '/') + ';';
} else {
return c;
}
}
/**
* Convert a fully-qualified Java type name (either primitive or class name, '.' separated) into
* an internal JVM type name (one letter for primitive and '/' separated, starting with 'L' and
* ending with ';' for class name).
*/
public static String makeTypeAll(String c) {
String alias = typeAliases.get(c);
if (alias != null) {
return alias;
} else {
return makeType(c);
}
}
/**
* Convert a JVM type name back into a Java class name.
*
* @throws IllegalArgumentException if t is null
*/
public static String makeClass(String t) throws IllegalArgumentException {
if (t == null) {
throw new IllegalArgumentException("t is null");
}
if (t.startsWith("[")) {
return t;
} else if (!t.startsWith("L")) {
throw new IllegalArgumentException(t + " is not a valid class type");
} else {
return t.substring(1, t.length() - 1).replace('/', '.');
}
}
/** Convert a JVM type name (either for a primitive or a class name) into a Java type name. */
static String makeClassAll(String t) {
String alias = classAliases.get(t);
if (alias != null) {
return alias;
} else {
return makeClass(t);
}
}
private static final HashMap<String, String> classAliases;
private static final HashMap<String, String> typeAliases;
private static void addAlias(String c, String t) {
typeAliases.put(c, t);
classAliases.put(t, c);
}
static {
typeAliases = new HashMap<>();
classAliases = new HashMap<>();
addAlias("void", "V");
addAlias("int", "I");
addAlias("long", "J");
addAlias("float", "F");
addAlias("double", "D");
addAlias("byte", "B");
addAlias("char", "C");
addAlias("short", "S");
addAlias("boolean", "Z");
}
/**
* Compute the JVM type name for an actual Java class. Names such as "int", "void", etc are also
* converted to their JVM type names.
*
* @throws IllegalArgumentException if c is null
*/
public static String makeType(Class<?> c) {
if (c == null) {
throw new IllegalArgumentException("c is null");
}
String name = c.getName();
String alias = typeAliases.get(name);
if (alias != null) {
return alias;
} else {
return makeType(name);
}
}
/**
* Compute the number of parameters given by method signature "type". Any "this" parameter is not
* included.
*
* @throws IllegalArgumentException if type == null
*/
public static int getParamsCount(String type) throws IllegalArgumentException {
if (type == null || type.length() < 2) {
throw new IllegalArgumentException("invalid type: " + type);
}
int index = 1;
int count = 0;
try {
while (type.charAt(index) != ')') {
count++;
index += getTypeLength(type, index);
}
return count;
} catch (StringIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid type: " + type, e);
}
}
/**
* Extract the types of the parameters given by method signature "type".
*
* @param thisClassType null if the method is static, otherwise the type of "this"
* @return an array of the parameter types in order, including "this" as the first parameter if
* thisClassType was non-null
* @throws IllegalArgumentException if type == null
*/
public static String[] getParamsTypes(String thisClassType, String type)
throws IllegalArgumentException {
if (type == null) {
throw new IllegalArgumentException("type == null");
}
int count = thisClassType != null ? 1 : 0;
String[] r = new String[getParamsCount(type) + count];
int index = 1;
if (thisClassType != null) {
r[0] = thisClassType;
}
while (type.charAt(index) != ')') {
int len = getTypeLength(type, index);
r[count] = type.substring(index, index + len);
count++;
index += len;
}
return r;
}
/**
* Compute the types of the local variables on entry to a method. Similar to "getParamsTypes"
* except null array entries are inserted to account for unused local variables because of 2-word
* parameter values.
*
* @throws IllegalArgumentException if type == null
*/
public static String[] getParamsTypesInLocals(String thisClassType, String type)
throws IllegalArgumentException {
if (type == null) {
throw new IllegalArgumentException("type == null");
}
int count = thisClassType != null ? 1 : 0;
String[] r = new String[getParamsWordSize(type) + count];
int index = 1;
if (thisClassType != null) {
r[0] = thisClassType;
}
while (type.charAt(index) != ')') {
int len = getTypeLength(type, index);
String t = getStackType(type.substring(index, index + len));
r[count] = t;
count += getWordSize(t);
index += len;
}
return r;
}
/**
* Compute the promoted type that the JVM uses to manipulate values of type "t" on its working
* stack.
*
* @throws IllegalArgumentException if t is null
*/
public static String getStackType(String t) {
if (t == null || t.length() < 1) {
throw new IllegalArgumentException("invalid t: " + t);
}
switch (t.charAt(0)) {
case 'Z':
case 'C':
case 'B':
case 'S':
return "I";
default:
return t;
}
}
/** Compute the type "array of t". */
public static String makeArray(String t) {
return ('[' + t).intern();
}
/** @return true iff t is an array type */
public static boolean isArrayType(String t) {
if (t == null || t.length() == 0) {
return false;
} else {
switch (t.charAt(0)) {
case '[':
return true;
default:
return false;
}
}
}
/** @return true iff t is a primitive type */
public static boolean isPrimitiveType(String t) {
if (t == null || t.length() == 0) {
return false;
} else {
switch (t.charAt(0)) {
case 'L':
case '[':
return false;
default:
return true;
}
}
}
/**
* Get the return type from a method signature.
*
* @throws IllegalArgumentException if s is null
*/
public static String getReturnType(String s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
return s.substring(s.lastIndexOf(')') + 1);
}
/** General "print an error" routine. */
public static void error(String s) {
System.err.println(s);
new Error("Stack Trace").printStackTrace();
}
/**
* Given a Java Method, compute the VM-style type signature.
*
* @throws IllegalArgumentException if params == null
*/
public static String computeSignature(Class<?>[] params, Class<?> result)
throws IllegalArgumentException {
if (params == null) {
throw new IllegalArgumentException("params == null");
}
StringBuilder buf = new StringBuilder();
buf.append('(');
for (Class<?> param : params) {
buf.append(makeType(param));
}
buf.append(')');
buf.append(makeType(result));
return buf.toString();
}
/**
* Make an Instruction which loads the value of a field, given its name and Java Class. The field
* type is obtained using reflection.
*
* @throws IllegalArgumentException if c is null
*/
public static GetInstruction makeGet(Class<?> c, String name) {
if (c == null) {
throw new IllegalArgumentException("c is null");
}
try {
Field f = c.getField(name);
return GetInstruction.make(
makeType(f.getType()), makeType(c), name, (f.getModifiers() & Constants.ACC_STATIC) != 0);
} catch (SecurityException | NoSuchFieldException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
/**
* Make an Instruction which stores the value of a field, given its name and Java Class. The field
* type is obtained using reflection.
*
* @throws IllegalArgumentException if c is null
*/
public static PutInstruction makePut(Class<?> c, String name) {
if (c == null) {
throw new IllegalArgumentException("c is null");
}
try {
Field f = c.getField(name);
return PutInstruction.make(
makeType(f.getType()), makeType(c), name, (f.getModifiers() & Constants.ACC_STATIC) != 0);
} catch (SecurityException | NoSuchFieldException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
private static String makeName(String name, Class<?>[] paramTypes) {
if (paramTypes == null) {
return name;
} else {
StringBuilder buf = new StringBuilder(name);
buf.append('(');
for (int i = 0; i < paramTypes.length; i++) {
if (i > 0) {
buf.append(',');
}
buf.append(paramTypes[i].getName());
}
buf.append(')');
return buf.toString();
}
}
public static Method findMethod(Class<?> c, String name) {
return findMethod(c, name, null);
}
public static Method findMethod(Class<?> c, String name, Class<?>[] paramTypes) {
if (c == null) {
throw new IllegalArgumentException("c is null");
}
Method[] methods = c.getMethods();
Method result = null;
for (Method m : methods) {
if (m.getName().equals(name)
&& (paramTypes == null || Arrays.equals(m.getParameterTypes(), paramTypes))) {
if (result != null) {
throw new IllegalArgumentException(
"Method " + makeName(name, paramTypes) + " is ambiguous in class " + c);
}
result = m;
}
}
return result;
}
/**
* Make an Instruction which calls a method, given its name, Java Class, and a list of parameter
* classes to use for overload resolution. Method information is obtained using reflection.
*
* @throws IllegalArgumentException if name is null
*/
public static InvokeInstruction makeInvoke(Class<?> c, String name, Class<?>[] paramTypes) {
if (name == null) {
throw new IllegalArgumentException("name is null");
}
InvokeInstruction result = null;
if (name.equals("<init>")) {
Constructor<?>[] cs = c.getConstructors();
for (Constructor<?> con : cs) {
if (paramTypes == null || Arrays.equals(con.getParameterTypes(), paramTypes)) {
if (result != null) {
throw new IllegalArgumentException(
"Constructor " + makeName(name, paramTypes) + " is ambiguous in class " + c);
}
result =
InvokeInstruction.make(
computeSignature(con.getParameterTypes(), Void.TYPE),
makeType(c),
name,
Dispatch.SPECIAL);
}
}
} else {
Method m = findMethod(c, name, paramTypes);
if (m != null) {
Dispatch opcode = Dispatch.VIRTUAL;
if ((m.getModifiers() & Constants.ACC_STATIC) != 0) {
opcode = Dispatch.STATIC;
} else if (m.getDeclaringClass().isInterface()) {
opcode = Dispatch.INTERFACE;
}
result =
InvokeInstruction.make(
computeSignature(m.getParameterTypes(), m.getReturnType()),
makeType(c),
name,
opcode);
}
}
if (result == null) {
throw new IllegalArgumentException(
"Method " + makeName(name, paramTypes) + " is not present in class " + c);
} else {
return result;
}
}
/**
* Make an Instruction which calls a method, given its name and Java Class. Method information is
* obtained using reflection. If there is more than one method with the given name, an error will
* be thrown.
*
* @throws IllegalArgumentException if name is null
*/
public static InvokeInstruction makeInvoke(Class<?> c, String name) {
return makeInvoke(c, name, null);
}
/**
* Compute the type index constant (Constants.TYPE_...) from the JVM type. Returns -1 if the type
* is not one of the predefined constants.
*/
static int getTypeIndex(String t) {
if (t == null) {
return -1;
} else {
int len = t.length();
if (len < 1) {
return -1;
} else {
char ch = t.charAt(0);
if (ch < typeIndices.length) {
int r = typeIndices[ch];
if (r != 4) {
if (len > 1) {
return -1;
} else {
return r;
}
} else {
return r;
}
} else {
return -1;
}
}
}
}
private static final byte[] typeIndices = makeTypeIndices();
private static byte[] makeTypeIndices() {
byte[] r = new byte[128];
Arrays.fill(r, (byte) -1);
r['I'] = 0;
r['J'] = 1;
r['F'] = 2;
r['D'] = 3;
r['L'] = 4;
r['['] = 4;
r['B'] = 5;
r['C'] = 6;
r['S'] = 7;
r['Z'] = 8;
return r;
}
public static void readFully(InputStream s, byte[] bytes)
throws IllegalArgumentException, IllegalArgumentException, IOException {
if (s == null) {
throw new IllegalArgumentException("s == null");
}
if (bytes == null) {
throw new IllegalArgumentException("bytes == null");
}
int offset = 0;
while (offset < bytes.length) {
int r = s.read(bytes, offset, bytes.length - offset);
if (r < 0) {
throw new IOException("Class truncated");
}
offset += r;
}
}
public static byte[] readFully(InputStream s) throws IOException {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
byte[] bytes = new byte[s.available()];
readFully(s, bytes);
int b = s.read();
if (b < 0) {
return bytes;
} else {
byte[] big = Arrays.copyOf(bytes, bytes.length * 2 + 1);
big[bytes.length] = (byte) b;
int offset = bytes.length + 1;
do {
if (big.length == offset) {
// grow array by factor of 2
bytes = new byte[offset * 2];
System.arraycopy(big, 0, bytes, 0, offset);
big = bytes;
}
int r = s.read(big, offset, big.length - offset);
if (r < 0) {
bytes = new byte[offset];
System.arraycopy(big, 0, bytes, 0, offset);
return bytes;
}
offset += r;
} while (true);
}
}
public static Pair<boolean[], boolean[]> computeBasicBlocks(
IInstruction[] instructions, ExceptionHandler[][] handlers) {
// Compute r so r[i] == true iff instruction i begins a basic block.
boolean[] r = new boolean[instructions.length];
boolean[] catchers = new boolean[instructions.length];
r[0] = true;
for (int i = 0; i < instructions.length; i++) {
int[] targets = instructions[i].getBranchTargets();
// if there are any targets, then break the basic block here.
// also break the basic block after a return
if (targets.length > 0 || !instructions[i].isFallThrough()) {
if (i + 1 < instructions.length && !r[i + 1]) {
r[i + 1] = true;
}
}
for (int target : targets) {
if (!r[target]) {
r[target] = true;
}
}
if (instructions[i].isPEI()) {
ExceptionHandler[] hs = handlers[i];
// break the basic block here.
if (i + 1 < instructions.length && !r[i + 1]) {
r[i + 1] = true;
}
if (hs != null) {
for (ExceptionHandler h : hs) {
// exceptionHandlers.add(hs[j]);
if (!r[h.getHandler()]) {
// we have not discovered the catch block yet.
// form a new basic block
r[h.getHandler()] = true;
}
catchers[h.getHandler()] = true;
}
}
}
}
return Pair.make(r, catchers);
}
}
| 19,279
| 27.948949
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/analysis/Analyzer.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.analysis;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.DupInstruction;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.Dispatch;
import com.ibm.wala.shrike.shrikeBT.ILoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.LoadInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.NewInstruction;
import com.ibm.wala.shrike.shrikeBT.StoreInstruction;
import com.ibm.wala.shrike.shrikeBT.SwapInstruction;
import com.ibm.wala.shrike.shrikeBT.Util;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
/** @author roca */
public class Analyzer {
public static final String thisType = "THIS";
public static final String topType = "TOP";
// inputs
protected final boolean isConstructor;
protected final boolean isStatic;
protected final String classType;
protected final String signature;
protected final IInstruction[] instructions;
protected final ExceptionHandler[][] handlers;
protected ClassHierarchyProvider hierarchy;
// working
protected int maxStack;
protected int maxLocals;
protected String[][] stacks;
protected String[][] locals;
protected int[] stackSizes;
protected BitSet basicBlockStarts;
protected int[][] backEdges;
protected int[] instToBC;
protected String[][] varTypes;
protected static final String[] noStrings = new String[0];
protected static final int[] noEdges = new int[0];
public Analyzer(
boolean isConstructor,
boolean isStatic,
String classType,
String signature,
IInstruction[] instructions,
ExceptionHandler[][] handlers,
int[] instToBC,
String[][] vars) {
if (instructions == null) {
throw new IllegalArgumentException("null instructions");
}
if (handlers == null) {
throw new IllegalArgumentException("null handlers");
}
for (IInstruction i : instructions) {
if (i == null) {
throw new IllegalArgumentException("null instruction is illegal");
}
}
this.classType = classType;
this.isConstructor = isConstructor;
this.isStatic = isStatic;
this.signature = signature;
this.instructions = instructions;
this.handlers = handlers;
this.instToBC = instToBC;
this.varTypes = vars;
}
/**
* Use class hierarchy information in 'h'. If this method is not called or h provides only partial
* hierarchy information, the verifier behaves optimistically.
*/
public final void setClassHierarchy(ClassHierarchyProvider h) {
this.hierarchy = h;
}
private void addBackEdge(int from, int to) {
int[] oldEdges = backEdges[from];
if (oldEdges == null) {
backEdges[from] = new int[] {to};
} else if (oldEdges[oldEdges.length - 1] < 0) {
int left = 1;
int right = oldEdges.length - 1;
while (true) {
if (right - left < 2) {
if (oldEdges[left] >= 0) {
if (oldEdges[right] >= 0) throw new Error("Failed binary search");
left = right;
}
break;
} else {
int mid = (left + right) / 2;
if (oldEdges[mid] < 0) {
right = mid;
} else {
left = mid + 1;
}
}
}
oldEdges[left] = to;
} else {
int[] newEdges = Arrays.copyOf(oldEdges, oldEdges.length * 2);
newEdges[oldEdges.length] = to;
for (int i = oldEdges.length + 1; i < newEdges.length; i++) {
newEdges[i] = -1;
}
backEdges[from] = newEdges;
}
}
public final int[][] getBackEdges() {
if (backEdges != null) {
return backEdges;
}
backEdges = new int[instructions.length][];
for (int i = 0; i < instructions.length; i++) {
IInstruction instr = instructions[i];
int[] targets = instr.getBranchTargets();
for (int target : targets) {
addBackEdge(target, i);
}
ExceptionHandler[] hs = handlers[i];
for (ExceptionHandler element : hs) {
addBackEdge(element.getHandler(), i);
}
}
for (int i = 0; i < backEdges.length; i++) {
int[] back = backEdges[i];
if (back == null) {
backEdges[i] = noEdges;
} else if (back[back.length - 1] < 0) {
int j = back.length;
while (back[j - 1] < 0) {
j--;
}
int[] newBack = new int[j];
System.arraycopy(back, 0, newBack, 0, newBack.length);
backEdges[i] = newBack;
}
}
return backEdges;
}
private String patchType(String t) {
if (t == thisType) {
return classType;
} else if (t != null && t.startsWith("#")) {
return stripSharp(t);
} else {
return t;
}
}
public final boolean isSubtypeOf(String t1, String t2) {
return ClassHierarchy.isSubtypeOf(hierarchy, patchType(t1), patchType(t2)) != ClassHierarchy.NO;
}
private static boolean isPrimitive(String type) {
return type != null && (!type.startsWith("L") && !type.startsWith("["));
}
public final String findCommonSupertype(String t1, String t2) {
if (String.valueOf(t1).equals(String.valueOf(t2))) {
return t1;
}
if (String.valueOf(t1).equals("L;") || String.valueOf(t2).equals("L;")) {
if (String.valueOf(t1).equals("L;")) {
return t2;
} else {
return t1;
}
}
if (t1 == thisType || t2 == thisType || t1 == topType || t2 == topType) {
return topType;
}
if (isPrimitive(t1) != isPrimitive(t2)) {
return topType;
}
String x = ClassHierarchy.findCommonSupertype(hierarchy, patchType(t1), patchType(t2));
return x;
}
public final BitSet getBasicBlockStarts() {
if (basicBlockStarts != null) {
return basicBlockStarts;
}
BitSet r = new BitSet(instructions.length);
r.set(0);
for (IInstruction instruction : instructions) {
int[] targets = instruction.getBranchTargets();
for (int target : targets) {
r.set(target);
}
}
for (ExceptionHandler[] hs : handlers) {
if (hs != null) {
for (ExceptionHandler element : hs) {
r.set(element.getHandler());
}
}
}
basicBlockStarts = r;
return r;
}
public final IInstruction[] getInstructions() {
return instructions;
}
private void getReachableRecursive(
int from, BitSet reachable, boolean followHandlers, BitSet mask)
throws IllegalArgumentException {
if (from < 0) {
throw new IllegalArgumentException("from < 0");
}
while (true) {
// stop if we've already visited this instruction or if we've gone outside
// the mask
if (reachable.get(from) || (mask != null && !mask.get(from))) {
return;
}
reachable.set(from);
IInstruction instr = instructions[from];
int[] targets = instr.getBranchTargets();
for (int target : targets) {
getReachableRecursive(target, reachable, followHandlers, mask);
}
if (followHandlers) {
ExceptionHandler[] hs = handlers[from];
for (ExceptionHandler element : hs) {
getReachableRecursive(element.getHandler(), reachable, followHandlers, mask);
}
}
if (instr.isFallThrough()) {
++from;
continue;
}
break;
}
}
public final BitSet getReachableFrom(int from) {
return getReachableFrom(from, true, null);
}
public final void getReachableFromUpdate(
int from, BitSet reachable, boolean followHandlers, BitSet mask) {
if (reachable == null) {
throw new IllegalArgumentException("reachable is null");
}
reachable.clear();
getReachableRecursive(from, reachable, followHandlers, mask);
}
public final BitSet getReachableFrom(int from, boolean followHandlers, BitSet mask) {
BitSet reachable = new BitSet();
getReachableRecursive(from, reachable, followHandlers, mask);
return reachable;
}
private void getReachingRecursive(int to, BitSet reaching, BitSet mask) {
while (true) {
// stop if we've already visited this instruction or if we've gone outside
// the mask
if (reaching.get(to) || (mask != null && !mask.get(to))) {
return;
}
reaching.set(to);
int[] targets = backEdges[to];
for (int target : targets) {
getReachingRecursive(target, reaching, mask);
}
if (to > 0 && instructions[to - 1].isFallThrough()) {
--to;
continue;
}
break;
}
}
private void getReachingBase(int to, BitSet reaching, BitSet mask) {
int[] targets = backEdges[to];
for (int target : targets) {
getReachingRecursive(target, reaching, mask);
}
if (to > 0 && instructions[to - 1].isFallThrough()) {
getReachingRecursive(to - 1, reaching, mask);
}
}
public final void getReachingToUpdate(int to, BitSet reaching, BitSet mask) {
if (reaching == null) {
throw new IllegalArgumentException("reaching is null");
}
getBackEdges();
reaching.clear();
getReachingBase(to, reaching, mask);
}
final BitSet getReachingTo(int to, BitSet mask) {
getBackEdges();
BitSet reaching = new BitSet();
getReachingBase(to, reaching, mask);
return reaching;
}
final BitSet getReachingTo(int to) {
return getReachingTo(to, null);
}
private void computeStackSizesAt(int[] stackSizes, int i, int size) throws FailureException {
while (true) {
if (stackSizes[i] >= 0) {
if (size != stackSizes[i]) {
throw new FailureException(i, "Stack size mismatch", null);
}
return;
}
stackSizes[i] = size;
IInstruction instr = instructions[i];
if (instr instanceof DupInstruction) {
size += ((DupInstruction) instr).getSize();
} else if (instr instanceof SwapInstruction) {
} else {
size -= instr.getPoppedCount();
if (instr.getPushedWordSize() > 0) {
size++;
}
}
int[] targets = instr.getBranchTargets();
for (int target : targets) {
computeStackSizesAt(stackSizes, target, size);
}
ExceptionHandler[] hs = handlers[i];
for (ExceptionHandler element : hs) {
computeStackSizesAt(stackSizes, element.getHandler(), 1);
}
if (!instr.isFallThrough()) {
return;
}
i++;
}
}
/** This exception is thrown by verify() when it fails. */
public static final class FailureException extends Exception {
private static final long serialVersionUID = -7663520961403117526L;
private final int offset;
private final String reason;
private List<PathElement> path;
FailureException(int offset, String reason, List<PathElement> path) {
super(reason + " at offset " + offset);
this.offset = offset;
this.reason = reason;
this.path = path;
}
/** @return the index of the Instruction which failed to verify */
public int getOffset() {
return offset;
}
/** @return a description of the reason why verification failed */
public String getReason() {
return reason;
}
/**
* @return a list of PathElements describing how the type that caused the error was propagated
* from its origin to the point of the error
*/
public List<PathElement> getPath() {
return path;
}
void setPath(List<PathElement> path) {
this.path = path;
}
/** Print the path to the given stream, if there is one. */
public void printPath(Writer w) throws IOException {
if (path != null) {
for (PathElement elem : path) {
String[] stack = elem.stack;
String[] locals = elem.locals;
w.write("Offset " + elem.index + ": [");
for (int j = 0; j < stack.length; j++) {
if (j > 0) {
w.write(",");
}
w.write(stack[j]);
}
w.write("], [");
for (int j = 0; j < locals.length; j++) {
if (j > 0) {
w.write(",");
}
w.write(locals[j] == null ? "?" : locals[j]);
}
w.write("]\n");
}
}
}
}
public static final class PathElement {
final int index;
final String[] stack;
final String[] locals;
PathElement(int index, String[] stack, String[] locals) {
this.stack = stack.clone();
this.locals = locals.clone();
this.index = index;
}
/** @return the bytecode offset of the instruction causing a value transfer. */
public int getIndex() {
return index;
}
/** @return the types of the local variabls at the instruction. */
public String[] getLocals() {
return locals;
}
/** @return the types of the working stack at the instruction. */
public String[] getStack() {
return stack;
}
}
private static String[] cutArray(String[] a, int len) {
if (len == 0) {
return noStrings;
} else {
String[] r = new String[len];
System.arraycopy(a, 0, r, 0, len);
return r;
}
}
private boolean mergeTypes(
int i,
String[] curStack,
int curStackSize,
String[] curLocals,
int curLocalsSize,
List<PathElement> path)
throws FailureException {
boolean a = mergeStackTypes(i, curStack, curStackSize, path);
boolean b = mergeLocalTypes(i, curLocals, curLocalsSize);
return a || b;
}
private static boolean longType(String type) {
return Constants.TYPE_long.equals(type) || Constants.TYPE_double.equals(type);
}
private boolean mergeStackTypes(
int i, String[] curStack, int curStackSize, List<PathElement> path) throws FailureException {
boolean changed = false;
if (stacks[i] == null) {
stacks[i] = cutArray(curStack, curStackSize);
changed = true;
} else {
String[] st = stacks[i];
if (st.length != curStackSize) {
throw new FailureException(
i, "Stack size mismatch: " + st.length + ", " + curStackSize, path);
}
for (int j = 0; j < curStackSize; j++) {
String t = findCommonSupertype(st[j], curStack[j]);
if (t != st[j]) {
if (t == null) {
throw new FailureException(
i, "Stack type mismatch at " + j + " (" + st[j] + " vs " + curStack[j] + ')', path);
}
st[j] = t;
changed = true;
}
}
}
return changed;
}
private boolean mergeLocalTypes(int i, String[] curLocals, int curLocalsSize) {
boolean changed = false;
if (locals[i] == null) {
locals[i] = cutArray(curLocals, curLocalsSize);
changed = true;
} else {
String[] ls = locals[i];
for (int lj = 0, cj = 0; lj < ls.length; lj++, cj++) {
String t = findCommonSupertype(ls[lj], curLocals[cj]);
if (t != ls[lj]) {
ls[lj] = t;
changed = true;
}
}
}
return changed;
}
public static String stripSharp(String type) {
return type.substring(type.lastIndexOf('#') + 1);
}
/** A PathElement describes a point where a value is moved from one location to another. */
private void computeTypes(int i, TypeVisitor visitor, BitSet makeTypesAt, List<PathElement> path)
throws FailureException {
final String[] curStack = new String[maxStack];
final String[] curLocals = new String[maxLocals];
while (true) {
if (path != null) {
path.add(new PathElement(i, stacks[i], locals[i]));
}
int curStackSize = stacks[i].length;
System.arraycopy(stacks[i], 0, curStack, 0, curStackSize);
final int[] curLocalsSize = {locals[i].length};
System.arraycopy(locals[i], 0, curLocals, 0, curLocalsSize[0]);
IInstruction.Visitor localsUpdate =
new IInstruction.Visitor() {
@Override
public void visitInvoke(IInvokeInstruction instruction) {
if (instruction.getInvocationCode() == Dispatch.SPECIAL) {
if (instruction.getMethodName().equals("<init>")) {
int sz =
Util.getParamsTypes(
instruction.getClassType(), instruction.getMethodSignature())
.length;
if (isConstructor) {
if (thisType.equals(curStack[sz - 1])) {
for (int i = 0; i < curLocals.length; i++) {
if (thisType.equals(curLocals[i])) {
curLocals[i] = classType;
}
}
for (int i = 0; i < curStack.length; i++) {
if (thisType.equals(curStack[i])) {
curStack[i] = classType;
}
}
}
}
if (curStack.length > sz
&& curStack[sz] != null
&& curStack[sz].startsWith("#")) {
curStack[sz] = stripSharp(curStack[sz]);
}
}
}
}
@Override
public void visitLocalLoad(ILoadInstruction instruction) {
String t = curLocals[instruction.getVarIndex()];
curStack[0] = t;
}
@Override
public void visitLocalStore(IStoreInstruction instruction) {
int index = instruction.getVarIndex();
String t = curStack[0];
curLocals[index] = t;
if (longType(t) && curLocals.length > index + 1) {
curLocals[index + 1] = null;
}
if (index >= curLocalsSize[0]) {
curLocalsSize[0] = index + (longType(t) && curLocals.length > index + 1 ? 2 : 1);
}
}
};
boolean restart = false;
while (true) {
IInstruction instr = instructions[i];
int popped = instr.getPoppedCount();
if (curStackSize < popped) {
throw new FailureException(i, "Stack underflow", path);
}
if (visitor != null) {
visitor.setState(i, path, curStack, curLocals);
instr.visit(visitor);
if (!visitor.shouldContinue()) {
return;
}
}
if (instr instanceof DupInstruction) {
DupInstruction d = (DupInstruction) instr;
int size = d.getSize();
System.arraycopy(curStack, popped, curStack, popped + size, curStackSize - popped);
System.arraycopy(curStack, 0, curStack, popped, size);
curStackSize += size;
} else if (instr instanceof SwapInstruction) {
String s = curStack[0];
curStack[0] = curStack[1];
curStack[1] = s;
} else {
@SuppressWarnings("NonConstantStringShouldBeStringBuffer")
String pushed = instr.getPushedType(curStack);
if (instr instanceof NewInstruction && !pushed.startsWith("[")) {
pushed = "#" + instToBC[i] + '#' + pushed;
}
if (pushed != null) {
System.arraycopy(curStack, popped, curStack, 1, curStackSize - popped);
curStack[0] = Util.getStackType(pushed);
instr.visit(localsUpdate); // visit localLoad after pushing
curStackSize -= popped - 1;
} else {
instr.visit(localsUpdate); // visit localStore before popping
System.arraycopy(curStack, popped, curStack, 0, curStackSize - popped);
curStackSize -= popped;
if (varTypes != null) {
if (instr instanceof IStoreInstruction) {
int local = ((IStoreInstruction) instr).getVarIndex();
if (Constants.TYPE_null.equals(curLocals[local])) {
for (int idx : new int[] {i, i + 1}) {
int bc = instToBC[idx];
if (bc == 667 && local == 16) {
System.err.println("got here");
}
if (bc != -1
&& varTypes != null
&& varTypes.length > bc
&& varTypes[bc] != null) {
if (varTypes[bc].length > local && varTypes[bc][local] != null) {
String declaredType = varTypes[bc][local];
curLocals[local] = declaredType;
}
}
}
}
}
}
}
}
ExceptionHandler[] handler = handlers[i];
for (ExceptionHandler element : handler) {
int target = element.getHandler();
String cls = element.getCatchClass();
if (cls == null) {
cls = "Ljava/lang/Throwable;";
}
String[] catchStack = new String[] {cls};
if (mergeTypes(target, catchStack, 1, curLocals, curLocalsSize[0], path)) {
computeTypes(target, visitor, makeTypesAt, path);
}
}
int[] targets = instr.getBranchTargets();
for (int target : targets) {
if (mergeTypes(target, curStack, curStackSize, curLocals, curLocalsSize[0], path)) {
computeTypes(target, visitor, makeTypesAt, path);
}
}
if (!instr.isFallThrough()) {
break;
} else {
i++;
if (makeTypesAt.get(i)) {
if (mergeTypes(i, curStack, curStackSize, curLocals, curLocalsSize[0], path)) {
restart = true;
break;
}
if (path != null) {
path.remove(path.size() - 1);
}
return;
}
}
}
if (!restart) {
break;
}
}
if (path != null) {
path.remove(path.size() - 1);
}
}
public int[] getStackSizes() throws FailureException {
if (stackSizes != null) {
return stackSizes;
}
stackSizes = new int[instructions.length];
Arrays.fill(stackSizes, -1);
computeStackSizesAt(stackSizes, 0, 0);
return stackSizes;
}
private void computeMaxLocals() {
maxLocals = locals[0].length;
for (IInstruction instr : instructions) {
if (instr instanceof LoadInstruction) {
maxLocals = Math.max(maxLocals, ((LoadInstruction) instr).getVarIndex() + 1);
} else if (instr instanceof StoreInstruction) {
maxLocals = Math.max(maxLocals, ((StoreInstruction) instr).getVarIndex() + 1);
}
}
}
protected final void initTypeInfo() throws FailureException {
stacks = new String[instructions.length][];
locals = new String[instructions.length][];
String thisType;
if (isConstructor) {
thisType = Analyzer.thisType;
} else {
thisType = classType;
}
stacks[0] = noStrings;
locals[0] = Util.getParamsTypesInLocals(isStatic ? null : thisType, signature);
if (isConstructor) {
for (int i = 0; i < locals[0].length; i++) {
if (classType.equals(locals[0][i])) {
locals[0][i] = thisType;
}
}
}
int[] stackSizes = getStackSizes();
maxStack = 0;
for (int stackSize : stackSizes) {
maxStack = Math.max(maxStack, stackSize);
}
computeMaxLocals();
}
/**
* Verify the method and compute types at every program point.
*
* @throws FailureException the method contains invalid bytecode
*/
public final void computeTypes(TypeVisitor v, BitSet makeTypesAt, boolean wantPath)
throws FailureException {
initTypeInfo();
computeTypes(0, v, makeTypesAt, wantPath ? new ArrayList<>() : null);
}
public abstract static class TypeVisitor extends IInstruction.Visitor {
public abstract void setState(
int index, List<PathElement> path, String[] curStack, String[] curLocals);
public abstract boolean shouldContinue();
}
/**
* @return an array indexed by instruction index; each entry is an array of Strings giving the
* types of the locals at that instruction.
*/
public final String[][] getLocalTypes() {
return locals;
}
/**
* @return an array indexed by instruction index; each entry is an array of Strings giving the
* types of the stack elements at that instruction. The top of the stack is the last element
* of the array.
*/
public final String[][] getStackTypes() {
return stacks;
}
protected Analyzer(MethodData info) {
this(
info.getName().equals("<init>"),
info.getIsStatic(),
info.getClassType(),
info.getSignature(),
info.getInstructions(),
info.getHandlers(),
info.getInstructionsToBytecodes(),
null);
}
protected Analyzer(MethodData info, int[] instToBC, String[][] vars) {
this(
info.getName().equals("<init>"),
info.getIsStatic(),
info.getClassType(),
info.getSignature(),
info.getInstructions(),
info.getHandlers(),
instToBC,
vars);
}
public static Analyzer createAnalyzer(MethodData info) {
if (info == null) {
throw new IllegalArgumentException("info is null");
}
return new Analyzer(info);
}
}
| 26,056
| 28.277528
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/analysis/ClassHierarchy.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.analysis;
import com.ibm.wala.shrike.shrikeBT.Constants;
import java.util.HashSet;
import java.util.Iterator;
/**
* This class takes the raw information from a ClassHierarchyProvider and computes type operations
* (subtype check, type union). All operations are static.
*
* <p>Because ClassHierarchyProvider sometimes only provides partial information, these routines
* sometimes answer "don't know".
*/
public final class ClassHierarchy {
private ClassHierarchy() {}
/** Equals Constants.NO */
public static final int NO = Constants.NO;
/** Equals Constants.YES */
public static final int YES = Constants.YES;
/** Equals Constants.MAYBE */
public static final int MAYBE = Constants.MAYBE;
private static int checkSuperinterfacesContain(
ClassHierarchyProvider hierarchy, String t1, String t2, HashSet<String> visited) {
String[] ifaces = hierarchy.getSuperInterfaces(t1);
if (ifaces == null) {
return MAYBE;
}
int r = NO;
for (String iface2 : ifaces) {
String iface = iface2;
if (visited.add(iface)) {
if (iface.equals(t2)) {
return YES;
} else {
int v = checkSuperinterfacesContain(hierarchy, iface, t2, visited);
switch (v) {
case YES:
return YES;
case MAYBE:
r = MAYBE;
break;
}
}
}
}
return r;
}
private static int checkSupertypesContain(
ClassHierarchyProvider hierarchy, String t1, String t2) {
int r = NO;
String c = t1;
while (true) {
String sup = hierarchy.getSuperClass(c);
if (sup == null) {
if (!c.equals(Constants.TYPE_Object)) {
r = MAYBE;
}
break;
}
if (sup.equals(t2)) {
return YES;
}
c = sup;
}
if (hierarchy.isInterface(t2) != NO) {
HashSet<String> visited = new HashSet<>();
for (c = t1; c != null; c = hierarchy.getSuperClass(c)) {
int v = checkSuperinterfacesContain(hierarchy, c, t2, visited);
switch (v) {
case YES:
return YES;
case MAYBE:
r = MAYBE;
break;
}
}
}
return r;
}
private static int checkSubtypesContain(
ClassHierarchyProvider hierarchy, String t1, String t2, HashSet<String> visited) {
// No interface is a subclass of a real class
if (hierarchy.isInterface(t1) == NO && hierarchy.isInterface(t2) == YES) {
return NO;
}
String[] subtypes = hierarchy.getSubClasses(t1);
if (subtypes == null) {
return MAYBE;
}
int r = NO;
for (String subtype : subtypes) {
String subt = subtype;
if (visited.add(subt)) {
if (subt.equals(t2)) {
return YES;
} else {
int v = checkSubtypesContain(hierarchy, subt, t2, visited);
switch (v) {
case YES:
return YES;
case MAYBE:
r = MAYBE;
break;
}
}
}
}
return r;
}
private static int checkSubtypeOfHierarchy(
ClassHierarchyProvider hierarchy, String t1, String t2) {
if (t2.equals(Constants.TYPE_Object)) {
return YES;
} else {
int v = checkSupertypesContain(hierarchy, t1, t2);
if (v == MAYBE) {
v = checkSubtypesContain(hierarchy, t2, t1, new HashSet<>());
}
return v;
}
}
/**
* Perform subtype check.
*
* @param hierarchy the hierarchy information to use for the decision
* @param t1 a type in JVM format
* @param t2 a type in JVM format
* @return whether t1 is a subtype of t2 (YES, NO, MAYBE)
*/
public static int isSubtypeOf(ClassHierarchyProvider hierarchy, String t1, String t2) {
if (t1 == null || t2 == null) {
return NO;
} else if (t1.equals(t2)) {
return YES;
} else if (t1.equals(Constants.TYPE_unknown) || t2.equals(Constants.TYPE_unknown)) {
return MAYBE;
} else {
switch (t1.charAt(0)) {
case 'L':
if (t1.equals(Constants.TYPE_null)) {
return YES;
} else if (t2.startsWith("[")) {
return NO;
} else if (hierarchy == null) {
return MAYBE;
} else {
return checkSubtypeOfHierarchy(hierarchy, t1, t2);
}
case '[':
if (t2.equals(Constants.TYPE_Object)
|| t2.equals("Ljava/io/Serializable;")
|| t2.equals("Ljava/lang/Cloneable;")) {
return YES;
} else if (t2.startsWith("[")) {
return isSubtypeOf(hierarchy, t1.substring(1), t2.substring(1));
} else {
return NO;
}
default:
return NO;
}
}
}
private static boolean insertSuperInterfaces(
ClassHierarchyProvider hierarchy, String t, HashSet<String> supers) {
String[] ifaces = hierarchy.getSuperInterfaces(t);
if (ifaces == null) {
return false;
} else {
boolean r = true;
for (String iface : ifaces) {
if (supers.add(iface)) {
if (!insertSuperInterfaces(hierarchy, iface, supers)) {
r = false;
}
}
}
return r;
}
}
private static boolean insertSuperClasses(
ClassHierarchyProvider hierarchy, String t, HashSet<String> supers) {
String last = t;
for (String c = t; c != null; c = hierarchy.getSuperClass(c)) {
supers.add(c);
last = c;
}
return last.equals(Constants.TYPE_Object);
}
private static boolean insertSuperClassInterfaces(
ClassHierarchyProvider hierarchy, String t, HashSet<String> supers) {
boolean r = true;
for (String c = t; c != null; c = hierarchy.getSuperClass(c)) {
if (!insertSuperInterfaces(hierarchy, c, supers)) {
r = false;
}
}
return r;
}
private static boolean collectDominatingSuperClasses(
ClassHierarchyProvider hierarchy, String t, HashSet<String> matches, HashSet<String> supers) {
String last = t;
for (String c = t; c != null; c = hierarchy.getSuperClass(c)) {
if (matches.contains(c)) {
supers.add(c);
return true;
}
last = c;
}
return last.equals(Constants.TYPE_Object);
}
private static boolean collectDominatingSuperInterfacesFromClass(
ClassHierarchyProvider hierarchy, String t, HashSet<String> supers) {
String[] ifaces = hierarchy.getSuperInterfaces(t);
if (ifaces == null) {
return false;
} else {
boolean r = true;
for (String iface : ifaces) {
if (supers.add(iface)) {
if (!insertSuperInterfaces(hierarchy, iface, supers)) {
r = false;
}
}
}
return r;
}
}
private static boolean collectDominatingSuperInterfaces(
ClassHierarchyProvider hierarchy, String t, HashSet<String> supers) {
boolean r = true;
for (String c = t; c != null && !supers.contains(c); c = hierarchy.getSuperClass(c)) {
if (!collectDominatingSuperInterfacesFromClass(hierarchy, c, supers)) {
r = false;
}
}
return r;
}
private static String findCommonSupertypeHierarchy(
ClassHierarchyProvider hierarchy, String t1, String t2) {
if (isSubtypeOf(hierarchy, t1, t2) == YES) {
return t2;
} else if (isSubtypeOf(hierarchy, t2, t1) == YES) {
return t1;
}
HashSet<String> t1Supers = new HashSet<>();
t1Supers.add(Constants.TYPE_Object);
boolean t1ExactClasses = insertSuperClasses(hierarchy, t1, t1Supers);
int t1ClassCount = t1Supers.size();
boolean t1ExactInterfaces = insertSuperClassInterfaces(hierarchy, t1, t1Supers);
HashSet<String> t2Supers = new HashSet<>();
boolean t2ExactClasses = collectDominatingSuperClasses(hierarchy, t2, t1Supers, t2Supers);
if (t2Supers.size() == 0) {
// we didn't find a common superclass, so we don't know what it might be
return Constants.TYPE_unknown;
} // otherwise we know for sure what the common superclass is
boolean t2ExactInterfaces;
if (t1ExactInterfaces && t1ExactClasses && t1Supers.size() - t1ClassCount == 0) {
// t1 doesn't have any interfaces so we don't need to search t2's
// interfaces
t2ExactInterfaces = true;
} else {
t2ExactInterfaces = collectDominatingSuperInterfaces(hierarchy, t2, t2Supers);
if (!t1ExactInterfaces && t2Supers.size() != 1) {
// we found an interface; it might also apply to t1; must bail
return Constants.TYPE_unknown;
}
}
if (!t2ExactClasses || !t2ExactInterfaces) {
// there may be some common interfaces that we don't know about
return "";
}
for (Iterator<String> iter = t2Supers.iterator(); iter.hasNext(); ) {
String element = iter.next();
boolean subsumed = false;
for (String element2 : t2Supers) {
if (element != element2 && isSubtypeOf(hierarchy, element2, element) == YES) {
subsumed = true;
break;
}
}
if (subsumed) {
iter.remove();
}
}
if (t2Supers.size() == 1) {
return t2Supers.iterator().next();
} else if (t2Supers.size() == 0) {
return Constants.TYPE_Object;
} else {
return Constants.TYPE_unknown; // some non-representable combination of
// class and interfaces
}
}
/**
* Compute the most specific common supertype.
*
* @param hierarchy the hierarchy information to use for the decision
* @param t1 a type in JVM format
* @param t2 a type in JVM format
* @return the most specific common supertype of t1 and t2, or TYPE_unknown if it cannot be
* determined or cannot be represented as a Java type, or null if there is no common supertype
*/
public static String findCommonSupertype(ClassHierarchyProvider hierarchy, String t1, String t2) {
if (t1 == null || t2 == null) {
return null;
} else if (t1.equals(t2)) {
return t1;
} else if (t1.equals(Constants.TYPE_unknown) || t2.equals(Constants.TYPE_unknown)) {
return Constants.TYPE_unknown;
} else {
if (t2.charAt(0) == '[') { // put array into t1
String t = t1;
t1 = t2;
t2 = t;
}
switch (t1.charAt(0)) {
case 'L':
// two non-array types
// if either one is constant null, return the other one
if (t1.equals(Constants.TYPE_null)) {
return t2;
} else if (t2.equals(Constants.TYPE_null)) {
return t1;
} else if (hierarchy == null) {
// don't have a class hierarchy
return Constants.TYPE_unknown;
} else {
return findCommonSupertypeHierarchy(hierarchy, t1, t2);
}
case '[':
{
char ch2 = t2.charAt(0);
switch (ch2) {
case '[':
char ch1_1 = t1.charAt(1);
if (ch1_1 == '[' || ch1_1 == 'L') {
return '[' + findCommonSupertype(hierarchy, t1.substring(1), t2.substring(1));
} else {
return Constants.TYPE_Object;
}
case 'L':
switch (t2) {
case Constants.TYPE_null:
return t1;
case "Ljava/io/Serializable;":
case "Ljava/lang/Cloneable;":
return t2;
default:
return Constants.TYPE_Object;
}
default:
return null;
}
}
default:
return null;
}
}
}
}
| 12,136
| 28.245783
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/analysis/ClassHierarchyProvider.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.analysis;
/**
* This interface provides information about the class hierarchy to some consumer, such as a
* bytecode verifier.
*
* <p>All class names are given in JVM type format, e.g., Ljava/lang/Object;.
*/
public interface ClassHierarchyProvider {
/**
* @return the superclass of the given class, or null if the superclass is not known or cl is
* java.lang.Object
*/
String getSuperClass(String cl);
/** @return the superinterfaces of the given class, or null if they are not known */
String[] getSuperInterfaces(String cl);
/**
* @return the complete set of direct subclasses or implementors of cl, or null if the complete
* set is not known
*/
String[] getSubClasses(String cl);
/** @return whether or not cl is an interface, or Constants.MAYBE if not known */
int isInterface(String cl);
}
| 1,257
| 32.105263
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/analysis/ClassHierarchyStore.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.analysis;
import com.ibm.wala.shrike.shrikeBT.Constants;
import java.util.HashMap;
import java.util.Iterator;
/**
* This implementation of ClassHierarchyProvider is a simple writable data structure representing a
* class hierarchy. You call setClassInfo to record information about a class.
*/
public final class ClassHierarchyStore implements ClassHierarchyProvider {
private static final String[] noClasses = new String[0];
static final class ClassInfo {
final boolean isInterface;
final boolean isFinal;
final String superClass;
final String[] superInterfaces;
ClassInfo(boolean isInterface, boolean isFinal, String superClass, String[] superInterfaces) {
this.isInterface = isInterface;
this.isFinal = isFinal;
this.superClass = superClass;
this.superInterfaces = superInterfaces;
}
}
private final HashMap<String, ClassInfo> contents = new HashMap<>();
/** Create an empty store. */
public ClassHierarchyStore() {}
public boolean containsClass(String cl) {
return contents.containsKey(cl);
}
/**
* Append some class information to the store.
*
* @param cl the JVM type of the class being added (e.g., Ljava/lang/Object;)
* @param isInterface true iff it's an interface
* @param isFinal true iff it's final
* @param superClass the JVM type of the superclass, or null if this is Object
* @param superInterfaces the JVM types of its implemented interfaces
*/
public void setClassInfo(
String cl, boolean isInterface, boolean isFinal, String superClass, String[] superInterfaces)
throws IllegalArgumentException {
if (superClass != null && superClass.equals(cl)) {
throw new IllegalArgumentException("Class " + cl + " cannot be its own superclass");
}
contents.put(cl, new ClassInfo(isInterface, isFinal, superClass, superInterfaces));
}
/** Delete the class information from the store. */
public void removeClassInfo(String cl) {
contents.remove(cl);
}
/** Iterate through all classes in the store. */
public Iterator<String> iterateOverClasses() {
return contents.keySet().iterator();
}
@Override
public String getSuperClass(String cl) {
ClassInfo info = contents.get(cl);
return info == null ? null : info.superClass;
}
@Override
public String[] getSuperInterfaces(String cl) {
ClassInfo info = contents.get(cl);
return info == null ? null : info.superInterfaces;
}
@Override
public String[] getSubClasses(String cl) {
ClassInfo info = contents.get(cl);
return (info == null || !info.isFinal) ? null : noClasses;
}
@Override
public int isInterface(String cl) {
ClassInfo info = contents.get(cl);
return info == null ? Constants.MAYBE : (info.isInterface ? Constants.YES : Constants.NO);
}
}
| 3,229
| 30.666667
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/analysis/Verifier.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.analysis;
import com.ibm.wala.shrike.shrikeBT.ArrayLengthInstruction;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.DupInstruction;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.GotoInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayLoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.IComparisonInstruction;
import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction;
import com.ibm.wala.shrike.shrikeBT.IConversionInstruction;
import com.ibm.wala.shrike.shrikeBT.IGetInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstanceofInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.ILoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IPutInstruction;
import com.ibm.wala.shrike.shrikeBT.IShiftInstruction;
import com.ibm.wala.shrike.shrikeBT.IStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.ITypeTestInstruction;
import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.InvokeDynamicInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.MonitorInstruction;
import com.ibm.wala.shrike.shrikeBT.NewInstruction;
import com.ibm.wala.shrike.shrikeBT.PopInstruction;
import com.ibm.wala.shrike.shrikeBT.ReturnInstruction;
import com.ibm.wala.shrike.shrikeBT.SwitchInstruction;
import com.ibm.wala.shrike.shrikeBT.ThrowInstruction;
import com.ibm.wala.shrike.shrikeBT.Util;
import java.util.BitSet;
import java.util.List;
/**
* This class typechecks intermediate code. It's very easy to use:
*
* <pre>
*
* MethodData md = ...;
* try {
* (new Verifier(md)).verify();
* } catch (Verifier.FailureException ex) {
* System.out.println("Verification failed at instruction "
* + ex.getOffset() + ": " + ex.getReason());
* }
*
* </pre>
*
* For full verification you need to provide class hierarchy information using setClassHierarchy.
* Without this information, we can't compute the exact types of variables at control flow merge
* points. If you don't provide a hierarchy, or the hierarchy you provide is partial, then the
* Verifier will be optimistic.
*
* <p>This method can also be used to gather type information for every stack and local variable at
* every program point. Just call computeTypes() instead of verify() and then retrieve the results
* with getLocalTypes() and getStackTypes().
*/
public final class Verifier extends Analyzer {
final class VerifyVisitor extends TypeVisitor {
private int curIndex;
private List<PathElement> curPath;
private FailureException ex;
private String[] curStack;
private String[] curLocals;
VerifyVisitor() {}
@Override
public void setState(
int offset, List<PathElement> path, String[] curStack, String[] curLocals) {
curIndex = offset;
curPath = path;
this.curStack = curStack;
this.curLocals = curLocals;
}
@Override
public boolean shouldContinue() {
return ex == null;
}
void checkError() throws FailureException {
if (ex != null) {
throw ex;
}
}
private void checkStackSubtype(int i, String t) {
if (!isSubtypeOf(curStack[i], Util.getStackType(t))) {
ex =
new FailureException(
curIndex,
"Expected type " + t + " at stack " + i + ", got " + curStack[i],
curPath);
}
}
private void checkArrayStackSubtype(int i, String t) {
if (!t.equals(Constants.TYPE_byte) || !"[Z".equals(curStack[i])) {
checkStackSubtype(i, Util.makeArray(t));
}
}
@Override
public void visitConstant(ConstantInstruction instruction) {
// make sure that constants are checked
instruction.getValue();
}
@Override
public void visitGoto(GotoInstruction instruction) {}
@Override
public void visitLocalLoad(ILoadInstruction instruction) {
String t = curLocals[instruction.getVarIndex()];
if (t == null) {
ex =
new FailureException(
curIndex,
"Local variable " + instruction.getVarIndex() + " is not defined",
curPath);
}
if (!isSubtypeOf(t, instruction.getType())) {
ex =
new FailureException(
curIndex,
"Expected type "
+ instruction.getType()
+ " for local "
+ instruction.getVarIndex()
+ ", got "
+ t,
curPath);
}
}
@Override
public void visitLocalStore(IStoreInstruction instruction) {
checkStackSubtype(0, instruction.getType());
}
@Override
public void visitArrayLoad(IArrayLoadInstruction instruction) {
checkStackSubtype(0, Constants.TYPE_int);
checkArrayStackSubtype(1, instruction.getType());
}
@Override
public void visitArrayStore(IArrayStoreInstruction instruction) {
checkStackSubtype(0, instruction.getType());
checkStackSubtype(1, Constants.TYPE_int);
checkArrayStackSubtype(2, instruction.getType());
}
@Override
public void visitPop(PopInstruction instruction) {}
@Override
public void visitDup(DupInstruction instruction) {}
@Override
public void visitBinaryOp(IBinaryOpInstruction instruction) {
checkStackSubtype(0, instruction.getType());
checkStackSubtype(1, instruction.getType());
}
@Override
public void visitUnaryOp(IUnaryOpInstruction instruction) {
checkStackSubtype(0, instruction.getType());
}
@Override
public void visitShift(IShiftInstruction instruction) {
checkStackSubtype(0, Constants.TYPE_int);
checkStackSubtype(1, instruction.getType());
}
@Override
public void visitConversion(IConversionInstruction instruction) {
checkStackSubtype(0, instruction.getFromType());
}
@Override
public void visitComparison(IComparisonInstruction instruction) {
checkStackSubtype(0, instruction.getType());
checkStackSubtype(1, instruction.getType());
}
@Override
public void visitConditionalBranch(IConditionalBranchInstruction instruction) {
checkStackSubtype(0, instruction.getType());
checkStackSubtype(1, instruction.getType());
}
@Override
public void visitSwitch(SwitchInstruction instruction) {
checkStackSubtype(0, Constants.TYPE_int);
}
@Override
public void visitReturn(ReturnInstruction instruction) {
if (instruction.getType() != Constants.TYPE_void) {
checkStackSubtype(0, instruction.getType());
checkStackSubtype(0, Util.getReturnType(signature));
}
}
@Override
public void visitGet(IGetInstruction instruction) {
// make sure constant pool entries are dereferenced
String classType = instruction.getClassType();
if (!instruction.isStatic()) {
checkStackSubtype(0, classType);
}
}
@Override
public void visitPut(IPutInstruction instruction) {
// make sure constant pool entries are dereferenced
String classType = instruction.getClassType();
String type = instruction.getFieldType();
checkStackSubtype(0, type);
if (!instruction.isStatic()) {
checkStackSubtype(1, classType);
}
}
@Override
public void visitInvoke(IInvokeInstruction instruction) {
if (instruction instanceof InvokeDynamicInstruction) {
return;
}
// make sure constant pool entries are dereferenced
String classType = instruction.getClassType();
String signature = instruction.getMethodSignature();
String thisClass =
instruction.getInvocationCode() == IInvokeInstruction.Dispatch.STATIC ? null : classType;
String[] params = Util.getParamsTypes(thisClass, signature);
for (int i = 0; i < params.length; i++) {
checkStackSubtype(i, params[params.length - 1 - i]);
}
}
@Override
public void visitNew(NewInstruction instruction) {
for (int i = 0; i < instruction.getArrayBoundsCount(); i++) {
checkStackSubtype(i, Constants.TYPE_int);
}
// make sure constant is dereferenced
instruction.getType();
}
@Override
public void visitArrayLength(ArrayLengthInstruction instruction) {
if (!curStack[0].equals(Constants.TYPE_null) && !Util.isArrayType(curStack[0])) {
ex =
new FailureException(
curIndex, "Expected array type at stack 0, got " + curStack[0], curPath);
}
}
@Override
public void visitThrow(ThrowInstruction instruction) {
checkStackSubtype(0, Constants.TYPE_Throwable);
}
@Override
public void visitMonitor(MonitorInstruction instruction) {
checkStackSubtype(0, Constants.TYPE_Object);
}
@Override
public void visitCheckCast(ITypeTestInstruction instruction) {
checkStackSubtype(0, Constants.TYPE_Object);
// make sure constant is dereferenced
instruction.getTypes();
}
@Override
public void visitInstanceof(IInstanceofInstruction instruction) {
checkStackSubtype(0, Constants.TYPE_Object);
// make sure constant is dereferenced
instruction.getType();
}
}
/** Initialize a verifier. */
public Verifier(
boolean isConstructor,
boolean isStatic,
String classType,
String signature,
IInstruction[] instructions,
ExceptionHandler[][] handlers,
int[] instToBC,
String[][] vars) {
super(isConstructor, isStatic, classType, signature, instructions, handlers, instToBC, vars);
}
/**
* Initialize a verifier.
*
* @throws NullPointerException if info is null
*/
public Verifier(MethodData info) throws NullPointerException {
super(info);
}
public Verifier(MethodData info, int[] instToBC, String[][] vars) throws NullPointerException {
super(info, instToBC, vars);
}
/**
* Try to verify the method. If verification is unsuccessful, we throw an exception.
*
* @throws FailureException the method contains invalid bytecode
*/
public void verify() throws FailureException {
VerifyVisitor v = new VerifyVisitor();
computeTypes(v, getBasicBlockStarts(), true);
v.checkError();
}
public void verifyCollectAll() throws FailureException {
VerifyVisitor v = new VerifyVisitor();
BitSet all = new BitSet(instructions.length);
all.set(0, instructions.length);
computeTypes(v, all, true);
v.checkError();
}
public void computeTypes() throws FailureException {
computeTypes(null, getBasicBlockStarts(), false);
}
}
| 11,476
| 31.058659
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/info/InstructionTypeCounter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.info;
import com.ibm.wala.shrike.shrikeBT.ArrayLengthInstruction;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.DupInstruction;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.GotoInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayLoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.IComparisonInstruction;
import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction;
import com.ibm.wala.shrike.shrikeBT.IConversionInstruction;
import com.ibm.wala.shrike.shrikeBT.IGetInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstanceofInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.ILoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IPutInstruction;
import com.ibm.wala.shrike.shrikeBT.IShiftInstruction;
import com.ibm.wala.shrike.shrikeBT.IStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.ITypeTestInstruction;
import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.MonitorInstruction;
import com.ibm.wala.shrike.shrikeBT.NewInstruction;
import com.ibm.wala.shrike.shrikeBT.PopInstruction;
import com.ibm.wala.shrike.shrikeBT.ReturnInstruction;
import com.ibm.wala.shrike.shrikeBT.SwapInstruction;
import com.ibm.wala.shrike.shrikeBT.SwitchInstruction;
import com.ibm.wala.shrike.shrikeBT.ThrowInstruction;
/**
* This method annotation counts the number of instructions of each type (according to each
* Instruction subclass).
*
* <p>The get...Count methods are the only methods needed by clients. These methods check to see if
* the MethodData object already has an InstructionTypeCounter annotation before recomputing the
* counts and returning the desired count.
*/
public class InstructionTypeCounter implements MethodData.Results {
private static final String key = InstructionTypeCounter.class.getName();
private int countMonitors;
private int countGets;
private int countPuts;
private int countArrayLoads;
private int countArrayStores;
private int countInvokes;
private int countArrayLengths;
private int countBinaryOps;
private int countCheckCasts;
private int countComparisons;
private int countConditionalBranches;
private int countConstants;
private int countConversions;
private int countDups;
private int countGotos;
private int countInstanceOfs;
private int countLocalLoads;
private int countLocalStores;
private int countNews;
private int countPops;
private int countReturns;
private int countShifts;
private int countSwaps;
private int countSwitches;
private int countThrows;
private int countUnaryOps;
InstructionTypeCounter(MethodData info) {
recalculateFrom(info.getInstructions());
}
private void recalculateFrom(IInstruction[] instructions) {
countMonitors = 0;
countGets = 0;
countPuts = 0;
countArrayLoads = 0;
countArrayStores = 0;
countInvokes = 0;
countArrayLengths = 0;
countBinaryOps = 0;
countCheckCasts = 0;
countComparisons = 0;
countConditionalBranches = 0;
countConstants = 0;
countConversions = 0;
countDups = 0;
countGotos = 0;
countInstanceOfs = 0;
countLocalLoads = 0;
countLocalStores = 0;
countNews = 0;
countPops = 0;
countReturns = 0;
countShifts = 0;
countSwaps = 0;
countSwitches = 0;
countThrows = 0;
countUnaryOps = 0;
IInstruction.Visitor visitor =
new IInstruction.Visitor() {
@Override
public void visitArrayLength(ArrayLengthInstruction instruction) {
countArrayLengths++;
}
@Override
public void visitBinaryOp(IBinaryOpInstruction instruction) {
countBinaryOps++;
}
@Override
public void visitCheckCast(ITypeTestInstruction instruction) {
countCheckCasts++;
}
@Override
public void visitComparison(IComparisonInstruction instruction) {
countComparisons++;
}
@Override
public void visitConditionalBranch(IConditionalBranchInstruction instruction) {
countConditionalBranches++;
}
@Override
public void visitConstant(ConstantInstruction instruction) {
countConstants++;
}
@Override
public void visitConversion(IConversionInstruction instruction) {
countConversions++;
}
@Override
public void visitDup(DupInstruction instruction) {
countDups++;
}
@Override
public void visitGoto(GotoInstruction instruction) {
countGotos++;
}
@Override
public void visitInstanceof(IInstanceofInstruction instruction) {
countInstanceOfs++;
}
@Override
public void visitLocalLoad(ILoadInstruction instruction) {
countLocalLoads++;
}
@Override
public void visitLocalStore(IStoreInstruction instruction) {
countLocalStores++;
}
@Override
public void visitNew(NewInstruction instruction) {
countNews++;
}
@Override
public void visitPop(PopInstruction instruction) {
countPops++;
}
@Override
public void visitReturn(ReturnInstruction instruction) {
countReturns++;
}
@Override
public void visitShift(IShiftInstruction instruction) {
countShifts++;
}
@Override
public void visitSwap(SwapInstruction instruction) {
countSwaps++;
}
@Override
public void visitSwitch(SwitchInstruction instruction) {
countSwitches++;
}
@Override
public void visitThrow(ThrowInstruction instruction) {
countThrows++;
}
@Override
public void visitUnaryOp(IUnaryOpInstruction instruction) {
countUnaryOps++;
}
@Override
public void visitArrayLoad(IArrayLoadInstruction instruction) {
countArrayLoads++;
}
@Override
public void visitArrayStore(IArrayStoreInstruction instruction) {
countArrayStores++;
}
@Override
public void visitGet(IGetInstruction instruction) {
countGets++;
}
@Override
public void visitPut(IPutInstruction instruction) {
countPuts++;
}
@Override
public void visitMonitor(MonitorInstruction instruction) {
countMonitors++;
}
@Override
public void visitInvoke(IInvokeInstruction instruction) {
countInvokes++;
}
};
for (IInstruction instruction : instructions) {
instruction.visit(visitor);
}
}
/**
* Whenever the underlying method is updated, we'll throw away our counts so they can be
* reconstructed from scratch next time.
*
* <p>This is not to be called by clients.
*/
@Override
public boolean notifyUpdate(
MethodData info,
IInstruction[] newInstructions,
ExceptionHandler[][] newHandlers,
int[] newInstructionMap) {
// just throw this away and we'll recalculate from scratch if necessary
return true;
}
public static int getArrayLoadCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countArrayLoads;
}
public static int getArrayStoreCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countArrayStores;
}
public static int getGetCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countGets;
}
public static int getPutCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countPuts;
}
public static int getMonitorCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countMonitors;
}
public static int getInvokeCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countInvokes;
}
public static int getComparisonCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countComparisons;
}
public static int getArrayLengthCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countArrayLengths;
}
public static int getConstantCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countConstants;
}
public static int getShiftCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countShifts;
}
public static int getSwitchesCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countSwitches;
}
public static int getSwapCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countSwaps;
}
public static int getBinaryOpCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countBinaryOps;
}
public static int getCheckCastCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countCheckCasts;
}
public static int getThrowCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countThrows;
}
public static int getConditionalBranchCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countConditionalBranches;
}
public static int getConversionCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countConversions;
}
public static int getDupCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countDups;
}
public static int getGotoCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countGotos;
}
public static int getReturnCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countReturns;
}
public static int getInstanceOfCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countInstanceOfs;
}
public static int getLocalLoadCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countLocalLoads;
}
public static int getLocalStoreCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countLocalStores;
}
public static int getNewCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countNews;
}
public static int getPopCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countPops;
}
public static int getUnaryOpCount(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
return getCounter(info).countUnaryOps;
}
private static InstructionTypeCounter getCounter(MethodData info) {
InstructionTypeCounter c = (InstructionTypeCounter) info.getInfo(key);
if (c == null) {
c = new InstructionTypeCounter(info);
info.putInfo(key, c);
}
return c;
}
}
| 13,881
| 27.681818
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/info/LocalAllocator.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.info;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.ILoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.Util;
/**
* This method annotation parcels out fresh local variables for use as temporaries by
* instrumentation code. It assumes that local variables are not allocated by any other mechanism.
*/
public class LocalAllocator implements MethodData.Results {
private static final String key = LocalAllocator.class.getName();
private int nextLocal;
LocalAllocator(MethodData info) {
recalculateFrom(info);
}
private void recalculateFrom(MethodData info) {
IInstruction[] instructions = info.getInstructions();
final int[] max = {Util.getParamsWordSize(info.getSignature()) + (info.getIsStatic() ? 0 : 1)};
IInstruction.Visitor visitor =
new IInstruction.Visitor() {
@Override
public void visitLocalLoad(ILoadInstruction instruction) {
int v = instruction.getVarIndex() + Util.getWordSize(instruction.getType());
if (v > max[0]) {
max[0] = v;
}
}
@Override
public void visitLocalStore(IStoreInstruction instruction) {
int v = instruction.getVarIndex() + Util.getWordSize(instruction.getType());
if (v > max[0]) {
max[0] = v;
}
}
};
for (IInstruction instruction : instructions) {
instruction.visit(visitor);
}
nextLocal = max[0];
}
private int allocateLocals(int count) {
int r = nextLocal;
nextLocal += count;
return r;
}
/** This should not be called by clients. */
@Override
public boolean notifyUpdate(
MethodData info,
IInstruction[] newInstructions,
ExceptionHandler[][] newHandlers,
int[] newInstructionMap) {
return false;
}
/** Allocates a new local variable of the specified type. */
public static int allocate(MethodData info, int count) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
LocalAllocator l = (LocalAllocator) info.getInfo(key);
if (l == null) {
l = new LocalAllocator(info);
info.putInfo(key, l);
}
return l.allocateLocals(count);
}
public static int allocate(MethodData info, String type) throws IllegalArgumentException {
return allocate(info, type == null ? 2 : Util.getWordSize(type));
}
/** Allocates a new local that will fit any type. */
public static int allocate(MethodData info) throws IllegalArgumentException {
return allocate(info, null);
}
}
| 3,192
| 30.303922
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/info/ThisAssignmentChecker.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.info;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.StoreInstruction;
/**
* This method annotation checks to see whether "this" is assigned to by the method. The result is
* cached in an annotation.
*/
public class ThisAssignmentChecker implements MethodData.Results {
private static final String key = ThisAssignmentChecker.class.getName();
private boolean assignmentToThis;
ThisAssignmentChecker(MethodData info) {
recalculateFrom(info);
}
private void recalculateFrom(MethodData info) {
assignmentToThis = false;
if (!info.getIsStatic()) {
IInstruction[] instructions = info.getInstructions();
for (IInstruction instr : instructions) {
if (instr instanceof StoreInstruction) {
StoreInstruction st = (StoreInstruction) instr;
if (st.getVarIndex() == 0) {
assignmentToThis = true;
}
}
}
}
}
/** This should not be called by any client. */
@Override
public boolean notifyUpdate(
MethodData info,
IInstruction[] newInstructions,
ExceptionHandler[][] newHandlers,
int[] newInstructionMap) {
// just throw this away and we'll recalculate from scratch if necessary
return true;
}
/** @return true iff 'this' is assigned to by the method */
public static boolean isThisAssigned(MethodData info) throws IllegalArgumentException {
if (info == null) {
throw new IllegalArgumentException();
}
ThisAssignmentChecker c = (ThisAssignmentChecker) info.getInfo(key);
if (c == null) {
c = new ThisAssignmentChecker(info);
info.putInfo(key, c);
}
return c.assignmentToThis;
}
}
| 2,219
| 29.410959
| 98
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/CTCompiler.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT;
import com.ibm.wala.shrike.shrikeBT.Compiler;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser.ReferenceToken;
import java.util.Random;
/**
* This class lets you compile ShrikeBT intermediate code into real Java bytecodes using ShrikeCT.
*/
public final class CTCompiler extends Compiler {
private final ClassWriter cw;
private final Random random = new Random();
/** Compile 'md' into the class given by 'cw'. */
private CTCompiler(ClassWriter cw, MethodData md) {
super(md);
this.cw = cw;
}
@Override
protected int allocateConstantPoolInteger(int v) {
return cw.addCPInt(v);
}
@Override
protected int allocateConstantPoolFloat(float v) {
return cw.addCPFloat(v);
}
@Override
protected int allocateConstantPoolLong(long v) {
return cw.addCPLong(v);
}
@Override
protected int allocateConstantPoolDouble(double v) {
return cw.addCPDouble(v);
}
@Override
protected int allocateConstantPoolString(String v) {
return cw.addCPString(v);
}
@Override
protected int allocateConstantPoolClassType(String c) {
return cw.addCPClass(convertTypeToClass(c));
}
@Override
protected int allocateConstantPoolMethodType(String c) {
return cw.addCPMethodType(c);
}
@Override
protected int allocateConstantPoolMethodHandle(ReferenceToken c) {
return cw.addCPMethodHandle(c);
}
@Override
protected int allocateConstantPoolInvokeDynamic(BootstrapMethod b, String name, String type) {
return cw.addCPInvokeDynamic(b, name, type);
}
/**
* Convert a JVM type to the internal JVM class name (e.g., Ljava/lang/Object; to
* java/lang/Object)
*
* @throws IllegalArgumentException if s is null
*/
public static String convertTypeToClass(String s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
if (s.length() > 0 && s.charAt(0) == 'L') {
return s.substring(1, s.length() - 1);
} else {
return s;
}
}
public static CTCompiler make(ClassWriter cw, MethodData md) {
if (md == null) {
throw new IllegalArgumentException("md is null");
}
return new CTCompiler(cw, md);
}
@Override
protected int allocateConstantPoolField(String c, String name, String type) {
return cw.addCPFieldRef(convertTypeToClass(c), name, type);
}
@Override
protected int allocateConstantPoolMethod(String c, String name, String sig) {
return cw.addCPMethodRef(convertTypeToClass(c), name, sig);
}
@Override
protected int allocateConstantPoolInterfaceMethod(String c, String name, String sig) {
return cw.addCPInterfaceMethodRef(convertTypeToClass(c), name, sig);
}
@Override
protected String createHelperMethod(boolean isStatic, String sig) {
long r = Math.abs(random.nextLong());
String name = "_helper_" + r;
return name;
}
}
| 3,448
| 26.373016
| 98
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/CTDecoder.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT;
import com.ibm.wala.shrike.shrikeBT.ConstantPoolReader;
import com.ibm.wala.shrike.shrikeBT.Decoder;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.CodeReader;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
/** This class decodes Java bytecodes into ShrikeBT code using a ShrikeCT class reader. */
public final class CTDecoder extends Decoder {
/**
* Decode the code resource 'r'.
*
* @throws NullPointerException if r is null
*/
public CTDecoder(CodeReader r) throws NullPointerException {
this(r, makeConstantPoolReader(r.getClassReader()));
}
/**
* Decode the code resource 'r' using the predeclared constant pool reader 'cpr' (obtained by
* makeConstantPoolReader below).
*
* @throws NullPointerException if r is null
*/
public CTDecoder(CodeReader r, ConstantPoolReader cpr) throws NullPointerException {
super(r.getBytecode(), r.getRawHandlers(), cpr);
}
/**
* Convert the internal JVM class name to a JVM type name (e.g., java/lang/Object to
* Ljava/lang/Object;).
*
* @throws IllegalArgumentException if s is null
*/
public static String convertClassToType(String s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
if (s.length() > 0 && s.charAt(0) != '[') {
return 'L' + s + ';';
} else {
return s;
}
}
/** Build a ConstantPoolReader implementation to read the constant pool from 'cr'. */
public static ConstantPoolReader makeConstantPoolReader(ClassReader cr)
throws IllegalArgumentException {
if (cr == null) {
throw new IllegalArgumentException("illegal null cr");
}
return new CPReader(cr.getCP());
}
static final class CPReader extends ConstantPoolReader {
private final ConstantPoolParser cp;
CPReader(ConstantPoolParser cp) {
this.cp = cp;
}
@Override
public int getConstantPoolItemType(int index) {
return cp.getItemType(index);
}
private static Error convertToError(InvalidClassFileException e) {
e.printStackTrace();
return new Error("Invalid class file: " + e.getMessage());
}
@Override
public int getConstantPoolInteger(int index) {
return cp.getCPInt(index);
}
@Override
public float getConstantPoolFloat(int index) {
return cp.getCPFloat(index);
}
@Override
public long getConstantPoolLong(int index) {
return cp.getCPLong(index);
}
@Override
public double getConstantPoolDouble(int index) {
return cp.getCPDouble(index);
}
@Override
public String getConstantPoolMethodType(int index) {
try {
return cp.getCPMethodType(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolString(int index) {
try {
return cp.getCPString(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolClassType(int index) {
try {
return convertClassToType(cp.getCPClass(index));
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolMemberClassType(int index) {
try {
return convertClassToType(cp.getCPRefClass(index));
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolMemberName(int index) {
try {
return cp.getCPRefName(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolMemberType(int index) {
try {
return cp.getCPRefType(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolHandleClassType(int index) {
try {
return cp.getCPHandleClass(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolHandleName(int index) {
try {
return cp.getCPHandleName(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolHandleType(int index) {
try {
return cp.getCPHandleType(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public byte getConstantPoolHandleKind(int index) {
try {
return cp.getCPHandleKind(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public BootstrapMethod getConstantPoolDynamicBootstrap(int index) {
try {
return cp.getCPDynBootstrap(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolDynamicName(int index) {
try {
return cp.getCPDynName(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
@Override
public String getConstantPoolDynamicType(int index) {
try {
return cp.getCPDynType(index);
} catch (InvalidClassFileException e) {
throw convertToError(e);
}
}
}
}
| 6,048
| 26.004464
| 95
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/CTUtils.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.analysis.ClassHierarchyStore;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import com.ibm.wala.shrike.shrikeCT.ClassWriter.Element;
import com.ibm.wala.shrike.shrikeCT.CodeWriter;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.shrike.shrikeCT.LineNumberTableWriter;
import java.util.Arrays;
/**
* This is a dumping ground for useful functions that manipulate class info.
*
* @author roca@us.ibm.com
*/
public class CTUtils {
public static void addClassToHierarchy(ClassHierarchyStore store, ClassReader cr)
throws InvalidClassFileException, IllegalArgumentException {
if (store == null) {
throw new IllegalArgumentException("store is null");
}
if (cr == null) {
throw new IllegalArgumentException();
}
String[] superInterfaces = new String[cr.getInterfaceCount()];
for (int i = 0; i < superInterfaces.length; i++) {
superInterfaces[i] = CTDecoder.convertClassToType(cr.getInterfaceName(i));
}
String superName = cr.getSuperName();
if ("java/io/File".equals(cr.getName()) || "java/lang/Throwable".equals(cr.getName())) {
System.err.println(superName);
}
store.setClassInfo(
CTDecoder.convertClassToType(cr.getName()),
(cr.getAccessFlags() & Constants.ACC_INTERFACE) != 0,
(cr.getAccessFlags() & Constants.ACC_FINAL) != 0,
superName != null ? CTDecoder.convertClassToType(superName) : null,
superInterfaces);
}
/**
* Compile and add a method to a {@link ClassWriter}.
*
* @param md the method data
* @param classWriter the target class writer
* @param rawLines line number information if available, otherwise {@code null}
*/
public static void compileAndAddMethodToClassWriter(
MethodData md, ClassWriter classWriter, ClassWriter.Element rawLines) {
if (classWriter == null) {
throw new IllegalArgumentException("classWriter is null");
}
if (md == null) {
throw new IllegalArgumentException("md is null");
}
CTCompiler compiler = CTCompiler.make(classWriter, md);
compiler.compile();
CTCompiler.Output output = compiler.getOutput();
CodeWriter code = new CodeWriter(classWriter);
code.setMaxStack(output.getMaxStack());
code.setMaxLocals(output.getMaxLocals());
code.setCode(output.getCode());
code.setRawHandlers(output.getRawHandlers());
LineNumberTableWriter lines = null;
// I guess it is the line numbers in the java files.
if (rawLines == null) {
// add fake line numbers: just map each bytecode instruction to its own
// 'line'
// NOTE:Should not use md.getInstructions().length, because the
// the length of the created code can be smaller than the md's instruction
// length
// WRONG: int[] newLineMap = new int[md.getInstructions().length];
int[] newLineMap = new int[code.getCodeLength()];
Arrays.setAll(newLineMap, i -> i);
int[] rawTable = LineNumberTableWriter.makeRawTable(newLineMap);
lines = new LineNumberTableWriter(classWriter);
lines.setRawTable(rawTable);
}
code.setAttributes(new ClassWriter.Element[] {rawLines == null ? lines : rawLines});
Element[] elements = {code};
// System.out.println("Name:"+md.getName()+" Sig:"+md.getSignature());
classWriter.addMethod(md.getAccess(), md.getName(), md.getSignature(), elements);
}
}
| 4,005
| 38.663366
| 92
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/ClassInstrumenter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT;
import com.ibm.wala.shrike.shrikeBT.Compiler;
import com.ibm.wala.shrike.shrikeBT.ConstantPoolReader;
import com.ibm.wala.shrike.shrikeBT.Decoder.InvalidBytecodeException;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.Instruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.ReturnInstruction;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException;
import com.ibm.wala.shrike.shrikeBT.analysis.ClassHierarchyProvider;
import com.ibm.wala.shrike.shrikeCT.ClassConstants;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import com.ibm.wala.shrike.shrikeCT.CodeReader;
import com.ibm.wala.shrike.shrikeCT.CodeWriter;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.shrike.shrikeCT.LineNumberTableReader;
import com.ibm.wala.shrike.shrikeCT.LineNumberTableWriter;
import com.ibm.wala.shrike.shrikeCT.LocalVariableTableReader;
import com.ibm.wala.shrike.shrikeCT.LocalVariableTableWriter;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.StackMapFrame;
import com.ibm.wala.shrike.shrikeCT.StackMapTableReader;
import com.ibm.wala.shrike.shrikeCT.StackMapTableWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* This class provides a convenient way to instrument every method in a class. It assumes you are
* using ShrikeCT to read and write classes. It's stateful; initially every method is set to the
* original code read from the class, but you can then go in and modify the methods.
*/
public final class ClassInstrumenter {
private final boolean[] deletedMethods;
private final MethodData[] methods;
private final CodeReader[] oldCode;
private final ClassReader cr;
private final ConstantPoolReader cpr;
private boolean createFakeLineNumbers = false;
private int fakeLineOffset;
private final String inputName;
private final ClassHierarchyProvider cha;
/** Create a class instrumenter from raw bytes. */
public ClassInstrumenter(String inputName, byte[] bytes, ClassHierarchyProvider cha)
throws InvalidClassFileException {
this(inputName, new ClassReader(bytes), cha);
}
/** @return name of resource from which this class was read */
public String getInputName() {
return inputName;
}
/**
* Calling this means that methods without line numbers get fake line numbers added: each bytecode
* instruction is treated as at line 'offset' + the offset of the instruction.
*/
public void enableFakeLineNumbers(int offset) {
createFakeLineNumbers = true;
fakeLineOffset = offset;
}
/**
* Create a class instrumenter from a preinitialized class reader.
*
* @throws IllegalArgumentException if cr is null
*/
public ClassInstrumenter(String inputName, ClassReader cr, ClassHierarchyProvider cha) {
if (cr == null) {
throw new IllegalArgumentException("cr is null");
}
this.cr = cr;
this.cha = cha;
methods = new MethodData[cr.getMethodCount()];
oldCode = new CodeReader[methods.length];
cpr = CTDecoder.makeConstantPoolReader(cr);
deletedMethods = new boolean[methods.length];
this.inputName = inputName;
}
/** @return the reader for the class */
public ClassReader getReader() {
return cr;
}
/** Implement this interface to instrument every method of a class using visitMethods() below. */
public interface MethodExaminer {
/** Do something to the method. */
void examineCode(MethodData data);
}
private void prepareMethod(int i) throws InvalidClassFileException {
if (deletedMethods[i]) {
methods[i] = null;
} else if (methods[i] == null) {
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
cr.initMethodAttributeIterator(i, iter);
for (; iter.isValid(); iter.advance()) {
if (iter.getName().equals("Code")) {
CodeReader code = new CodeReader(iter);
CTDecoder d = new CTDecoder(code, cpr);
try {
d.decode();
} catch (InvalidBytecodeException e) {
throw new InvalidClassFileException(code.getRawOffset(), e.getMessage());
}
MethodData md =
new MethodData(
d,
cr.getMethodAccessFlags(i),
CTDecoder.convertClassToType(cr.getName()),
cr.getMethodName(i),
cr.getMethodType(i));
methods[i] = md;
oldCode[i] = code;
return;
}
}
}
}
/**
* Indicate that the method should be deleted from the class.
*
* @param i the index of the method to delete
*/
public void deleteMethod(int i) {
deletedMethods[i] = true;
}
private static final ExceptionHandler[] noHandlers = new ExceptionHandler[0];
// Xiangyu
// create a empty method body and then user can apply patches later on
public MethodData createEmptyMethodData(String name, String sig, int access) {
// Instruction[] instructions=new Instruction[0];
Instruction[] instructions = new Instruction[1];
String type = Util.getReturnType(sig);
if ("C".equals(type) || "B".equals(type) || "Z".equals(type) || "S".equals(type)) {
type = "I";
}
instructions[0] = ReturnInstruction.make(type);
ExceptionHandler[][] handlers = new ExceptionHandler[instructions.length][];
Arrays.fill(handlers, noHandlers);
int[] i2b = new int[instructions.length];
Arrays.setAll(i2b, i -> i);
MethodData md = null;
try {
md =
new MethodData(
access, Util.makeType(cr.getName()), name, sig, instructions, handlers, i2b);
} catch (InvalidClassFileException ex) {
ex.printStackTrace();
}
return md;
}
/**
* Do something to every method in the class. This will visit all methods, including those already
* marked for deletion.
*
* @param me the visitor to apply to each method
*/
public void visitMethods(MethodExaminer me) throws InvalidClassFileException {
for (int i = 0; i < methods.length; i++) {
prepareMethod(i);
if (methods[i] != null) {
me.examineCode(methods[i]);
}
}
}
/**
* Get the current state of method i. This can be edited using a MethodEditor.
*
* @param i the index of the method to inspect
*/
public MethodData visitMethod(int i) throws InvalidClassFileException {
prepareMethod(i);
return methods[i];
}
/**
* Get the original code resource for the method.
*
* @param i the index of the method to inspect
*/
public CodeReader getMethodCode(int i) throws InvalidClassFileException {
prepareMethod(i);
return oldCode[i];
}
/**
* Reset method i back to the code from the original class, and "undelete" it if it was marked for
* deletion.
*
* @param i the index of the method to reset
*/
public void resetMethod(int i) {
deletedMethods[i] = false;
methods[i] = null;
}
/**
* Replace the code for method i with new code. This also "undeletes" the method if it was marked
* for deletion.
*
* @param i the index of the method to replace
* @throws IllegalArgumentException if md is null
*/
public void replaceMethod(int i, MethodData md) {
if (md == null) {
throw new IllegalArgumentException("md is null");
}
deletedMethods[i] = false;
methods[i] = md;
oldCode[i] = null;
md.setHasChanged();
}
/** Check whether any methods in the class have actually been changed. */
public boolean isChanged() {
for (int i = 0; i < methods.length; i++) {
if (deletedMethods[i] || (methods[i] != null && methods[i].getHasChanged())) {
return true;
}
}
return false;
}
/**
* Create a class which is a copy of the original class but with the new method code. We return
* the ClassWriter used, so more methods and fields (and other changes) can still be added.
*
* <p>We fix up any debug information to be consistent with the changes to the code.
*/
public ClassWriter emitClass() throws InvalidClassFileException {
return emitClass(new ClassWriter());
}
public ClassWriter emitClass(ClassWriter w) throws InvalidClassFileException {
emitClassInto(w);
return w;
}
/**
* Copy the contents of the old class, plus any method modifications, into a new ClassWriter. The
* ClassWriter must be empty!
*
* @param w the classwriter to copy into.
*/
private void emitClassInto(ClassWriter w) throws InvalidClassFileException {
w.setMajorVersion(cr.getMajorVersion());
w.setMinorVersion(cr.getMinorVersion());
w.setRawCP(cr.getCP(), false);
w.setAccessFlags(cr.getAccessFlags());
w.setNameIndex(cr.getNameIndex());
w.setSuperNameIndex(cr.getSuperNameIndex());
w.setInterfaceNameIndices(cr.getInterfaceNameIndices());
int fieldCount = cr.getFieldCount();
for (int i = 0; i < fieldCount; i++) {
w.addRawField(
new ClassWriter.RawElement(
cr.getBytes(), cr.getFieldRawOffset(i), cr.getFieldRawSize(i)));
}
for (int i = 0; i < methods.length; i++) {
MethodData md = methods[i];
if (!deletedMethods[i]) {
if (md == null || !md.getHasChanged()) {
w.addRawMethod(
new ClassWriter.RawElement(
cr.getBytes(), cr.getMethodRawOffset(i), cr.getMethodRawSize(i)));
} else {
CTCompiler comp = CTCompiler.make(w, md);
comp.setPresetConstants(cpr);
try {
comp.compile();
} catch (Error | Exception ex) {
ex.printStackTrace();
throw new Error("Error compiling method " + md + ": " + ex.getMessage());
}
CodeReader oc = oldCode[i];
int flags = cr.getMethodAccessFlags(i);
// we're not installing a native method here
flags &= ~ClassConstants.ACC_NATIVE;
w.addMethod(
flags,
cr.getMethodNameIndex(i),
cr.getMethodTypeIndex(i),
makeMethodAttributes(i, w, oc, comp.getOutput(), md));
Compiler.Output[] aux = comp.getAuxiliaryMethods();
if (aux != null) {
for (Compiler.Output a : aux) {
w.addMethod(
a.getAccessFlags(),
a.getMethodName(),
a.getMethodSignature(),
makeMethodAttributes(i, w, oc, a, md));
}
}
}
}
}
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
cr.initClassAttributeIterator(iter);
for (; iter.isValid(); iter.advance()) {
w.addClassAttribute(
new ClassWriter.RawElement(cr.getBytes(), iter.getRawOffset(), iter.getRawSize()));
}
}
private static CodeWriter makeNewCode(ClassWriter w, Compiler.Output output) {
CodeWriter code = new CodeWriter(w);
code.setMaxStack(output.getMaxStack());
code.setMaxLocals(output.getMaxLocals());
code.setCode(output.getCode());
code.setRawHandlers(output.getRawHandlers());
return code;
}
private LineNumberTableWriter makeNewLines(
ClassWriter w, CodeReader oldCode, Compiler.Output output) throws InvalidClassFileException {
int[] newLineMap = null;
int[] oldLineMap = LineNumberTableReader.makeBytecodeToSourceMap(oldCode);
if (oldLineMap != null) {
// Map the old line number map onto the new bytecodes
int[] newToOldMap = output.getNewBytecodesToOldBytecodes();
newLineMap = new int[newToOldMap.length];
for (int i = 0; i < newToOldMap.length; i++) {
int old = newToOldMap[i];
if (old >= 0) {
newLineMap[i] = oldLineMap[old];
}
}
} else if (createFakeLineNumbers) {
newLineMap = new int[output.getCode().length];
Arrays.setAll(newLineMap, i -> i + fakeLineOffset);
} else {
return null;
}
// Now compress it into the JVM form
int[] rawTable = LineNumberTableWriter.makeRawTable(newLineMap);
if (rawTable == null || rawTable.length == 0) {
return null;
} else {
LineNumberTableWriter lines = new LineNumberTableWriter(w);
lines.setRawTable(rawTable);
return lines;
}
}
private static LocalVariableTableWriter makeNewLocals(
ClassWriter w, CodeReader oldCode, Compiler.Output output) throws InvalidClassFileException {
int[][] oldMap = LocalVariableTableReader.makeVarMap(oldCode);
if (oldMap != null) {
// Map the old map onto the new bytecodes
int[] newToOldMap = output.getNewBytecodesToOldBytecodes();
int[][] newMap = new int[newToOldMap.length][];
int[] lastLocals = null;
for (int i = 0; i < newToOldMap.length; i++) {
int old = newToOldMap[i];
if (old >= 0) {
newMap[i] = oldMap[old];
lastLocals = newMap[i];
} else {
newMap[i] = lastLocals;
}
}
int[] rawTable = LocalVariableTableWriter.makeRawTable(newMap, output);
if (rawTable == null || rawTable.length == 0) {
return null;
} else {
LocalVariableTableWriter locals = new LocalVariableTableWriter(w);
locals.setRawTable(rawTable);
return locals;
}
} else {
return null;
}
}
private ClassWriter.Element[] makeMethodAttributes(
int m, ClassWriter w, CodeReader oldCode, Compiler.Output output, MethodData md)
throws InvalidClassFileException {
CodeWriter code = makeNewCode(w, output);
int codeAttrCount = 0;
LineNumberTableWriter lines = null;
LocalVariableTableWriter locals = null;
StackMapTableWriter stacks = null;
if (oldCode != null) {
lines = makeNewLines(w, oldCode, output);
if (lines != null) {
codeAttrCount++;
}
locals = makeNewLocals(w, oldCode, output);
if (locals != null) {
codeAttrCount++;
}
if (oldCode.getClassReader().getMajorVersion() > 50) {
try {
List<StackMapFrame> sm = StackMapTableReader.readStackMap(oldCode);
String[][] varTypes = null;
int[] newToOld = output.getNewBytecodesToOldBytecodes();
int[][] vars = LocalVariableTableReader.makeVarMap(oldCode);
if (vars != null) {
varTypes = new String[newToOld.length][];
for (int i = 0; i < newToOld.length; i++) {
int idx = newToOld[i];
if (idx != -1 && vars[idx] != null) {
varTypes[i] = new String[vars[idx].length / 2];
for (int j = 1; j < vars[idx].length; j += 2) {
int type = vars[idx][j];
varTypes[i][j / 2] =
type == 0 ? null : oldCode.getClassReader().getCP().getCPUtf8(type);
}
}
}
}
stacks = new StackMapTableWriter(w, md, output, cha, varTypes, sm);
codeAttrCount++;
} catch (IOException | FailureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ClassWriter.Element[] codeAttributes = new ClassWriter.Element[codeAttrCount];
int codeAttrIndex = 0;
if (lines != null) {
codeAttributes[codeAttrIndex++] = lines;
}
if (locals != null) {
codeAttributes[codeAttrIndex++] = locals;
}
if (stacks != null) {
codeAttributes[codeAttrIndex++] = stacks;
}
code.setAttributes(codeAttributes);
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
cr.initMethodAttributeIterator(m, iter);
int methodAttrCount = iter.getRemainingAttributesCount();
if (oldCode == null) {
methodAttrCount++;
}
ClassWriter.Element[] methodAttributes = new ClassWriter.Element[methodAttrCount];
for (int i = 0; iter.isValid(); iter.advance()) {
if (iter.getName().equals("Code")) {
methodAttributes[i] = code;
code = null;
if (oldCode == null) {
throw new Error("No old code provided, but Code attribute found");
}
} else {
methodAttributes[i] =
new ClassWriter.RawElement(cr.getBytes(), iter.getRawOffset(), iter.getRawSize());
}
i++;
}
if (oldCode == null) {
if (code == null) {
throw new Error("Old code not provided but existing code was found and replaced");
}
methodAttributes[methodAttrCount - 1] = code;
}
return methodAttributes;
}
}
| 17,064
| 32.994024
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/OfflineInstrumenter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.tools.OfflineInstrumenterBase;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* This class provides a convenient way to iterate through a collection of Java classes and
* instrument their code. This is just a specialization of OfflineInstrumenterBase to use the
* shrikeCT functionality.
*/
public final class OfflineInstrumenter extends OfflineInstrumenterBase {
@Override
protected Object makeClassFromStream(String inputName, BufferedInputStream s) throws IOException {
byte[] bytes = new byte[s.available()];
Util.readFully(s, bytes);
try {
return new ClassInstrumenter(inputName, bytes, cha);
} catch (InvalidClassFileException e) {
throw new IOException("Class is invalid: " + e.getMessage());
}
}
@Override
protected String getClassName(Object cl) {
try {
return ((ClassInstrumenter) cl).getReader().getName().replace('/', '.');
} catch (InvalidClassFileException e) {
return null;
}
}
@Override
protected void writeClassTo(Object cl, Object mods, OutputStream s) throws IOException {
ClassInstrumenter ci = (ClassInstrumenter) cl;
ClassWriter cw = (ClassWriter) mods;
if (cw == null) {
s.write(ci.getReader().getBytes());
} else {
s.write(cw.makeBytes());
}
}
/** Get the next class to be instrumented. */
public ClassInstrumenter nextClass() throws IOException {
return (ClassInstrumenter) internalNextClass();
}
/**
* Update the original class with some method changes. 'code' should be the result of
* out.emitClass(). You can add new fields and methods to 'code' (or make other changes) before
* calling this method.
*/
public void outputModifiedClass(ClassInstrumenter out, ClassWriter code)
throws IllegalStateException, IOException {
internalOutputModifiedClass(out, out.getInputName(), code);
}
/**
* Update the original class with some method changes. This method calls out.emitClass() for you.
*/
public void outputModifiedClass(ClassInstrumenter out)
throws IllegalArgumentException, IOException {
if (out == null) {
throw new IllegalArgumentException();
}
try {
internalOutputModifiedClass(out, out.getInputName(), out.emitClass());
} catch (InvalidClassFileException e) {
e.printStackTrace();
throw new IOException("Invalid class file");
}
}
}
| 3,043
| 32.822222
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/tools/AddSerialVersion.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT.tools;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeCT.ClassConstants;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import com.ibm.wala.shrike.shrikeCT.ConstantValueWriter;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class AddSerialVersion {
// this class should not be instantiated
private AddSerialVersion() {}
/**
* This method computes the serialVersionUID for class r (if there isn't one already) and adds the
* field to the classwriter w.
*
* <p>When run as a program, just takes a list of class files as command line arguments and
* computes their serialVersionUIDs.
*
* @throws IllegalArgumentException if r is null
*/
public static void addSerialVersionUID(ClassReader r, ClassWriter w)
throws InvalidClassFileException {
if (r == null) {
throw new IllegalArgumentException("r is null");
}
int numFields = r.getFieldCount();
for (int i = 0; i < numFields; i++) {
if (r.getFieldName(i).equals("serialVersionUID")) {
return; // already has a serialVersionUID
}
}
long UID = computeSerialVersionUID(r);
w.addField(
ClassConstants.ACC_PUBLIC | ClassConstants.ACC_STATIC | ClassConstants.ACC_FINAL,
"serialVersionUID",
"J",
new ClassWriter.Element[] {new ConstantValueWriter(w, UID)});
}
/** This class implements a stream that just discards everything written to it. */
public static final class SinkOutputStream extends OutputStream {
@Override
public void write(int b) {}
@Override
public void write(byte[] b) {}
@Override
public void write(byte[] b, int off, int len) {}
}
/**
* This method computes the serialVersionUID for class r. See <a
* href="http://java.sun.com/j2se/1.4.2/docs/guide/serialization/spec/class.html">the
* specification</a>.
*
* @throws IllegalArgumentException if r is null
*/
public static long computeSerialVersionUID(final ClassReader r) throws InvalidClassFileException {
if (r == null) {
throw new IllegalArgumentException("r is null");
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
throw new Error("SHA algorithm not supported: " + e.getMessage());
}
try (SinkOutputStream sink = new SinkOutputStream();
DataOutputStream out = new DataOutputStream(new DigestOutputStream(sink, digest)); ) {
try {
// step 1
out.writeUTF(r.getName());
// step 2
out.writeInt(r.getAccessFlags());
// step 3
String[] interfaces = r.getInterfaceNames();
Arrays.sort(interfaces);
for (String interface1 : interfaces) {
out.writeUTF(interface1);
}
// step 4
Integer[] fields = new Integer[r.getFieldCount()];
final String[] fieldNames = new String[fields.length];
int fieldCount = 0;
for (int f = 0; f < fields.length; f++) {
int flags = r.getFieldAccessFlags(f);
if ((flags & ClassConstants.ACC_PRIVATE) == 0
|| (flags & (ClassConstants.ACC_STATIC | ClassConstants.ACC_TRANSIENT)) == 0) {
fields[fieldCount] = f;
fieldNames[f] = r.getFieldName(f);
fieldCount++;
}
}
Arrays.sort(
fields,
0,
fieldCount,
(o1, o2) -> {
String name1 = fieldNames[o1];
String name2 = fieldNames[o2];
return name1.compareTo(name2);
});
for (int i = 0; i < fieldCount; i++) {
int f = fields[i];
out.writeUTF(fieldNames[f]);
out.writeInt(r.getFieldAccessFlags(f));
out.writeUTF(r.getFieldType(f));
}
// steps 5, 6 and 7
Integer[] methods = new Integer[r.getMethodCount()];
final int[] methodKinds = new int[methods.length];
final String[] methodSigs = new String[methods.length];
int methodCount = 0;
for (int m = 0; m < methodSigs.length; m++) {
String name = r.getMethodName(m);
int flags = r.getMethodAccessFlags(m);
if (name.equals("<clinit>") || (flags & ClassConstants.ACC_PRIVATE) == 0) {
methods[methodCount] = m;
methodSigs[m] = name + r.getMethodType(m);
switch (name) {
case "<clinit>":
methodKinds[m] = 0;
break;
case "<init>":
methodKinds[m] = 1;
break;
default:
methodKinds[m] = 2;
break;
}
methodCount++;
}
}
Arrays.sort(
methods,
0,
methodCount,
(o1, o2) -> {
int m1 = o1;
int m2 = o2;
if (methodKinds[m1] != methodKinds[m2]) {
return methodKinds[m1] - methodKinds[m2];
}
String name1 = methodSigs[m1];
String name2 = methodSigs[m2];
return name1.compareTo(name2);
});
for (int i = 0; i < methodCount; i++) {
int m = methods[i];
out.writeUTF(r.getMethodName(m));
out.writeInt(r.getMethodAccessFlags(m));
out.writeUTF(r.getMethodType(m));
}
} catch (IOException e1) {
throw new Error("Unexpected IOException: " + e1.getMessage());
}
} catch (IOException e2) {
}
byte[] hash = digest.digest();
return (hash[0] & 0xFF)
| (hash[1] & 0xFF) << 8
| (hash[2] & 0xFF) << 16
| hash[3] << 24
| (hash[4] & 0xFFL) << 32
| (hash[5] & 0xFFL) << 40
| (hash[6] & 0xFFL) << 48
| (hash[7] & 0xFFL) << 56;
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
throw new IllegalArgumentException("args[" + i + "] is null");
}
try (final FileInputStream in = new FileInputStream(args[i])) {
byte[] data = Util.readFully(in);
ClassReader r = new ClassReader(data);
System.out.println(
Util.makeClass(r.getName()) + ": serialVersionUID = " + computeSerialVersionUID(r));
} catch (FileNotFoundException e) {
System.err.println("File not found: " + args[i]);
} catch (IOException e) {
System.err.println("Error reading file: " + args[i]);
} catch (InvalidClassFileException e) {
System.err.println("Invalid class file: " + args[i]);
}
}
}
}
| 7,452
| 33.188073
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/tools/BatchVerifier.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT.tools;
import com.ibm.wala.shrike.shrikeBT.Decoder;
import com.ibm.wala.shrike.shrikeBT.Disassembler;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException;
import com.ibm.wala.shrike.shrikeBT.analysis.ClassHierarchyStore;
import com.ibm.wala.shrike.shrikeBT.analysis.Verifier;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTDecoder;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTUtils;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.CodeReader;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
/**
* This is a demo class.
*
* <p>Class files are taken as input arguments (or if there are none, from standard input). The
* methods in those files are instrumented: we insert a System.err.println() at ever method call,
* and a System.err.println() at every method entry.
*
* <p>In Unix, I run it like this: java -cp ~/dev/shrike/shrike
* com.ibm.wala.shrikeBT.shrikeCT.tools.BatchVerifier test.jar -o output.jar
*
* <p>The instrumented classes are placed in the directory "output" under the current directory.
* Disassembled code is written to the file "report" under the current directory.
*/
public class BatchVerifier {
private static boolean disasm = false;
private static final ClassHierarchyStore store = new ClassHierarchyStore();
private static int errors = 0;
public static void main(String[] args) throws Exception {
OfflineInstrumenter oi = new OfflineInstrumenter();
args = oi.parseStandardArgs(args);
for (String arg : args) {
if (arg.equals("-d")) {
disasm = true;
break;
}
}
try (final PrintWriter w =
new PrintWriter(new BufferedWriter(new FileWriter("report", false)))) {
oi.beginTraversal();
ClassInstrumenter ci;
while ((ci = oi.nextClass()) != null) {
ClassReader cr = ci.getReader();
CTUtils.addClassToHierarchy(store, cr);
}
oi.beginTraversal();
while ((ci = oi.nextClass()) != null) {
doClass(ci.getReader(), w);
}
}
oi.close();
if (errors > 0) {
System.err.println(errors + " error" + (errors > 1 ? "s" : "") + " detected");
}
}
private static void doClass(final ClassReader cr, PrintWriter w) throws Exception {
int methodCount = cr.getMethodCount();
w.write("Verifying " + cr.getName() + '\n');
w.flush();
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
for (int i = 0; i < methodCount; i++) {
cr.initMethodAttributeIterator(i, iter);
for (; iter.isValid(); iter.advance()) {
if (iter.getName().equals("Code")) {
w.write(
"Verifying "
+ cr.getName()
+ '.'
+ cr.getMethodName(i)
+ ' '
+ cr.getMethodType(i)
+ ":\n");
w.flush();
CodeReader code = new CodeReader(iter);
CTDecoder d = new CTDecoder(code);
try {
d.decode();
} catch (Decoder.InvalidBytecodeException e) {
throw new InvalidClassFileException(code.getRawOffset(), e.getMessage());
}
MethodData md =
new MethodData(
d,
cr.getMethodAccessFlags(i),
CTDecoder.convertClassToType(cr.getName()),
cr.getMethodName(i),
cr.getMethodType(i));
if (disasm) {
w.write("ShrikeBT code:\n");
new Disassembler(md).disassembleTo(w);
w.flush();
}
Verifier v = new Verifier(md);
try {
v.verify();
} catch (FailureException e) {
w.println("ERROR: VERIFICATION FAILED");
e.printStackTrace(w);
e.printPath(w);
errors++;
w.flush();
}
break;
}
}
}
}
}
| 4,634
| 31.412587
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/tools/BootstrapDumper.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT.tools;
import com.ibm.wala.shrike.shrikeBT.Decoder.InvalidBytecodeException;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.InvokeDynamicInstruction;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTDecoder;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.CodeReader;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.invoke.CallSite;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
public class BootstrapDumper {
private final PrintWriter w;
/** Get ready to print a class to the given output stream. */
public BootstrapDumper(PrintWriter w) {
this.w = w;
}
public static void main(String[] args) throws Exception {
OfflineInstrumenter oi = new OfflineInstrumenter();
String[] classpathEntries = oi.parseStandardArgs(args);
PrintWriter w = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BootstrapDumper p = new BootstrapDumper(w);
URL[] urls = new URL[classpathEntries.length - 1];
for (int i = 1; i < classpathEntries.length; i++) {
System.err.println(classpathEntries[i]);
File f = new File(classpathEntries[i]);
assert f.exists();
urls[i - 1] = f.toURI().toURL();
}
try (final URLClassLoader image =
URLClassLoader.newInstance(urls, BootstrapDumper.class.getClassLoader().getParent())) {
System.err.println(image);
ClassInstrumenter ci;
oi.beginTraversal();
while ((ci = oi.nextClass()) != null) {
try {
p.doClass(image, ci.getReader());
} finally {
w.flush();
}
}
}
oi.close();
}
private void dumpAttributes(Class<?> cl, ClassReader.AttrIterator attrs)
throws InvalidClassFileException, InvalidBytecodeException, ClassNotFoundException,
NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
for (; attrs.isValid(); attrs.advance()) {
String name = attrs.getName();
if (name.equals("Code")) {
CodeReader code = new CodeReader(attrs);
CTDecoder decoder = new CTDecoder(code);
decoder.decode();
IInstruction[] insts = decoder.getInstructions();
for (IInstruction inst : insts) {
if (inst instanceof InvokeDynamicInstruction) {
CallSite target = ((InvokeDynamicInstruction) inst).bootstrap(cl);
w.println(target.dynamicInvoker());
w.println(target.getTarget());
/*
* only in Java 8. Uncomment when we mandate Java 8.
try {
w.println(MethodHandles.reflectAs(Method.class, target.dynamicInvoker()));
} catch (Throwable e) {
System.out.println(e);
}
*/
}
}
}
}
}
/**
* Print a class.
*
* @throws IllegalArgumentException if cr is null
*/
public void doClass(ClassLoader image, final ClassReader cr)
throws InvalidClassFileException, InvalidBytecodeException, ClassNotFoundException,
NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
if (cr == null) {
throw new IllegalArgumentException("cr is null");
}
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
cr.initClassAttributeIterator(attrs);
int methodCount = cr.getMethodCount();
for (int i = 0; i < methodCount; i++) {
cr.initMethodAttributeIterator(i, attrs);
dumpAttributes(Class.forName(cr.getName().replace('/', '.'), false, image), attrs);
}
}
}
| 4,474
| 34.515873
| 95
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/tools/BootstrapInstrumentor.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT.tools;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.ConstantPoolReader;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.Decoder.InvalidBytecodeException;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.Dispatch;
import com.ibm.wala.shrike.shrikeBT.InvokeDynamicInstruction;
import com.ibm.wala.shrike.shrikeBT.InvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.ReturnInstruction;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTDecoder;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTUtils;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import com.ibm.wala.shrike.shrikeCT.CodeReader;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.util.collections.HashSetFactory;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Set;
public class BootstrapInstrumentor {
private final PrintWriter w;
private int idx;
/** Get ready to print a class to the given output stream. */
public BootstrapInstrumentor(PrintWriter w) {
this.w = w;
}
public static void main(String[] args) throws Exception {
PrintWriter w = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BootstrapInstrumentor p = new BootstrapInstrumentor(w);
p.doit(args);
}
public void doit(String[] args) throws Exception {
OfflineInstrumenter oi = new OfflineInstrumenter();
oi.parseStandardArgs(args);
oi.setPassUnmodifiedClasses(true);
ClassInstrumenter ci;
oi.beginTraversal();
while ((ci = oi.nextClass()) != null) {
try {
idx = 0;
Set<MethodData> bss = doClass(ci);
ClassWriter cw = ci.emitClass();
for (MethodData md : bss) {
CTUtils.compileAndAddMethodToClassWriter(md, cw, null);
}
oi.outputModifiedClass(ci, cw);
} finally {
w.flush();
}
}
oi.close();
}
private Set<MethodData> dumpAttributes(ClassInstrumenter ci, ClassReader.AttrIterator attrs)
throws InvalidClassFileException, InvalidBytecodeException, SecurityException,
IllegalArgumentException {
Set<MethodData> result = HashSetFactory.make();
ClassReader cr = ci.getReader();
for (; attrs.isValid(); attrs.advance()) {
String name = attrs.getName();
if (name.equals("Code")) {
CodeReader code = new CodeReader(attrs);
CTDecoder decoder = new CTDecoder(code);
decoder.decode();
ConstantPoolReader cpr = decoder.getConstantPool();
IInstruction[] origInsts = decoder.getInstructions();
for (IInstruction inst : origInsts) {
if (inst instanceof InvokeDynamicInstruction) {
InvokeDynamicInstruction x = (InvokeDynamicInstruction) inst;
BootstrapMethod m = x.getBootstrap();
IInstruction insts[] = new IInstruction[m.callArgumentCount() + 8];
int arg = 0;
insts[arg++] =
InvokeInstruction.make(
"()Ljava/lang/invoke/MethodHandles$Lookup;",
"java/lang/invoke/MethodHandles",
"lookup",
Dispatch.STATIC);
insts[arg++] = ConstantInstruction.makeString(x.getMethodName());
insts[arg++] = ConstantInstruction.makeString(x.getMethodSignature());
insts[arg++] = ConstantInstruction.makeClass(cr.getName());
insts[arg++] =
InvokeInstruction.make(
"()Ljava/lang/ClassLoader;",
"java/lang/Class",
"getClassLoader",
Dispatch.VIRTUAL);
insts[arg++] =
InvokeInstruction.make(
"(Ljava/lang/String;Ljava/lang/ClassLoader;)Ljava/lang/invoke/MethodType;",
"java/lang/invoke/MethodType",
"fromMethodDescriptorString",
Dispatch.STATIC);
for (int an = 0; an < m.callArgumentCount(); an++) {
insts[arg++] = ConstantInstruction.make(cpr, m.callArgumentIndex(an));
}
insts[arg++] =
InvokeInstruction.make(
m.methodType(),
m.methodClass(),
m.methodName(),
((InvokeDynamicInstruction) inst).getInvocationCode());
insts[arg++] = ReturnInstruction.make("Ljava/lang/invoke/CallSite;");
result.add(
MethodData.makeWithDefaultHandlersAndInstToBytecodes(
Constants.ACC_PUBLIC | Constants.ACC_STATIC,
cr.getName(),
"bs" + idx++,
"()Ljava/lang/invoke/CallSite;",
insts));
}
}
}
}
return result;
}
/**
* Print a class.
*
* @throws IllegalArgumentException if cr is null
*/
public Set<MethodData> doClass(final ClassInstrumenter ci)
throws InvalidClassFileException, InvalidBytecodeException, SecurityException,
IllegalArgumentException {
ClassReader cr = ci.getReader();
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
cr.initClassAttributeIterator(attrs);
int methodCount = cr.getMethodCount();
Set<MethodData> result = HashSetFactory.make();
for (int i = 0; i < methodCount; i++) {
cr.initMethodAttributeIterator(i, attrs);
result.addAll(dumpAttributes(ci, attrs));
}
return result;
}
}
| 6,347
| 35.482759
| 95
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/tools/ClassPrinter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT.tools;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.Decoder.InvalidBytecodeException;
import com.ibm.wala.shrike.shrikeBT.Disassembler;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTDecoder;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.AnnotationsReader;
import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.AnnotationAttribute;
import com.ibm.wala.shrike.shrikeCT.ClassConstants;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.CodeReader;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser;
import com.ibm.wala.shrike.shrikeCT.ConstantValueReader;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.shrike.shrikeCT.LineNumberTableReader;
import com.ibm.wala.shrike.shrikeCT.LocalVariableTableReader;
import com.ibm.wala.shrike.shrikeCT.SignatureReader;
import com.ibm.wala.shrike.shrikeCT.SourceFileReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
/**
* This class prints the contents of a class file. It's like an alternative to javap that shows more
* information.
*
* <p>In Unix I run it like this: java -cp ~/dev/shrike/shrike
* com.ibm.wala.shrikeBT.shrikeCT.tools.ClassPrinter test.jar This will print the contents of every
* class in the JAR file.
*
* @author roca
*/
public class ClassPrinter {
private final PrintWriter w;
private boolean printLineNumberInfo = true;
private boolean printConstantPool = true;
/** Get ready to print a class to the given output stream. */
public ClassPrinter(PrintWriter w) {
this.w = w;
}
/** Controls whether to print line number information. The default is 'true'. */
public void setPrintLineNumberInfo(boolean b) {
printLineNumberInfo = b;
}
/** Controls whether to print all the constant pool entries. The default is 'true'. */
public void setPrintConstantPool(boolean b) {
printConstantPool = b;
}
public static void main(String[] args) throws Exception {
OfflineInstrumenter oi = new OfflineInstrumenter();
args = oi.parseStandardArgs(args);
PrintWriter w = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
ClassPrinter p = new ClassPrinter(w);
ClassInstrumenter ci;
oi.beginTraversal();
while ((ci = oi.nextClass()) != null) {
try {
p.doClass(ci.getReader());
} finally {
w.flush();
}
}
oi.close();
}
private static final char[] hexChars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
private static String makeHex(byte[] bytes, int pos, int len, int padTo) {
StringBuilder b = new StringBuilder();
for (int i = pos; i < pos + len; i++) {
byte v = bytes[i];
b.append(hexChars[(v >> 4) & 0xF]);
b.append(hexChars[v & 0xF]);
}
while (b.length() < padTo) {
b.append(' ');
}
return b.toString();
}
private static String makeChars(byte[] bytes, int pos, int len) {
StringBuilder b = new StringBuilder();
for (int i = pos; i < pos + len; i++) {
char ch = (char) bytes[i];
if (ch < 32 || ch > 127) {
b.append('.');
} else {
b.append(ch);
}
}
return b.toString();
}
private static String getClassName(ClassReader cr, int index) throws InvalidClassFileException {
if (index == 0) {
return "any";
} else {
return cr.getCP().getCPClass(index);
}
}
private static String dumpFlags(int flags) {
StringBuilder buf = new StringBuilder();
Class<Constants> c = Constants.class;
Field[] fs = c.getDeclaredFields();
for (Field element : fs) {
String name = element.getName();
if (name.startsWith("ACC_")) {
int val;
try {
val = element.getInt(null);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new Error(e.getMessage());
}
if ((flags & val) != 0) {
if (buf.length() > 0) {
buf.append(' ');
}
buf.append(name.substring(4).toLowerCase());
}
}
}
return "0x" + Integer.toString(16, flags) + '(' + buf + ')';
}
private void dumpAttributes(ClassReader cr, ClassReader.AttrIterator attrs)
throws InvalidClassFileException, InvalidBytecodeException, IOException {
for (; attrs.isValid(); attrs.advance()) {
String name = attrs.getName();
w.write(" " + name + ": @" + Integer.toString(attrs.getRawOffset(), 16) + '\n');
if (name.equals("Code")) {
CodeReader code = new CodeReader(attrs);
w.write(" maxstack: " + code.getMaxStack() + '\n');
w.write(" maxlocals: " + code.getMaxLocals() + '\n');
w.write(" bytecode:\n");
int[] rawHandlers = code.getRawHandlers();
CTDecoder decoder = new CTDecoder(code);
decoder.decode();
Disassembler disasm =
new Disassembler(
decoder.getInstructions(),
decoder.getHandlers(),
decoder.getInstructionsToBytecodes());
disasm.disassembleTo(" ", w);
w.write(" exception handlers:\n");
for (int e = 0; e < rawHandlers.length; e += 4) {
w.write(
" "
+ rawHandlers[e]
+ " to "
+ rawHandlers[e + 1]
+ " catch "
+ getClassName(cr, rawHandlers[e + 3])
+ " at "
+ rawHandlers[e + 2]
+ '\n');
}
ClassReader.AttrIterator codeAttrs = new ClassReader.AttrIterator();
code.initAttributeIterator(codeAttrs);
for (; codeAttrs.isValid(); codeAttrs.advance()) {
String cName = codeAttrs.getName();
w.write(" " + cName + ": " + Integer.toString(codeAttrs.getRawOffset(), 16) + '\n');
}
if (printLineNumberInfo) {
int[] map = LineNumberTableReader.makeBytecodeToSourceMap(code);
if (map != null) {
w.write(" line number map:\n");
String line = null;
int count = 0;
for (int j = 0; j < map.length; j++) {
String line2 = " " + j + ": " + map[j];
if (line == null
|| !line2
.substring(line2.indexOf(':'))
.equals(line.substring(line.indexOf(':')))) {
if (count > 1) {
w.write(" (" + count + " times)\n");
} else if (count > 0) {
w.write("\n");
}
count = 0;
line = line2;
w.write(line);
}
count++;
}
if (count > 1) {
w.write(" (" + count + " times)\n");
} else if (count > 0) {
w.write("\n");
}
}
}
int[][] locals = LocalVariableTableReader.makeVarMap(code);
if (locals != null) {
w.write(" local variable map:\n");
String line = null;
int count = 0;
for (int j = 0; j < locals.length; j++) {
int[] vars = locals[j];
String line2 = null;
if (vars != null) {
StringBuilder buf = new StringBuilder();
buf.append(" ").append(j).append(':');
for (int k = 0; k < vars.length; k += 2) {
if (vars[k] != 0) {
String n =
cr.getCP().getCPUtf8(vars[k]) + '(' + cr.getCP().getCPUtf8(vars[k + 1]) + ')';
buf.append(' ').append(k / 2).append(':').append(n);
}
}
line2 = buf.toString();
}
if (line == null
|| line2 == null
|| !line2.substring(line2.indexOf(':')).equals(line.substring(line.indexOf(':')))) {
if (count > 1) {
w.write(" (" + count + " times)\n");
} else if (count > 0) {
w.write("\n");
}
count = 0;
line = line2;
if (line != null) {
w.write(line);
}
}
if (line != null) {
count++;
}
}
if (count > 1) {
w.write(" (" + count + " times)\n");
} else if (count > 0) {
w.write("\n");
}
}
} else if (name.equals("ConstantValue")) {
ConstantValueReader cv = new ConstantValueReader(attrs);
w.write(" value: " + getCPItemString(cr.getCP(), cv.getValueCPIndex()) + '\n');
} else if (name.equals("SourceFile")) {
SourceFileReader sr = new SourceFileReader(attrs);
w.write(" file: " + cr.getCP().getCPUtf8(sr.getSourceFileCPIndex()) + '\n');
} else if (name.equals("Signature")) {
SignatureReader sr = new SignatureReader(attrs);
w.write(" signature: " + cr.getCP().getCPUtf8(sr.getSignatureCPIndex()) + '\n');
} else if (AnnotationsReader.isKnownAnnotation(name)) {
AnnotationsReader r = new AnnotationsReader(attrs, name);
printAnnotations(r);
} else {
int len = attrs.getDataSize();
int pos = attrs.getDataOffset();
while (len > 0) {
int amount = Math.min(16, len);
w.write(
" "
+ makeHex(cr.getBytes(), pos, amount, 32)
+ ' '
+ makeChars(cr.getBytes(), pos, amount)
+ '\n');
len -= amount;
pos += amount;
}
}
}
}
private void printAnnotations(AnnotationsReader r) throws InvalidClassFileException {
for (AnnotationAttribute annot : r.getAllAnnotations()) {
w.write(" Annotation type: " + annot.type + '\n');
}
}
private static String getCPItemString(ConstantPoolParser cp, int i)
throws InvalidClassFileException {
int t = cp.getItemType(i);
switch (t) {
case ClassConstants.CONSTANT_Utf8:
return "Utf8 " + quoteString(cp.getCPUtf8(i));
case ClassConstants.CONSTANT_Class:
return "Class " + cp.getCPClass(i);
case ClassConstants.CONSTANT_String:
return "String " + quoteString(cp.getCPString(i));
case ClassConstants.CONSTANT_Integer:
return "Integer " + cp.getCPInt(i);
case ClassConstants.CONSTANT_Float:
return "Float " + cp.getCPFloat(i);
case ClassConstants.CONSTANT_Double:
return "Double " + cp.getCPDouble(i);
case ClassConstants.CONSTANT_Long:
return "Long " + cp.getCPLong(i);
case ClassConstants.CONSTANT_MethodRef:
return "Method "
+ cp.getCPRefClass(i)
+ ' '
+ cp.getCPRefName(i)
+ ' '
+ cp.getCPRefType(i);
case ClassConstants.CONSTANT_FieldRef:
return "Field " + cp.getCPRefClass(i) + ' ' + cp.getCPRefName(i) + ' ' + cp.getCPRefType(i);
case ClassConstants.CONSTANT_InterfaceMethodRef:
return "InterfaceMethod "
+ cp.getCPRefClass(i)
+ ' '
+ cp.getCPRefName(i)
+ ' '
+ cp.getCPRefType(i);
case ClassConstants.CONSTANT_NameAndType:
return "NameAndType " + cp.getCPNATType(i) + ' ' + cp.getCPNATName(i);
default:
return "Unknown type " + t;
}
}
private static String quoteString(String string) {
StringBuilder buf = new StringBuilder();
buf.append('"');
for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
switch (ch) {
case '\r':
buf.append("\\r");
break;
case '\n':
buf.append("\\n");
break;
case '\\':
buf.append("\\\\");
break;
case '\t':
buf.append("\\t");
break;
case '\"':
buf.append("\\\"");
break;
default:
if (ch >= 32 && ch <= 127) {
buf.append(ch);
} else {
buf.append("\\u");
String h = makeHex(new byte[] {(byte) (ch >> 8), (byte) ch}, 0, 2, 0);
buf.append("0".repeat(4 - h.length()));
buf.append(h);
}
}
}
buf.append('"');
return buf.toString();
}
/**
* Print a class.
*
* @throws IllegalArgumentException if cr is null
*/
public void doClass(final ClassReader cr)
throws InvalidClassFileException, InvalidBytecodeException, IOException {
if (cr == null) {
throw new IllegalArgumentException("cr is null");
}
w.write("Class: " + cr.getName() + '\n');
if (printConstantPool) {
ConstantPoolParser cp = cr.getCP();
for (int i = 1; i < cp.getItemCount(); i++) {
int t = cp.getItemType(i);
if (t > 0) {
w.write(" Constant pool item " + i + ": ");
w.write(getCPItemString(cp, i));
w.write("\n");
}
}
}
ClassReader.AttrIterator attrs = new ClassReader.AttrIterator();
cr.initClassAttributeIterator(attrs);
dumpAttributes(cr, attrs);
w.write("\n");
int fieldCount = cr.getFieldCount();
w.write(fieldCount + " fields:\n");
for (int i = 0; i < fieldCount; i++) {
w.write(
cr.getFieldName(i)
+ ' '
+ cr.getFieldType(i)
+ ' '
+ dumpFlags(cr.getFieldAccessFlags(i))
+ '\n');
cr.initFieldAttributeIterator(i, attrs);
dumpAttributes(cr, attrs);
}
w.write("\n");
int methodCount = cr.getMethodCount();
w.write(methodCount + " methods:\n");
for (int i = 0; i < methodCount; i++) {
w.write(
cr.getMethodName(i)
+ ' '
+ cr.getMethodType(i)
+ ' '
+ dumpFlags(cr.getMethodAccessFlags(i))
+ '\n');
cr.initMethodAttributeIterator(i, attrs);
dumpAttributes(cr, attrs);
}
w.write("\n");
}
}
| 14,758
| 32.316027
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/tools/ClassSearcher.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT.tools;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassConstants;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
/**
* This is a demo class.
*
* <p>Class files are taken as input arguments (or if there are none, from standard input). We
* search those class files for all references to the Java library classes "SoftReference" or
* "WeakReference". This is just a demo to show how to write a simple tool like this. Here we're
* using the OfflineInstrumenter class to manage loading a set of class files and JARs for analysis;
* we don't actually modify any code.
*
* <p>In Unix, I run it like this: java -cp ~/dev/shrike/shrike
* com.ibm.wala.shrikeBT.shrikeCT.tools.ClassSearcher test.jar -o output.jar
*/
public class ClassSearcher {
private static OfflineInstrumenter instrumenter;
private static int scanned = 0;
public static void main(String[] args) throws Exception {
instrumenter = new OfflineInstrumenter();
try (final Writer w = new BufferedWriter(new FileWriter("report", true))) {
instrumenter.parseStandardArgs(args);
instrumenter.beginTraversal();
ClassInstrumenter ci;
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w, instrumenter.getLastClassResourceName());
}
instrumenter.close();
}
System.out.println("Classes scanned: " + scanned);
}
private static void doClass(final ClassInstrumenter ci, Writer w, String resource)
throws Exception {
scanned++;
String cl1 = "java/lang/ref/WeakReference";
String cl2 = "java/lang/ref/SoftReference";
ClassReader r = ci.getReader();
ConstantPoolParser cp = r.getCP();
for (int i = 1; i < cp.getItemCount(); i++) {
if (cp.getItemType(i) == ClassConstants.CONSTANT_Class
&& (cp.getCPClass(i).equals(cl1) || cp.getCPClass(i).equals(cl2))) {
w.write(cp.getCPClass(i) + ' ' + resource + ' ' + r.getName() + '\n');
}
}
}
}
| 2,624
| 35.458333
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/shrikeCT/tools/MethodTracer.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.shrikeCT.tools;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.Disassembler;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.Instruction;
import com.ibm.wala.shrike.shrikeBT.InvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.MethodEditor;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.analysis.Verifier;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintStream;
import java.io.Writer;
/**
* This is a demo class.
*
* <p>Class files are taken as input arguments (or if there are none, from standard input). The
* methods in those files are instrumented: we insert a System.err.println() at ever method call,
* and a System.err.println() at every method entry.
*
* <p>In Unix, I run it like this: java -cp ~/dev/shrike/shrike
* com.ibm.wala.shrikeBT.shrikeCT.tools.MethodTracer test.jar -o output.jar
*
* <p>All modified classes are copied into "output.jar". Some classes may not be modified. To run
* the resulting code, you should put output.jar and test.jar on the classpath, and put output.jar
* before test.jar. Disassembled code is written to the file "report" under the current directory.
*/
public class MethodTracer {
private static final boolean disasm = true;
private static final boolean verify = true;
private static final boolean INSTRUMENT_CALLERS = false;
private static OfflineInstrumenter instrumenter;
public static void main(String[] args) throws Exception {
for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter();
try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
instrumenter.parseStandardArgs(args);
instrumenter.setPassUnmodifiedClasses(false);
instrumenter.beginTraversal();
ClassInstrumenter ci;
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w);
}
}
instrumenter.close();
}
}
// Keep these commonly used instructions around. This trick can speed up
// instrumentation tools a bit. It's always safe because Instruction objects
// are always immutable and shareable.
static final Instruction getSysErr = Util.makeGet(System.class, "err");
static final Instruction callPrintln =
Util.makeInvoke(PrintStream.class, "println", new Class[] {String.class});
private static void doClass(final ClassInstrumenter ci, Writer w) throws Exception {
w.write("Class: " + ci.getReader().getName() + '\n');
w.flush();
for (int i = 0; i < ci.getReader().getMethodCount(); i++) {
MethodData d = ci.visitMethod(i);
// d could be null, e.g., if the method is abstract or native
if (d != null) {
w.write(
"Instrumenting "
+ ci.getReader().getMethodName(i)
+ ' '
+ ci.getReader().getMethodType(i)
+ ":\n");
w.flush();
if (disasm) {
w.write("Initial ShrikeBT code:\n");
new Disassembler(d).disassembleTo(w);
w.flush();
}
if (verify) {
// verify the incoming code
Verifier v = new Verifier(d);
v.verify();
}
MethodEditor me = new MethodEditor(d);
me.beginPass();
final String msg0 =
"Call to "
+ Util.makeClass('L' + ci.getReader().getName() + ';')
+ '.'
+ ci.getReader().getMethodName(i);
me.insertAtStart(
new MethodEditor.Patch() {
@Override
public void emitTo(MethodEditor.Output w) {
w.emit(getSysErr);
w.emit(ConstantInstruction.makeString(msg0));
w.emit(callPrintln);
}
});
if (INSTRUMENT_CALLERS) {
IInstruction[] ins = d.getInstructions();
for (int k = 0; k < ins.length; k++) {
if (ins[k] instanceof InvokeInstruction) {
InvokeInstruction instr = (InvokeInstruction) ins[k];
final String msg =
"Call from "
+ Util.makeClass('L' + ci.getReader().getName() + ';')
+ '.'
+ ci.getReader().getMethodName(i)
+ ':'
+ k
+ " to target "
+ Util.makeClass(instr.getClassType())
+ '.'
+ instr.getMethodName();
me.insertBefore(
k,
new MethodEditor.Patch() {
@Override
public void emitTo(MethodEditor.Output w) {
w.emit(getSysErr);
w.emit(ConstantInstruction.makeString(msg));
w.emit(callPrintln);
}
});
}
}
}
// this updates the data d
me.applyPatches();
if (disasm) {
w.write("Final ShrikeBT code:\n");
new Disassembler(d).disassembleTo(w);
w.flush();
}
if (verify) {
// verify outgoing code
Verifier v = new Verifier(d);
v.verify();
}
}
}
if (ci.isChanged()) {
instrumenter.outputModifiedClass(ci);
}
}
}
| 6,013
| 33.365714
| 98
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/tools/MethodOptimizer.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.tools;
import com.ibm.wala.shrike.shrikeBT.DupInstruction;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.LoadInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.MethodEditor;
import com.ibm.wala.shrike.shrikeBT.MethodEditor.Output;
import com.ibm.wala.shrike.shrikeBT.PopInstruction;
import com.ibm.wala.shrike.shrikeBT.StoreInstruction;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.info.LocalAllocator;
import java.util.Arrays;
import java.util.BitSet;
@Deprecated
public final class MethodOptimizer {
private final MethodData data;
private IInstruction[] instructions;
private ExceptionHandler[][] handlers;
private final MethodEditor editor;
// The value at index [i][N] is the index of the only instruction which pushes
// a value onto
// the stack which is #N popped by instruction i, or -2 if there is no such
// instruction
// or -1 if there is more than one such instruction.
private int[][] uniqueStackDefLocations;
// The value at index i[N] is the index of the only instruction which pops a
// value off
// the stack which is pushed by instruction i, or -2 if there is no such
// instruction
// or -1 if there is more than one such instruction.
private int[] uniqueStackUseLocations;
private int[] stackSizes;
private int[][] backEdges;
// The value at index i is the index of the only instruction which stores a
// value onto
// the stack which is popped by instruction i, or -2 if there is no such
// instruction
// or -1 if there is more than one such instruction.
static final int[] noEdges = new int[0];
public MethodOptimizer(MethodData d, MethodEditor e) {
if (d == null) {
throw new IllegalArgumentException("null d");
}
this.data = d;
this.editor = e;
}
public MethodOptimizer(MethodData d) {
this(d, new MethodEditor(d));
}
public static class UnoptimizableCodeException extends Exception {
private static final long serialVersionUID = 2543170335674010642L;
public UnoptimizableCodeException(String s) {
super(s);
}
}
public int findUniqueStackDef(final int instr, final int stack)
throws UnoptimizableCodeException {
instructions = editor.getInstructions();
handlers = editor.getHandlers();
checkConsistentStackSizes();
buildBackEdges();
buildStackDefMap();
return uniqueStackDefLocations[instr][stack];
}
public void optimize() throws UnoptimizableCodeException {
boolean changed;
do {
instructions = editor.getInstructions();
handlers = editor.getHandlers();
checkConsistentStackSizes();
buildBackEdges();
editor.beginPass();
buildStackDefMap();
pushBackLocalStores();
forwardDups();
changed = editor.applyPatches();
editor.endPass();
} while (changed);
}
private void buildBackEdges() {
int[] backEdgeCount = new int[instructions.length];
for (int i = 0; i < instructions.length; i++) {
int[] targets = instructions[i].getBranchTargets();
for (int target : targets) {
backEdgeCount[target]++;
}
ExceptionHandler[] hs = handlers[i];
for (ExceptionHandler h : hs) {
backEdgeCount[h.getHandler()]++;
}
}
backEdges = new int[instructions.length][];
for (int i = 0; i < backEdges.length; i++) {
if (backEdgeCount[i] > 0) {
backEdges[i] = new int[backEdgeCount[i]];
} else {
backEdges[i] = noEdges;
}
}
Arrays.fill(backEdgeCount, 0);
for (int i = 0; i < instructions.length; i++) {
int[] targets = instructions[i].getBranchTargets();
for (int target2 : targets) {
int target = target2;
backEdges[target][backEdgeCount[target]] = i;
backEdgeCount[target]++;
}
ExceptionHandler[] hs = handlers[i];
for (ExceptionHandler element : hs) {
int target = element.getHandler();
backEdges[target][backEdgeCount[target]] = i;
backEdgeCount[target]++;
}
}
}
private int checkConsistentStackSizes() throws UnoptimizableCodeException {
stackSizes = new int[instructions.length];
Arrays.fill(stackSizes, -1);
checkStackSizesAt(0, 0);
int result = 0;
for (int stackSize : stackSizes) {
result = Math.max(result, stackSize);
}
return result;
}
private void checkStackSizesAt(int instruction, int stackSize) throws UnoptimizableCodeException {
while (true) {
if (instruction < 0 || instruction >= instructions.length) {
throw new UnoptimizableCodeException("Code exits in an illegal way");
}
if (stackSizes[instruction] != -1) {
if (stackSizes[instruction] != stackSize) {
throw new UnoptimizableCodeException(
"Mismatched stack sizes at "
+ instruction
+ ": "
+ stackSize
+ " and "
+ stackSizes[instruction]);
} else {
return;
}
}
stackSizes[instruction] = stackSize;
IInstruction instr = instructions[instruction];
stackSize -= instr.getPoppedCount();
if (stackSize < 0) {
throw new UnoptimizableCodeException("Stack underflow at " + instruction);
}
if (instr instanceof DupInstruction) {
DupInstruction d = (DupInstruction) instr;
stackSize += d.getSize() + d.getPoppedCount();
} else if (instr.getPushedType(null) != null) {
stackSize++;
}
int[] targets = instr.getBranchTargets();
for (int target : targets) {
checkStackSizesAt(target, stackSize);
}
ExceptionHandler[] hs = handlers[instruction];
for (ExceptionHandler element : hs) {
checkStackSizesAt(element.getHandler(), 1);
}
if (!instr.isFallThrough()) {
return;
}
instruction++;
}
}
private static boolean instructionKillsVar(IInstruction instr, int v) {
if (instr instanceof StoreInstruction) {
StoreInstruction st = (StoreInstruction) instr;
return st.getVarIndex() == v
|| (Util.getWordSize(st.getType()) == 2 && st.getVarIndex() + 1 == v);
} else {
return false;
}
}
private void forwardDups() {
for (int i = 0; i < instructions.length; i++) {
IInstruction instr = instructions[i];
if (instr instanceof DupInstruction
&& ((DupInstruction) instr).getDelta() == 0
&& uniqueStackDefLocations[i][0] >= 0
&& instructions[uniqueStackDefLocations[i][0]] instanceof LoadInstruction) {
int source = uniqueStackDefLocations[i][0];
final LoadInstruction li = (LoadInstruction) instructions[source];
for (int j = 0; j < instructions.length; j++) {
int[] locs = uniqueStackDefLocations[j];
if (locs[0] == i) {
// check to see if the variable is killed along any path from the
// dup
// to its use
BitSet path = getInstructionsOnPath(source, j);
boolean killed = false;
int v = li.getVarIndex();
for (int k = 0; j < instructions.length && !killed; k++) {
if (path.get(k)) {
if (instructionKillsVar(instructions[k], v)) {
killed = true;
}
}
}
if (!killed) {
editor.insertBefore(
j,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(PopInstruction.make(1));
w.emit(li);
}
});
}
}
}
}
}
}
private void pushBackLocalStores() {
for (int i = 0; i < instructions.length; i++) {
IInstruction instr = instructions[i];
if (instr instanceof StoreInstruction
&& uniqueStackDefLocations[i][0] >= 0
&& uniqueStackDefLocations[i][0] != i - 1
&& uniqueStackUseLocations[uniqueStackDefLocations[i][0]] == i) {
final StoreInstruction s = (StoreInstruction) instr;
int source = uniqueStackDefLocations[i][0];
// Check if the path from source to i contains anything killing the
// variable
BitSet path = getInstructionsOnPath(source, i);
boolean killed = false;
int v = s.getVarIndex();
for (int j = 0; j < instructions.length && !killed; j++) {
if (path.get(j)) {
if (instructionKillsVar(instructions[j], v)) {
killed = true;
}
}
}
if (killed) {
final String type = s.getType();
final int newVar = LocalAllocator.allocate(data, type);
// put a store to the newVar right after the source
editor.insertAfter(
source,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(StoreInstruction.make(type, newVar));
}
});
// load newVar before storing to correct variable
editor.insertBefore(
i,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(LoadInstruction.make(type, newVar));
}
});
} else {
// remove store instruction
editor.replaceWith(
i,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {}
});
// replace it right after the source
editor.insertAfter(
source,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(s);
}
});
}
}
}
}
private void buildStackDefMap() {
int[][] abstractStacks = new int[instructions.length][];
for (int i = 0; i < instructions.length; i++) {
abstractStacks[i] = new int[stackSizes[i]];
Arrays.fill(abstractStacks[i], -2);
}
for (int i = 0; i < instructions.length; i++) {
if (instructions[i] instanceof DupInstruction) {
DupInstruction d = (DupInstruction) instructions[i];
for (int j = 0; j < 2 * d.getSize() + d.getDelta(); j++) {
followStackDef(abstractStacks, i, i + 1, stackSizes[i + 1] - 1 - j);
}
} else if (instructions[i].getPushedType(null) != null) {
followStackDef(abstractStacks, i, i + 1, stackSizes[i + 1] - 1);
}
}
uniqueStackDefLocations = new int[instructions.length][];
for (int i = 0; i < instructions.length; i++) {
uniqueStackDefLocations[i] = new int[instructions[i].getPoppedCount()];
int popped = instructions[i].getPoppedCount();
System.arraycopy(
abstractStacks[i], stackSizes[i] - popped, uniqueStackDefLocations[i], 0, popped);
}
uniqueStackUseLocations = new int[instructions.length];
Arrays.fill(uniqueStackUseLocations, -2);
for (int i = 0; i < instructions.length; i++) {
abstractStacks[i] = new int[stackSizes[i]];
Arrays.fill(abstractStacks[i], -2);
}
for (int i = 0; i < instructions.length; i++) {
int count = instructions[i].getPoppedCount();
if (count == 1) {
followStackUse(abstractStacks, i, i, stackSizes[i] - 1);
} else if (count > 1) {
for (int j = 0; j < count; j++) {
followStackUse(abstractStacks, -1, i, stackSizes[i] - 1 - j);
}
}
}
for (int i = 0; i < instructions.length; i++) {
if (instructions[i].getPushedType(null) != null) {
uniqueStackUseLocations[i] = abstractStacks[i + 1][stackSizes[i + 1] - 1];
}
}
}
private void followStackDef(
int[][] abstractDefStacks, int def, int instruction, int stackPointer) {
while (true) {
int[] stack = abstractDefStacks[instruction];
if (stackPointer >= stack.length) {
// the value must have been popped off by the last instruction
return;
}
if (stack[stackPointer] == -2) {
stack[stackPointer] = def;
} else if (stack[stackPointer] == def) {
return;
} else if (stack[stackPointer] == -1) {
return;
} else {
stack[stackPointer] = -1;
def = -1;
}
int[] targets = instructions[instruction].getBranchTargets();
for (int target : targets) {
followStackDef(abstractDefStacks, def, target, stackPointer);
}
ExceptionHandler[] hs = handlers[instruction];
for (ExceptionHandler element : hs) {
followStackDef(abstractDefStacks, -1, element.getHandler(), 0);
}
if (!instructions[instruction].isFallThrough()) {
return;
}
instruction++;
}
}
private void followStackUse(
int[][] abstractUseStacks, int use, int instruction, int stackPointer) {
while (true) {
int[] stack = abstractUseStacks[instruction];
if (stackPointer >= stack.length) {
// the value must have been pushed by this instruction
return;
}
if (stack[stackPointer] == -2) {
stack[stackPointer] = use;
} else if (stack[stackPointer] == use || stack[stackPointer] == -1) {
return;
} else {
stack[stackPointer] = -1;
use = -1;
}
int[] back = backEdges[instruction];
for (int element : back) {
followStackUse(abstractUseStacks, use, element, stackPointer);
}
if (instruction == 0 || !instructions[instruction - 1].isFallThrough()) {
return;
}
instruction--;
}
}
private BitSet getInstructionsOnPath(int from, int to) {
BitSet reachable = new BitSet();
getReachableInstructions(reachable, from, to);
BitSet reaching = new BitSet();
getReachingInstructions(reaching, from, to);
reachable.and(reaching);
return reachable;
}
private void getReachableInstructions(BitSet bits, int from, int to) {
while (true) {
if (from == to) {
return;
}
bits.set(from);
int[] targets = instructions[from].getBranchTargets();
for (int target : targets) {
getReachableInstructions(bits, target, to);
}
if (!instructions[from].isFallThrough()) {
return;
}
from++;
}
}
private void getReachingInstructions(BitSet bits, int from, int to) {
while (true) {
if (to == from) {
return;
}
bits.set(to);
int[] targets = backEdges[to];
for (int target : targets) {
getReachingInstructions(bits, from, target);
}
if (to == 0 || !instructions[to - 1].isFallThrough()) {
return;
}
to--;
}
}
}
| 15,506
| 29.829026
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/tools/OfflineInstrumenterBase.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT.tools;
import com.ibm.wala.shrike.shrikeBT.analysis.ClassHierarchyProvider;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
/**
* This class provides functionality for performing offline instrumentation. It is subclassed with
* class-toolkit-specific functionality.
*/
public abstract class OfflineInstrumenterBase {
private int inputIndex;
private final HashSet<String> entryNames = new HashSet<>();
private final ArrayList<Input> inputs = new ArrayList<>();
private final BitSet ignoringInputs = new BitSet();
private File outputFile;
private boolean passUnmodifiedClasses = false;
private JarOutputStream outputJar;
private JarFile cachedJar;
private File cachedJarFile;
private ManifestBuilder manifestBuilder;
protected ClassHierarchyProvider cha;
/**
* This installs a ManifestBuilder callback that this class will notify whenever an entry has been
* added to the output zip file.
*/
public void setManifestBuilder(ManifestBuilder mb) {
manifestBuilder = mb;
}
/** Thiscallback is notified whenever an entry has been added to the output zip file. */
public interface ManifestBuilder {
void addEntry(ZipEntry ze);
}
/**
* This class represents a resource which can be opened and read; either a file or a JAR entry.
*/
abstract static class Input {
private String className;
/** Tell us what the classname is supposed to be, if it's a class file. */
public final void setClassName(String c) {
className = c.intern();
}
/** Returns the classname if it has been set. */
public final String getClassName() {
return className;
}
/** get name of resource used for input */
public abstract String getInputName();
/** Open the resource for reading as a stream. */
public abstract InputStream open() throws IOException;
/** @return true if this resource represents a class, false otherwise */
public boolean isClass() {
return true;
}
}
/**
* This class represents a JAR file entry. It might or might not be a class; we support non-class
* JAR resources so that we can copy them to the output JAR if the client requests that.
*/
final class JarInput extends Input {
private final File file;
private final String name;
/** Select a particular entry from a JAR file on disk. */
public JarInput(File f, String je) {
file = f;
name = je;
}
@Override
@SuppressWarnings("resource")
public InputStream open() throws IOException {
JarFile cachedJar = openCachedJar(file);
return cachedJar.getInputStream(cachedJar.getEntry(name));
}
@Override
public String toString() {
return file.getPath() + '#' + name;
}
@Override
public boolean isClass() {
return name.endsWith(".class");
}
@Override
public String getInputName() {
return name;
}
/** Get the underlying ZipEntry corresponding to this resource. */
@SuppressWarnings("resource")
public ZipEntry getEntry() throws IOException {
JarFile cachedJar = openCachedJar(file);
return cachedJar.getEntry(name);
}
}
/**
* Open a JAR/ZIP file. This routine caches the last JAR file opened to save effort when the same
* file is accessed again and again. DO NOT close the file returned by this routine until you've
* finished with this OfflineInstrumente completely. Also, this JarFile will be closed the next
* time someone calls openCachedJar.
*/
private JarFile openCachedJar(File file) throws IOException {
if (cachedJarFile == null || !cachedJarFile.equals(file)) {
if (cachedJar != null) {
cachedJar.close();
}
cachedJarFile = file;
cachedJar = new JarFile(file, false);
}
return cachedJar;
}
/**
* This class represents a plain old class file in the filesystem. Non-class file resources are
* not supported.
*/
static final class ClassInput extends Input {
private final File file;
private final File baseDirectory;
public ClassInput(File baseDirectory, File f) {
file = f;
this.baseDirectory = baseDirectory;
}
@Override
public InputStream open() throws IOException {
return new FileInputStream(file);
}
@Override
public String toString() {
return file.getPath();
}
@Override
public String getInputName() {
int base = baseDirectory.getPath().length() + 1;
return file.getPath().substring(base);
}
}
protected OfflineInstrumenterBase() {}
public void setClassHierarchyProvider(ClassHierarchyProvider cha) {
this.cha = cha;
}
/** Set the file in which instrumented classes will be deposited. */
public final void setOutputJar(File f) {
outputFile = f;
}
/** Indicate whether classes which are not modified will be put into the output jar anyway. */
public final void setPassUnmodifiedClasses(boolean pass) {
passUnmodifiedClasses = pass;
}
/** Add a JAR file containing source classes to instrument. */
public final void addInputJar(File f) throws IOException {
try (final JarFile jf = new JarFile(f, false)) {
for (Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements(); ) {
JarEntry entry = e.nextElement();
String name = entry.getName();
inputs.add(new JarInput(f, name));
}
}
}
/** Add a JAR entry containing a source class to instrument. */
public final void addInputJarEntry(File f, String name) {
inputs.add(new JarInput(f, name));
}
/** Add a class file containing a source class to instrument. */
public final void addInputClass(File baseDirectory, File f) {
inputs.add(new ClassInput(baseDirectory, f));
}
/**
* Add a directory containing class files to instrument. All subdirectories are also scanned.
*
* @throws IllegalArgumentException if d is null
*/
public final void addInputDirectory(File baseDirectory, File d)
throws IOException, IllegalArgumentException {
if (d == null) {
throw new IllegalArgumentException("d is null");
}
File[] fs = d.listFiles(f -> f.isDirectory() || f.getName().endsWith(".class"));
if (fs == null) {
throw new IllegalArgumentException("bad directory " + d.getAbsolutePath());
}
for (File f : fs) {
if (f.isDirectory()) {
addInputDirectory(baseDirectory, f);
} else {
addInputClass(baseDirectory, f);
}
}
}
/**
* Add something to instrument --- the name of a JAR file, a class file, a directory or an entry
* within a jar file (as filename#entryname). If we can't identify it, nothing is added and we
* return false.
*
* @throws IllegalArgumentException if a is null
*/
public final boolean addInputElement(File baseDirectory, String a) throws IOException {
if (a == null) {
throw new IllegalArgumentException("a is null");
}
try {
int poundIndex = a.indexOf('#');
if (poundIndex > 0) {
addInputJarEntry(new File(a.substring(0, poundIndex)), a.substring(poundIndex + 1));
return true;
}
File f = new File(a);
if (f.isDirectory()) {
addInputDirectory(baseDirectory, f);
return true;
} else if (f.exists()) {
if (a.endsWith(".class")) {
addInputClass(baseDirectory, f);
return true;
} else if (a.endsWith(".jar") || a.endsWith(".zip")) {
addInputJar(new File(a));
return true;
}
}
} catch (IOException ex) {
throw new IOException("Error reading input element '" + a + "': " + ex.getMessage());
}
return false;
}
/**
* Parse an argument list to find elements to instrument and the name of the output file. The "-o
* filename" option selects the output JAR file name. Any other argument not starting with "-" is
* added to the list of elements to instrument, if it appears to be the name of a class file, JAR
* file, or directory. If any argument starting with "--" is encountered, the rest of the
* command-line is considered leftover
*
* @return the arguments that were not understood
* @throws IllegalArgumentException if args == null
*/
public final String[] parseStandardArgs(String[] args)
throws IllegalArgumentException, IOException {
if (args == null) {
throw new IllegalArgumentException("args == null");
}
ArrayList<String> leftover = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
String a = args[i];
if (a == null) {
throw new IllegalArgumentException("args[" + i + "] is null");
}
if (a.equals("-o") && i + 1 < args.length) {
setOutputJar(new File(args[i + 1]));
i++;
continue;
} else if (!a.startsWith("-")) {
if (addInputElement(new File(a), a)) {
continue;
}
} else if (a.startsWith("--")) {
leftover.addAll(Arrays.asList(args).subList(i, args.length));
break;
}
leftover.add(a);
}
String[] r = new String[leftover.size()];
leftover.toArray(r);
return r;
}
/** @return the number of source classes to be instrumented */
public final int getNumInputClasses() {
return inputs.size();
}
/** Start traversing the source class list from the beginning. */
public final void beginTraversal() {
inputIndex = 0;
}
protected abstract Object makeClassFromStream(String inputName, BufferedInputStream s)
throws IOException;
protected abstract String getClassName(Object cl);
protected abstract void writeClassTo(Object cl, Object mods, OutputStream s) throws IOException;
protected final Object internalNextClass() throws IOException {
while (true) {
if (inputIndex >= inputs.size()) {
return null;
} else {
Input in = inputs.get(inputIndex);
inputIndex++;
if (ignoringInputs.get(inputIndex - 1) || !in.isClass()) {
continue;
}
try (final BufferedInputStream s = new BufferedInputStream(in.open())) {
Object r = makeClassFromStream(in.getInputName(), s);
String name = getClassName(r);
in.setClassName(name);
return r;
}
}
}
}
private static String toEntryName(String className) {
return className.replace('.', '/') + ".class";
}
/**
* Get the name of the resource containing the last class returned. This is either a file name
* (e.g., "com/ibm/Main.class"), or a JAR entry name (e.g., "apps/app.jar#com/ibm/Main.class").
*
* @return the resource name, or null if no class has been returned yet
*/
public final String getLastClassResourceName() {
if (inputIndex < 1) {
return null;
} else {
Input in = inputs.get(inputIndex - 1);
return in.toString();
}
}
/** Returns the File we are storing classes into. */
public final File getOutputFile() {
return outputFile;
}
protected final boolean internalOutputModifiedClass(Object cf, String name, Object mods)
throws IOException {
makeOutputJar();
if (entryNames.contains(name)) {
return false;
} else {
putNextEntry(new ZipEntry(name));
BufferedOutputStream s = new BufferedOutputStream(outputJar);
writeClassTo(cf, mods, s);
s.flush();
outputJar.closeEntry();
return true;
}
}
/** Set the JAR Comment for the output JAR. */
public final void setJARComment(String comment) throws IOException, IllegalStateException {
makeOutputJar();
outputJar.setComment(comment);
}
final void makeOutputJar() throws IOException, IllegalStateException {
if (outputJar == null) {
if (outputFile == null) {
throw new IllegalStateException("Output file was not set");
}
final FileOutputStream out = new FileOutputStream(outputFile);
outputJar = new JarOutputStream(out);
}
}
/** Skip the last class returned in every future traversal of the class list. */
public final void setIgnore() throws IllegalArgumentException {
if (inputIndex == 0) {
throw new IllegalArgumentException("Must get a class before ignoring it");
}
ignoringInputs.set(inputIndex - 1);
}
private static byte[] cachedBuf;
private static synchronized byte[] makeBuf() {
if (cachedBuf != null) {
byte[] r = cachedBuf;
cachedBuf = null;
return r;
} else {
return new byte[60000];
}
}
private static synchronized void releaseBuf(byte[] buf) {
cachedBuf = buf;
}
public static void copyStream(InputStream in, OutputStream out)
throws IllegalArgumentException, IOException {
if (in == null) {
throw new IllegalArgumentException("in == null");
}
byte[] buf = makeBuf();
try {
while (true) {
int read = in.read(buf);
if (read < 0) {
return;
}
out.write(buf, 0, read);
}
} finally {
releaseBuf(buf);
}
}
/**
* Add a raw ZipEntry to the output JAR. Call endOutputJarEntry() when you're done.
*
* @return the OutputStream to be used to write the entry contents
*/
public final OutputStream addOutputJarEntry(ZipEntry ze)
throws IOException, IllegalStateException {
if (outputJar == null) {
throw new IllegalStateException("output jar is null");
}
putNextEntry(ze);
return outputJar;
}
/** Complete and flush the entry initiated by addOutputJarEntry. */
public final void endOutputJarEntry() throws IOException, IllegalStateException {
if (outputJar == null) {
throw new IllegalStateException("output jar is null");
}
outputJar.closeEntry();
}
/**
* Call this to copy any unmodified classes to the output. This is called automatically by
* close(); you should only call this if you want to write an entry to the JAR file *after* the
* unmodified classes. This will only ever be called once per output JAR.
*/
public final void writeUnmodifiedClasses() throws IOException, IllegalStateException {
passUnmodifiedClasses = false;
makeOutputJar();
for (Input in : inputs) {
if (!in.isClass()) {
if (in instanceof JarInput) {
JarInput jin = (JarInput) in;
ZipEntry entry = jin.getEntry();
try (final InputStream s = jin.open()) {
ZipEntry newEntry = new ZipEntry(entry.getName());
newEntry.setComment(entry.getComment());
newEntry.setExtra(entry.getExtra());
newEntry.setTime(entry.getTime());
putNextEntry(newEntry);
copyStream(s, outputJar);
outputJar.closeEntry();
}
} else {
throw new Error("Unknown non-class input: " + in);
}
} else {
String name = in.getClassName();
if (name == null) {
try (final BufferedInputStream s = new BufferedInputStream(in.open(), 65536)) {
Object cl = makeClassFromStream(in.getInputName(), s);
String entryName = toEntryName(getClassName(cl));
if (!entryNames.contains(entryName)) {
putNextEntry(new ZipEntry(entryName));
BufferedOutputStream clOut = new BufferedOutputStream(outputJar);
writeClassTo(cl, null, clOut);
clOut.flush();
outputJar.closeEntry();
}
}
} else {
String entryName = toEntryName(name);
if (!entryNames.contains(entryName)) {
try (final BufferedInputStream s = new BufferedInputStream(in.open())) {
putNextEntry(new ZipEntry(entryName));
BufferedOutputStream clOut = new BufferedOutputStream(outputJar);
copyStream(s, clOut);
clOut.flush();
outputJar.closeEntry();
}
}
}
}
}
}
/** Call this when you're done modifying classes. */
public final void close() throws IOException, IllegalStateException {
if (passUnmodifiedClasses) {
writeUnmodifiedClasses();
}
if (outputJar != null) {
outputJar.close();
}
if (cachedJar != null) {
cachedJar.close();
}
}
private void putNextEntry(ZipEntry newEntry) throws IOException, IllegalStateException {
if (outputJar == null) {
throw new IllegalStateException();
}
outputJar.putNextEntry(newEntry);
entryNames.add(newEntry.getName());
if (manifestBuilder != null) {
manifestBuilder.addEntry(newEntry);
}
}
}
| 17,478
| 29.664912
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/AnnotationsReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import java.util.Arrays;
import java.util.Map;
/**
* This class reads Annotations attributes, e.g., RuntimeInvisibleAnnotations.
*
* @author sjfink
*/
public class AnnotationsReader extends AttributeReader {
/** offset in class file where this attribute begins */
protected final int beginOffset;
public AnnotationsReader(ClassReader.AttrIterator iter, String label)
throws InvalidClassFileException {
super(iter, label);
beginOffset = attr;
}
/** @return number of annotations in this attribute */
public int getAnnotationCount() throws InvalidClassFileException {
int offset = beginOffset + 6;
checkSize(offset, 2);
return cr.getUShort(offset);
}
/** @return total length of this attribute in bytes, <b>including</b> the first 6 bytes */
public int getAttributeSize() throws InvalidClassFileException {
int offset = beginOffset + 2;
checkSize(offset, 4);
return cr.getInt(offset) + 6;
}
/**
* get the Utf8 constant pool value, where the constant pool offset is given in the class
*
* @param offset offset in the class file at which the constant pool offset is given
*/
protected String getUtf8ConstantPoolValue(int offset) throws InvalidClassFileException {
checkSize(offset, 2);
int cpOffset = cr.getUShort(offset);
return cr.getCP().getCPUtf8(cpOffset);
}
/**
* Marker interface for possible element values in an annotation attribute.
*
* @see AnnotationsReader#readElementValueAndSize(int)
*/
public interface ElementValue {}
/**
* Represents a constant argument to an annotation. Class arguments (e.g., {@code Foo.class}) are
* also represented with this type, with the value being the String class name.
*/
public static class ConstantElementValue implements ElementValue {
/** the constant value */
public final Object val;
public ConstantElementValue(Object val) {
this.val = val;
}
@Override
public String toString() {
return String.valueOf(val);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((val == null) ? 0 : val.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ConstantElementValue other = (ConstantElementValue) obj;
if (val == null) {
if (other.val != null) return false;
} else if (!val.equals(other.val)) return false;
return true;
}
}
/** Represents enum constant annotation arguments. */
public static class EnumElementValue implements ElementValue {
/** the name of the enum type */
public final String enumType;
/** the enum value */
public final String enumVal;
public EnumElementValue(String enumType, String enumVal) {
super();
this.enumType = enumType;
this.enumVal = enumVal;
}
@Override
public String toString() {
return "EnumElementValue [type=" + enumType + ", val=" + enumVal + ']';
}
}
/** represents an annotation argument that itself is an array of arguments */
public static class ArrayElementValue implements ElementValue {
/** the values contained in the array */
public final ElementValue[] vals;
public ArrayElementValue(ElementValue[] vals) {
super();
this.vals = vals;
}
@Override
public String toString() {
return "ArrayElementValue [vals=" + Arrays.toString(vals) + ']';
}
}
/**
* get all the annotations declared in this attribute.
*
* <pre>
* RuntimeVisibleAnnotations_attribute {
* u2 attribute_name_index;
* u4 attribute_length;
* u2 num_annotations;
* annotation annotations[num_annotations];
* }
* </pre>
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.16">JLS
* (SE8), 4.7.16</a>
*/
public AnnotationAttribute[] getAllAnnotations() throws InvalidClassFileException {
AnnotationAttribute[] result = new AnnotationAttribute[getAnnotationCount()];
int offset = beginOffset + 8; // skip attribute_name_index,
// attribute_length, and num_annotations
for (int i = 0; i < result.length; i++) {
Pair<AnnotationAttribute, Integer> attributeAndSize = getAttributeAndSize(offset);
result[i] = attributeAndSize.fst;
offset += attributeAndSize.snd;
}
return result;
}
/**
*
*
* <pre>
* param_annotations {
* u2 attribute_name_index;
* u4 attribute_length;
* u1 num_parameters;
* {
* u2 num_annotations;
* annotation annotations[num_annotations];
* } parameter_annotations[num_parameters];
* </pre>
*/
public AnnotationAttribute[][] getAllParameterAnnotations() throws InvalidClassFileException {
int numParamOffset = beginOffset + 6;
checkSize(numParamOffset, 1);
int paramCount = cr.getByte(numParamOffset);
AnnotationAttribute[][] result = new AnnotationAttribute[paramCount][];
// skip attribute_name_index, attribute_length, and num_parameters
int offset = beginOffset + 7;
for (int i = 0; i < result.length; i++) {
checkSize(offset, 2);
result[i] = new AnnotationAttribute[cr.getUShort(offset)];
offset += 2;
for (int j = 0; j < result[i].length; j++) {
Pair<AnnotationAttribute, Integer> attributeAndSize = getAttributeAndSize(offset);
result[i][j] = attributeAndSize.fst;
offset += attributeAndSize.snd;
}
}
return result;
}
/**
*
*
* <pre>
* annotation {
* u2 type_index;
* u2 num_element_value_pairs;
* { u2 element_name_index;
* element_value value;
* } element_value_pairs[num_element_value_pairs]
* </pre>
*/
protected Pair<AnnotationAttribute, Integer> getAttributeAndSize(int begin)
throws InvalidClassFileException {
String type = getUtf8ConstantPoolValue(begin);
int numElementValuePairs = cr.getUShort(begin + 2);
int size = 4;
int offset = begin + 4;
Map<String, ElementValue> elementName2Val = HashMapFactory.make();
for (int i = 0; i < numElementValuePairs; i++) {
String elementName = getUtf8ConstantPoolValue(offset);
offset += 2;
Pair<ElementValue, Integer> elementValAndSize = readElementValueAndSize(offset);
offset += elementValAndSize.snd;
size += elementValAndSize.snd + 2;
elementName2Val.put(elementName, elementValAndSize.fst);
}
return Pair.make(new AnnotationAttribute(type, elementName2Val), size);
}
/**
* Representation of an annotation attribute. An annotation has the following format in the
* bytecode:
*
* <pre>
* annotation {
* u2 type_index;
* u2 num_element_value_pairs;
* { u2 element_name_index;
* element_value value;
* } element_value_pairs[num_element_value_pairs];
* </pre>
*
* See the JVM specification section 4.7.16 for details.
*
* <p>This class implements {@link ElementValue} to handle nested annotations.
*/
public static class AnnotationAttribute implements ElementValue {
/** the type of the annotation */
public final String type;
/** the arguments to the annotation */
public final Map<String, ElementValue> elementValues;
public AnnotationAttribute(String type, Map<String, ElementValue> elementValues) {
super();
this.type = type;
this.elementValues = elementValues;
}
@Override
public String toString() {
return "AnnotationElementValue [type=" + type + ", elementValues=" + elementValues + ']';
}
}
/**
*
*
* <pre>
* element_value {
* u1 tag;
* union {
* u2 const_value_index;
* { u2 type_name_index;
* u2 const_name_index;
* } enum_const_value;
* u2 class_info_index;
* annotation annotation_value;
* { u2 num_values;
* element_value values[num_values];
* } array_value;
* } value;
* </pre>
*
* A constant value (including class info) is represented by a {@link ConstantElementValue}. An
* enum constant value is represented by an {@link EnumElementValue}. An array value is
* represented by an {@link ArrayElementValue}. Finally, a nested annotation is represented by an
* {@link AnnotationAttribute}.
*/
protected Pair<ElementValue, Integer> readElementValueAndSize(int offset)
throws IllegalArgumentException, InvalidClassFileException {
char tag = (char) cr.getByte(offset);
// meaning of this short depends on the tag
int nextShort = cr.getUShort(offset + 1);
switch (tag) {
case 'B':
case 'C':
case 'I':
case 'S':
case 'Z':
return Pair.<ElementValue, Integer>make(
new ConstantElementValue(cr.getCP().getCPInt(nextShort)), 3);
case 'J':
return Pair.<ElementValue, Integer>make(
new ConstantElementValue(cr.getCP().getCPLong(nextShort)), 3);
case 'D':
return Pair.<ElementValue, Integer>make(
new ConstantElementValue(cr.getCP().getCPDouble(nextShort)), 3);
case 'F':
return Pair.<ElementValue, Integer>make(
new ConstantElementValue(cr.getCP().getCPFloat(nextShort)), 3);
case 's': // string
case 'c': // class; just represent as a constant element with the type name
return Pair.<ElementValue, Integer>make(
new ConstantElementValue(cr.getCP().getCPUtf8(nextShort)), 3);
case 'e': // enum
return Pair.<ElementValue, Integer>make(
new EnumElementValue(
cr.getCP().getCPUtf8(nextShort), cr.getCP().getCPUtf8(cr.getUShort(offset + 3))),
5);
case '[': // array
int numValues = nextShort;
int numArrayBytes = 3; // start with 3 for the tag and num_values bytes
ElementValue[] vals = new ElementValue[numValues];
// start curOffset at beginning of array values
int curArrayOffset = offset + 3;
for (int i = 0; i < numValues; i++) {
Pair<ElementValue, Integer> arrayElemValueAndSize =
readElementValueAndSize(curArrayOffset);
vals[i] = arrayElemValueAndSize.fst;
curArrayOffset += arrayElemValueAndSize.snd;
numArrayBytes += arrayElemValueAndSize.snd;
}
return Pair.<ElementValue, Integer>make(new ArrayElementValue(vals), numArrayBytes);
case '@': // annotation
Pair<AnnotationAttribute, Integer> attributeAndSize = getAttributeAndSize(offset + 1);
// add 1 to size for the tag
return Pair.<ElementValue, Integer>make(attributeAndSize.fst, attributeAndSize.snd + 1);
default:
assert false;
return null;
}
}
// //////////////
// utility methods for reading well-known annotation types
// //////////////
public enum AnnotationType {
RuntimeVisibleAnnotations,
RuntimeInvisibleAnnotations,
RuntimeVisibleParameterAnnotations,
RuntimeInvisibleParameterAnnotations
}
public static boolean isKnownAnnotation(String name) {
for (AnnotationType t : AnnotationType.values()) {
if (t.name().equals(name)) {
return true;
}
}
return false;
}
public static AnnotationsReader getReaderForAnnotation(
AnnotationType type, ClassReader.AttrIterator iter) {
// search for the desired attribute
final String attrName = type.toString();
try {
for (; iter.isValid(); iter.advance()) {
if (iter.getName().equals(attrName)) {
return new AnnotationsReader(iter, attrName);
}
}
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE();
}
return null;
}
}
| 12,451
| 31.175711
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/AttributeReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/**
* This is a base class for "attribute readers", the classes which provide access to the contents of
* attributes.
*/
public abstract class AttributeReader {
protected final ClassReader cr;
protected final int attr;
protected final int length;
/**
* Construct a reader for a particular attribute.
*
* @param attr a valid attribute iterator pointing at the attribute to read
* @param expectedName the name the attribute must have
*/
protected AttributeReader(ClassReader.AttrIterator attr, String expectedName)
throws InvalidClassFileException {
if (attr == null) {
throw new IllegalArgumentException("attr cannot be null");
}
attr.verifyValid();
this.cr = attr.cr;
this.attr = attr.offset;
this.length = attr.size;
String n = attr.getName();
if (expectedName != n && !expectedName.equals(n)) {
throw new IllegalArgumentException(
"Attribute " + n + " is not a " + expectedName + " attribute");
}
}
/** @return the class reader the attribute belongs to */
public final ClassReader getClassReader() {
return cr;
}
/** @return the offset of the raw attribute data (including the attribute header) */
public final int getRawOffset() {
return attr;
}
/** @return the size of the raw attribute data (including the attribute header) */
public final int getRawSize() {
return length;
}
/**
* Ensure that the len bytes starting at offset fall within the attribute data.
*
* @throws InvalidClassFileException if the bytes fall outside the data
*/
protected final void checkSize(int offset, int len) throws InvalidClassFileException {
if (length < offset - attr + len) {
throw new InvalidClassFileException(
offset,
"Attribute data too short, expected " + len + " bytes, got " + (length + attr - offset));
}
}
/**
* Ensure that the len bytes starting at offset end at the end of the attribute data.
*
* @throws InvalidClassFileException if the bytes do not end at the end of the attribute
*/
protected final void checkSizeEquals(int offset, int len) throws InvalidClassFileException {
if (length != offset - attr + len) {
throw new InvalidClassFileException(
offset,
"Attribute data invalid length, expected "
+ len
+ " bytes, got "
+ (length + attr - offset));
}
}
}
| 2,851
| 30.340659
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/BootstrapMethodsReader.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import com.ibm.wala.shrike.shrikeCT.ClassReader.AttrIterator;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
public class BootstrapMethodsReader extends AttributeReader {
public interface BootstrapMethod {
String LAMBDA_METAFACTORY_CLASS = "java/lang/invoke/LambdaMetafactory";
String BOOTSTRAP_METHOD_NAME = "metafactory";
String BOOTSTRAP_METHOD_TYPE =
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;";
byte invokeType();
String methodClass();
String methodName();
String methodType();
int callArgumentCount();
Object callArgument(ClassLoader cl, int i);
int callArgumentIndex(int i);
int callArgumentKind(int i);
ConstantPoolParser getCP();
int getIndexInClassFile();
/**
* Is this the bootstrap method used for compiling Java lambdas?
*
* @return {@code true} if the method is {@link
* java.lang.invoke.LambdaMetafactory#metafactory(java.lang.invoke.MethodHandles.Lookup,
* String, java.lang.invoke.MethodType, java.lang.invoke.MethodType,
* java.lang.invoke.MethodHandle, java.lang.invoke.MethodType)}
*/
default boolean isBootstrapForJavaLambdas() {
return methodClass().equals(LAMBDA_METAFACTORY_CLASS)
&& methodName().equals(BOOTSTRAP_METHOD_NAME)
&& methodType().equals(BOOTSTRAP_METHOD_TYPE);
}
}
private BootstrapMethod entries[];
protected BootstrapMethodsReader(AttrIterator attr) throws InvalidClassFileException {
super(attr, "BootstrapMethods");
readBootstrapEntries();
}
private void readBootstrapEntries() throws InvalidClassFileException {
final ConstantPoolParser cp = cr.getCP();
entries = new BootstrapMethod[cr.getUShort(attr + 6)];
int base = 8;
for (int i = 0; i < entries.length; i++) {
final int methodHandleOffset = cr.getUShort(attr + base);
final int argsBase = attr + base + 4;
final int index = i;
final int argumentCount = cr.getUShort(attr + base + 2);
entries[i] =
new BootstrapMethod() {
private final byte invokeType = cp.getCPHandleKind(methodHandleOffset);
private final String methodClass = cp.getCPHandleClass(methodHandleOffset);
private final String methodName = cp.getCPHandleName(methodHandleOffset);
private final String methodType = cp.getCPHandleType(methodHandleOffset);
@Override
public String toString() {
return methodClass + ':' + methodName + methodType;
}
@Override
public byte invokeType() {
return invokeType;
}
@Override
public String methodClass() {
return methodClass;
}
@Override
public String methodName() {
return methodName;
}
@Override
public String methodType() {
return methodType;
}
@Override
public int callArgumentCount() {
return argumentCount;
}
@Override
public int callArgumentKind(int i) {
return cp.getItemType(callArgumentIndex(i));
}
@Override
public int callArgumentIndex(int i) {
assert 0 <= i && i < argumentCount;
int index = argsBase + (2 * i);
return cr.getUShort(index);
}
@Override
public Object callArgument(ClassLoader cl, int i) {
try {
int index = callArgumentIndex(i);
int t = callArgumentKind(i);
switch (t) {
case ClassConstants.CONSTANT_Utf8:
return cp.getCPUtf8(index);
case ClassConstants.CONSTANT_Class:
return cp.getCPClass(index);
case ClassConstants.CONSTANT_String:
return cp.getCPString(index);
case ClassConstants.CONSTANT_Integer:
return cp.getCPInt(index);
case ClassConstants.CONSTANT_Float:
return cp.getCPFloat(index);
case ClassConstants.CONSTANT_Double:
return cp.getCPDouble(index);
case ClassConstants.CONSTANT_Long:
return cp.getCPLong(index);
case ClassConstants.CONSTANT_MethodHandle:
String className = cp.getCPHandleClass(index);
String eltName = cp.getCPHandleName(index);
String eltDesc = cp.getCPHandleType(index);
MethodType type = MethodType.fromMethodDescriptorString(eltDesc, cl);
Class<?> cls = Class.forName(className.replace('/', '.'), false, cl);
Method m =
cls.getDeclaredMethod(
eltName,
type.parameterList().toArray(new Class[type.parameterCount()]));
Lookup lk = MethodHandles.lookup().in(cls);
m.setAccessible(true);
return lk.unreflect(m);
case ClassConstants.CONSTANT_MethodType:
return MethodType.fromMethodDescriptorString(cp.getCPMethodType(index), cl);
default:
assert false : "invalid type " + t;
}
} catch (IllegalArgumentException
| IllegalAccessException
| SecurityException
| NoSuchMethodException
| ClassNotFoundException
| InvalidClassFileException e) {
throw new RuntimeException(e);
}
return null;
}
@Override
public ConstantPoolParser getCP() {
return cp;
}
@Override
public int getIndexInClassFile() {
return index;
}
};
base += (argumentCount * 2) + 4;
}
}
public int count() {
return entries.length;
}
public BootstrapMethod getEntry(int i) {
return entries[i];
}
}
| 6,948
| 33.231527
| 215
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/ClassConstants.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/**
* This interface defines class file constants used by ShrikeCT. The names and values are taken
* directly from the JVM spec.
*/
public interface ClassConstants {
int MAGIC = 0xCAFEBABE;
byte CONSTANT_Utf8 = 1;
byte CONSTANT_Integer = 3;
byte CONSTANT_Float = 4;
byte CONSTANT_Long = 5;
byte CONSTANT_Double = 6;
byte CONSTANT_Class = 7;
byte CONSTANT_String = 8;
byte CONSTANT_FieldRef = 9;
byte CONSTANT_MethodRef = 10;
byte CONSTANT_InterfaceMethodRef = 11;
byte CONSTANT_NameAndType = 12;
byte CONSTANT_MethodHandle = 15;
byte CONSTANT_MethodType = 16;
byte CONSTANT_InvokeDynamic = 18;
byte CONSTANT_Module = 19;
byte CONSTANT_Package = 20;
short ACC_PUBLIC = 0x1;
short ACC_PRIVATE = 0x2;
short ACC_PROTECTED = 0x4;
short ACC_STATIC = 0x8;
short ACC_FINAL = 0x10;
short ACC_SYNCHRONIZED = 0x20;
short ACC_SUPER = 0x20;
short ACC_VOLATILE = 0x40;
short ACC_TRANSIENT = 0x80;
short ACC_NATIVE = 0x100;
short ACC_INTERFACE = 0x200;
short ACC_ABSTRACT = 0x400;
short ACC_STRICT = 0x800;
byte REF_getField = 1;
byte REF_getStatic = 2;
byte REF_putField = 3;
byte REF_putStatic = 4;
byte REF_invokeVirtual = 5;
byte REF_invokeStatic = 6;
byte REF_invokeSpecial = 7;
byte REF_newInvokeSpecial = 8;
byte REF_invokeInterface = 9;
}
| 1,763
| 17.375
| 95
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/ClassReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/**
* This is the core class for reading class file data.
*
* <p>ClassReader performs lazy parsing, and thus most of the methods can throw an
* InvalidClassFileException.
*/
public final class ClassReader implements ClassConstants {
private final byte[] bytes;
private int[] methodOffsets;
private int[] fieldOffsets;
private ConstantPoolParser cpParser;
private int classInfoOffset;
private int attrInfoOffset;
private int interfaceCount;
/**
* Build a reader.
*
* <p>If the class file data is corrupt an exception might not be thrown immediately. Instead an
* exception might be thrown later, during the execution of some access method. This is a
* consequence of the 'lazy parsing' performed by ClassReader.
*
* @param bytes the class file data
* @throws InvalidClassFileException the class file data is corrupt
*/
public ClassReader(byte[] bytes) throws InvalidClassFileException {
this.bytes = bytes;
parse();
}
private void checkLength(int offset, int required) throws InvalidClassFileException {
if (bytes.length < offset + required) {
throw new InvalidClassFileException(
offset,
"file truncated, expected " + required + " bytes, saw only " + (bytes.length - offset));
}
}
private void parse() throws InvalidClassFileException {
int offset = 0;
checkLength(offset, 10);
int magic = getInt(offset);
int minorVersion = getUShort(offset + 4);
int majorVersion = getUShort(offset + 6);
int constantPoolCount = getUShort(offset + 8);
offset += 10;
if (magic != MAGIC) {
throw new InvalidClassFileException(offset, "bad magic number: " + magic);
}
// Support class files up through JDK 17 (version 61)
if (majorVersion < 45 || majorVersion > 61) {
throw new InvalidClassFileException(
offset, "unknown class file version: " + majorVersion + '.' + minorVersion);
}
cpParser = new ConstantPoolParser(bytes, offset, constantPoolCount);
offset += cpParser.getRawSize();
classInfoOffset = offset;
checkLength(offset, 8);
// int accessFlags = getUShort(offset);
// int thisClass = getUShort(offset + 2);
// int superClass = getUShort(offset + 4);
interfaceCount = getUShort(offset + 6);
if (interfaceCount < 0) {
throw new InvalidClassFileException(offset, "negative interface count: " + interfaceCount);
}
offset += 8;
checkLength(offset, interfaceCount * 2);
offset += interfaceCount * 2;
checkLength(offset, 2);
int fieldCount = getUShort(offset);
if (fieldCount < 0) {
throw new InvalidClassFileException(offset, "negative field count: " + interfaceCount);
}
offset = parseFields(offset + 2, fieldCount);
checkLength(offset, 2);
int methodCount = getUShort(offset);
if (methodCount < 0) {
throw new InvalidClassFileException(offset, "negative method count: " + interfaceCount);
}
offset = parseMethods(offset + 2, methodCount);
attrInfoOffset = offset;
checkLength(offset, 2);
int attrCount = getUShort(offset);
offset = skipAttributes(offset + 2, attrCount);
if (offset != bytes.length) {
throw new InvalidClassFileException(offset, "extra data in class file");
}
}
private int skipAttributes(int offset, int count) throws InvalidClassFileException {
if (count < 0) {
throw new InvalidClassFileException(offset, "negative attribute count: " + interfaceCount);
}
for (int i = 0; i < count; i++) {
checkLength(offset, 6);
int size = getInt(offset + 2);
if (size < 0) {
throw new InvalidClassFileException(offset, "negative attribute size: " + size);
}
offset += 6;
checkLength(offset, size);
offset += size;
}
return offset;
}
private int parseFields(int offset, int count) throws InvalidClassFileException {
fieldOffsets = new int[count + 1];
for (int i = 0; i < count; i++) {
fieldOffsets[i] = offset;
checkLength(offset, 8);
offset = skipAttributes(offset + 8, getUShort(offset + 6));
}
fieldOffsets[count] = offset;
return offset;
}
private int parseMethods(int offset, int count) throws InvalidClassFileException {
methodOffsets = new int[count + 1];
for (int i = 0; i < count; i++) {
methodOffsets[i] = offset;
checkLength(offset, 8);
offset = skipAttributes(offset + 8, getUShort(offset + 6));
}
methodOffsets[count] = offset;
return offset;
}
/** @return the raw class data bytes */
public byte[] getBytes() {
return bytes;
}
/** @return the magic number at the start of the class file. */
public int getMagic() {
return getInt(0);
}
/** @return the minor version of the class file */
public int getMinorVersion() {
return getUShort(4);
}
/** @return the major version of the class file */
public int getMajorVersion() {
return getUShort(6);
}
/** @return the access flags for the class */
public int getAccessFlags() {
return getUShort(classInfoOffset);
}
/** @return the index of the constant pool entry for the class name */
public int getNameIndex() {
return getUShort(classInfoOffset + 2);
}
String getClassFromAddress(int addr) throws InvalidClassFileException {
int c = getUShort(addr);
if (c == 0) {
return null;
} else {
try {
return cpParser.getCPClass(c);
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(addr, "Invalid class constant pool index: " + c);
}
}
}
/** @return the name of the class in JVM format (e.g., java/lang/Object) */
public String getName() throws InvalidClassFileException {
String s = getClassFromAddress(classInfoOffset + 2);
if (s == null) {
throw new InvalidClassFileException(classInfoOffset + 2, "Null class name not allowed");
} else {
return s;
}
}
/** @return the constant pool index of the superclass name, or 0 if this is java.lang.Object */
public int getSuperNameIndex() {
return getUShort(classInfoOffset + 4);
}
/**
* @return the superclass name in JVM format (e.g., java/lang/Object), or null if this class is
* java.lang.Object
*/
public String getSuperName() throws InvalidClassFileException {
return getClassFromAddress(classInfoOffset + 4);
}
/** @return the number of interfaces this class implements */
public int getInterfaceCount() {
return interfaceCount;
}
private void verifyInterfaceIndex(int i) {
if (i < 0 || i >= interfaceCount) {
throw new IllegalArgumentException("Invalid interface index: " + i);
}
}
/** @return the constant pool index of the name of the i'th implemented interface */
public int getInterfaceNameIndex(int i) {
verifyInterfaceIndex(i);
return getUShort(classInfoOffset + 8 + 2 * i);
}
/** @return an array of the constant pool indices for the names of the implemented interfaces */
public int[] getInterfaceNameIndices() {
int[] indices = new int[interfaceCount];
for (int i = 0; i < interfaceCount; i++) {
indices[i] = getUShort(classInfoOffset + 8 + 2 * i);
}
return indices;
}
/** @return the name of the i'th implemented interface */
public String getInterfaceName(int i) throws InvalidClassFileException {
verifyInterfaceIndex(i);
String s = getClassFromAddress(classInfoOffset + 8 + 2 * i);
if (s == null) {
throw new InvalidClassFileException(
classInfoOffset + 8 + 2 * i, "Null interface name not allowed");
} else {
return s;
}
}
/** @return an array of the names of the implemented interfaces */
public String[] getInterfaceNames() throws InvalidClassFileException {
String[] names = new String[interfaceCount];
for (int i = 0; i < interfaceCount; i++) {
String s = getClassFromAddress(classInfoOffset + 8 + 2 * i);
if (s == null) {
throw new InvalidClassFileException(
classInfoOffset + 8 + 2 * i, "Null interface name not allowed");
}
names[i] = s;
}
return names;
}
/**
* This method allows direct read-only access to the constant pool for the class.
*
* @return the constant pool for the class
*/
public ConstantPoolParser getCP() {
return cpParser;
}
/** @return the signed 32-bit value at offset i in the class data */
public int getInt(int i) {
return (bytes[i] << 24)
+ ((bytes[i + 1] & 0xFF) << 16)
+ ((bytes[i + 2] & 0xFF) << 8)
+ (bytes[i + 3] & 0xFF);
}
/** @return the unsigned 16-bit value at offset i in the class data */
public int getUShort(int i) {
return ((bytes[i] & 0xFF) << 8) + (bytes[i + 1] & 0xFF);
}
/** @return the signed 16-bit value at offset i in the class data */
public int getShort(int i) {
return (bytes[i] << 8) + (bytes[i + 1] & 0xFF);
}
/** @return the signed 8-bit value at offset i in the class data */
public byte getByte(int i) {
return bytes[i];
}
/** @return the unsigned 8-bit value at offset i in the class data */
public int getUnsignedByte(int i) {
return bytes[i] & 0xff;
}
/** @return the number of fields in the class */
public int getFieldCount() {
return fieldOffsets.length - 1;
}
private void verifyFieldIndex(int f) {
if (f < 0 || f >= fieldOffsets.length - 1) {
throw new IllegalArgumentException("Invalid field index: " + f);
}
}
/** @return the access flags for the f'th field */
public int getFieldAccessFlags(int f) {
verifyFieldIndex(f);
return getUShort(fieldOffsets[f]);
}
String getUtf8FromAddress(int addr) throws InvalidClassFileException {
int s = getUShort(addr);
if (s == 0) {
return null;
} else {
try {
return cpParser.getCPUtf8(s);
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(addr, "Invalid Utf8 constant pool index: " + s);
}
}
}
/** @return the name of the f'th field */
public String getFieldName(int f) throws InvalidClassFileException {
verifyFieldIndex(f);
return getUtf8FromAddress(fieldOffsets[f] + 2);
}
/** @return the type of the f'th field, in JVM format (e.g., I, Z, java/lang/Object) */
public String getFieldType(int f) throws InvalidClassFileException {
verifyFieldIndex(f);
return getUtf8FromAddress(fieldOffsets[f] + 4);
}
/**
* @return the index of the constant pool entry for the name of the f'th field, in JVM format
* (e.g., I, Z, Ljava/lang/Object;)
*/
public int getFieldNameIndex(int f) {
verifyFieldIndex(f);
return getUShort(fieldOffsets[f] + 2);
}
/**
* @return the index of the constant pool entry for the type of the f'th field, in JVM format
* (e.g., I, Z, Ljava/lang/Object;)
*/
public int getFieldTypeIndex(int f) {
verifyFieldIndex(f);
return getUShort(fieldOffsets[f] + 4);
}
/**
* AttrIterator provides access to attributes in the class file.
*
* <p>AttrIterators can be reused for many different iterations, like this:
*
* <pre>
* AttrIterator iter = new AttrIterator();
* int fieldCount = reader.getFieldCount();
* for (int i = 0; i < fieldCount; i++) {
* reader.initFieldAttributeIterator(i, iter);
* for (; iter.isValid(); iter.advance()) {
* if (iter.getName().equals("ConstantValue")) {
* ConstantValueReader cv = new ConstantValueReader(iter);
* ...
* }
* }
* }
* </pre>
*/
public static final class AttrIterator {
ClassReader cr;
int offset;
int size;
private int remaining;
/**
* Create a blank iterator. The iterator is not valid until it is initialized by some other
* class.
*/
public AttrIterator() {}
private void setSize() {
if (remaining > 0) {
size = 6 + cr.getInt(offset + 2);
}
}
void init(ClassReader cr, int offset) {
this.cr = cr;
this.offset = offset + 2;
this.remaining = cr.getUShort(offset);
setSize();
}
void verifyValid() {
if (remaining <= 0) {
throw new IllegalArgumentException("Attempt to manipulate invalid AttrIterator");
}
}
public ClassReader getClassReader() {
verifyValid();
return cr;
}
/**
* The attribute iterator must be valid.
*
* @return the offset of the raw attribute data (including attribute header) in the class file
* data
*/
public int getRawOffset() {
verifyValid();
return offset;
}
/**
* The attribute iterator must be valid.
*
* @return the size of the raw attribute data (including attribute header) in the class file
* data
*/
public int getRawSize() {
verifyValid();
return size;
}
/**
* The attribute iterator must be valid.
*
* @return the offset of the attribute data (excluding attribute header) in the class file data
*/
public int getDataOffset() {
verifyValid();
return offset + 6;
}
/**
* The attribute iterator must be valid.
*
* @return the size of the attribute data (excluding attribute header) in the class file data
*/
public int getDataSize() {
verifyValid();
return size - 6;
}
/** @return the number of attributes left in the list, including this attribute (if valid) */
public int getRemainingAttributesCount() {
return remaining;
}
/**
* The attribute iterator must be valid.
*
* @return the constant pool index of the name of the attribute
*/
public int getNameIndex() {
verifyValid();
return cr.getUShort(offset);
}
/**
* The attribute iterator must be valid.
*
* @return the name of the attribute
*/
public String getName() throws InvalidClassFileException {
verifyValid();
String s = cr.getUtf8FromAddress(offset);
if (s == null) {
throw new InvalidClassFileException(offset, "Null attribute name");
} else {
return s;
}
}
/** @return whether this iterator is valid */
public boolean isValid() {
return remaining > 0;
}
/**
* The attribute iterator must be valid.
*
* <p>The iterator is advanced to the next attribute (which might not exist, so the iterator
* might become invalid).
*/
public void advance() {
verifyValid();
offset += size;
remaining--;
setSize();
}
}
/**
* Point iter at the list of attributes for field f.
*
* @throws IllegalArgumentException if iter is null
*/
public void initFieldAttributeIterator(int f, AttrIterator iter) {
if (iter == null) {
throw new IllegalArgumentException("iter is null");
}
verifyFieldIndex(f);
iter.init(this, fieldOffsets[f] + 6);
}
/** @return the offset of the raw class data for field f */
public int getFieldRawOffset(int f) {
verifyFieldIndex(f);
return fieldOffsets[f];
}
/** @return the size of the raw class data for field f */
public int getFieldRawSize(int f) {
verifyFieldIndex(f);
return fieldOffsets[f + 1] - fieldOffsets[f];
}
/** @return the number of methods in the class */
public int getMethodCount() {
return methodOffsets.length - 1;
}
private void verifyMethodIndex(int m) {
if (m < 0 || m >= methodOffsets.length - 1) {
throw new IllegalArgumentException("Invalid method index: " + m);
}
}
/** @return the offset of the raw class data for method m */
public int getMethodRawOffset(int m) {
verifyMethodIndex(m);
return methodOffsets[m];
}
/** @return the size of the raw class data for method m */
public int getMethodRawSize(int m) {
verifyMethodIndex(m);
return methodOffsets[m + 1] - methodOffsets[m];
}
/** @return the access flags for method m */
public int getMethodAccessFlags(int m) {
verifyMethodIndex(m);
return getUShort(methodOffsets[m]);
}
/** @return the name of method m */
public String getMethodName(int m) throws InvalidClassFileException {
verifyMethodIndex(m);
return getUtf8FromAddress(methodOffsets[m] + 2);
}
/** @return the method descriptor of method m in JVM format (e.g., (ILjava/lang/Object;)V ) */
public String getMethodType(int m) throws InvalidClassFileException {
verifyMethodIndex(m);
return getUtf8FromAddress(methodOffsets[m] + 4);
}
/** @return the constant pool index of the name of method m */
public int getMethodNameIndex(int m) {
verifyMethodIndex(m);
return getUShort(methodOffsets[m] + 2);
}
/** @return the constant pool index of the method descriptor of method m */
public int getMethodTypeIndex(int m) {
verifyMethodIndex(m);
return getUShort(methodOffsets[m] + 4);
}
/**
* Point iter at the list of attributes for method m.
*
* @throws IllegalArgumentException if iter is null
*/
public void initMethodAttributeIterator(int m, AttrIterator iter) {
if (iter == null) {
throw new IllegalArgumentException("iter is null");
}
verifyMethodIndex(m);
iter.init(this, methodOffsets[m] + 6);
}
/**
* Point iter at the list of attributes for the class.
*
* @throws IllegalArgumentException if iter is null
*/
public void initClassAttributeIterator(AttrIterator iter) {
if (iter == null) {
throw new IllegalArgumentException("iter is null");
}
iter.init(this, attrInfoOffset);
}
}
| 18,121
| 28.088283
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/ClassWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser.ReferenceToken;
import java.util.ArrayList;
import java.util.HashMap;
/** This class formats and writes class data into JVM format. */
public class ClassWriter implements ClassConstants {
// input
private int majorVersion = 46;
private int minorVersion = 0;
private ConstantPoolParser rawCP;
private HashMap<Object, Integer> cachedCPEntries = new HashMap<>(1);
private final ArrayList<Object> newCPEntries = new ArrayList<>(1);
private int nextCPIndex = 1;
private final ArrayList<Element> fields = new ArrayList<>(1);
private final ArrayList<Element> methods = new ArrayList<>(1);
private final ArrayList<Element> classAttributes = new ArrayList<>(1);
private int thisClass;
private int superClass;
private int[] superInterfaces;
private int accessFlags;
private boolean forceAddCPEntries = false;
// output
private byte[] buf;
private int bufLen;
/**
* Create a blank ClassWriter with no methods, fields, or attributes, an empty constant pool, no
* super class, no implemented interfaces, no name, majorVersion 46, and minorVersion 0.
*/
public ClassWriter() {}
/**
* Set the class file format major version. You probably don't want to use this unless you really
* know what you are doing.
*/
public void setMajorVersion(int major) {
if (major < 0 || major > 0xFFFF) {
throw new IllegalArgumentException("Major version out of range: " + major);
}
majorVersion = major;
}
/**
* Set the class file format minor version. You probably don't want to use this unless you really
* know what you are doing.
*/
public void setMinorVersion(int minor) {
if (minor < 0 || minor > 0xFFFF) {
throw new IllegalArgumentException("Major version out of range: " + minor);
}
minorVersion = minor;
}
abstract static class CWItem {
abstract byte getType();
}
public static class CWStringItem extends CWItem {
private final String s;
private final byte type;
public CWStringItem(String s, byte type) {
this.s = s;
this.type = type;
}
@Override
public boolean equals(Object o) {
return o != null
&& o.getClass().equals(getClass())
&& ((CWStringItem) o).type == type
&& ((CWStringItem) o).s.equals(s);
}
@Override
public int hashCode() {
return s.hashCode() + (3901 * type);
}
@Override
byte getType() {
return type;
}
}
static class CWRef extends CWItem {
protected final String c;
protected final String n;
protected final String t;
private final byte type;
CWRef(byte type, String c, String n, String t) {
this.type = type;
this.c = c;
this.n = n;
this.t = t;
}
@Override
public boolean equals(Object o) {
if (o.getClass().equals(getClass())) {
CWRef r = (CWRef) o;
return r.type == type && r.c.equals(c) && r.n.equals(n) && r.t.equals(t);
} else {
return false;
}
}
@Override
public int hashCode() {
return type + (c.hashCode() << 5) + (n.hashCode() << 3) + t.hashCode();
}
@Override
byte getType() {
return type;
}
}
static class CWHandle extends CWRef {
private final byte kind;
CWHandle(byte type, byte kind, String c, String n, String t) {
super(type, c, n, t);
this.kind = kind;
}
@Override
public int hashCode() {
return super.hashCode() * kind;
}
@Override
public boolean equals(Object o) {
return super.equals(o) && ((CWHandle) o).kind == kind;
}
public byte getKind() {
return kind;
}
}
static class CWNAT extends CWItem {
private final String n;
private final String t;
CWNAT(String n, String t) {
this.n = n;
this.t = t;
}
@Override
public boolean equals(Object o) {
if (o instanceof CWNAT) {
CWNAT r = (CWNAT) o;
return r.n.equals(n) && r.t.equals(t);
} else {
return false;
}
}
@Override
public int hashCode() {
return (n.hashCode() << 3) + t.hashCode();
}
@Override
byte getType() {
return CONSTANT_NameAndType;
}
}
static class CWInvokeDynamic extends CWItem {
private final BootstrapMethod b;
private final String n;
private final String t;
CWInvokeDynamic(BootstrapMethod b, String n, String t) {
this.b = b;
this.n = n;
this.t = t;
}
@Override
public boolean equals(Object o) {
if (o instanceof CWInvokeDynamic) {
CWInvokeDynamic r = (CWInvokeDynamic) o;
return r.b.equals(b) && r.n.equals(n) && r.t.equals(t);
} else {
return false;
}
}
@Override
public int hashCode() {
return (b.hashCode() << 10) + (n.hashCode() << 3) + t.hashCode();
}
@Override
byte getType() {
return CONSTANT_InvokeDynamic;
}
}
/**
* Copy a constant pool from some ClassReader into this class. This must be done before any
* entries are allocated in this ClassWriter's constant pool, and it can only be done once. If and
* only if this is done, it is safe to copy "raw" fields, methods and attributes from the
* ClassReader into this class, because the constant pool references in those fields, methods and
* attributes are guaranteed to point to the same constant pool items in this new class.
*
* @param cacheEntries records whether to parse the raw constant pool completely so that if new
* entries are required which are the same as entries already in the raw pool, the existing
* entries in the raw pool are used instead. Setting this to 'true' produces smaller constant
* pools but may slow down performance because the raw pool must be completely parsed
*/
public void setRawCP(ConstantPoolParser cp, boolean cacheEntries)
throws InvalidClassFileException, IllegalArgumentException {
if (cp == null) {
throw new IllegalArgumentException();
}
if (rawCP != null) {
throw new IllegalArgumentException("Cannot set raw constant pool twice");
}
if (nextCPIndex != 1) {
throw new IllegalArgumentException(
"Cannot set raw constant pool after allocating new entries");
}
rawCP = cp;
nextCPIndex = cp.getItemCount();
if (cacheEntries) {
for (int i = 1; i < nextCPIndex; i++) {
byte t = cp.getItemType(i);
switch (t) {
case CONSTANT_String:
cachedCPEntries.put(new CWStringItem(cp.getCPString(i), CONSTANT_String), i);
break;
case CONSTANT_Class:
cachedCPEntries.put(new CWStringItem(cp.getCPClass(i), CONSTANT_Class), i);
break;
case CONSTANT_MethodType:
cachedCPEntries.put(new CWStringItem(cp.getCPMethodType(i), CONSTANT_MethodType), i);
break;
case CONSTANT_MethodHandle:
case CONSTANT_FieldRef:
case CONSTANT_InterfaceMethodRef:
case CONSTANT_MethodRef:
cachedCPEntries.put(
new CWRef(t, cp.getCPRefClass(i), cp.getCPRefName(i), cp.getCPRefType(i)), i);
break;
case CONSTANT_NameAndType:
cachedCPEntries.put(new CWNAT(cp.getCPNATName(i), cp.getCPNATType(i)), i);
break;
case CONSTANT_InvokeDynamic:
cachedCPEntries.put(
new CWInvokeDynamic(
cp.getCPDynBootstrap(i), cp.getCPDynName(i), cp.getCPDynType(i)),
i);
break;
case CONSTANT_Integer:
cachedCPEntries.put(cp.getCPInt(i), i);
break;
case CONSTANT_Float:
cachedCPEntries.put(cp.getCPFloat(i), i);
break;
case CONSTANT_Long:
cachedCPEntries.put(cp.getCPLong(i), i);
break;
case CONSTANT_Double:
cachedCPEntries.put(cp.getCPDouble(i), i);
break;
case CONSTANT_Utf8:
cachedCPEntries.put(cp.getCPUtf8(i), i);
break;
default:
throw new UnsupportedOperationException(
String.format("unexpected constant-pool item type %s", t));
}
}
}
}
/**
* @param force true iff you want the addCP methods to always create a new constant pool entry and
* never reuse an existing constant pool entry
*/
public void setForceAddCPEntries(boolean force) {
forceAddCPEntries = force;
}
protected int addCPEntry(Object o, int size) {
if (cachedCPEntries == null) {
throw new IllegalArgumentException(
"Cannot add a new constant pool entry during makeBytes() processing!");
}
Integer i = forceAddCPEntries ? null : cachedCPEntries.get(o);
if (i != null) {
return i;
} else {
int index = nextCPIndex;
nextCPIndex += size;
i = index;
cachedCPEntries.put(o, i);
newCPEntries.add(o);
if (nextCPIndex > 0xFFFF) {
throw new IllegalArgumentException("Constant pool item count exceeded");
}
return index;
}
}
/**
* Add a Utf8 string to the constant pool if necessary.
*
* @return the index of a constant pool item with the right value
*/
public int addCPUtf8(String s) {
return addCPEntry(s, 1);
}
/**
* Add an Integer to the constant pool if necessary.
*
* @return the index of a constant pool item with the right value
*/
public int addCPInt(int i) {
return addCPEntry(i, 1);
}
/**
* Add a Float to the constant pool if necessary.
*
* @return the index of a constant pool item with the right value
*/
public int addCPFloat(float f) {
return addCPEntry(f, 1);
}
/**
* Add a Long to the constant pool if necessary.
*
* @return the index of a constant pool item with the right value
*/
public int addCPLong(long l) {
return addCPEntry(l, 2);
}
/**
* Add a Double to the constant pool if necessary.
*
* @return the index of a constant pool item with the right value
*/
public int addCPDouble(double d) {
return addCPEntry(d, 2);
}
private int addCPString(String s, byte type) {
if (s == null) {
throw new IllegalArgumentException("null s: " + s);
}
return addCPEntry(new CWStringItem(s, type), 1);
}
public int addCPMethodHandle(ReferenceToken c) {
if (c == null) {
throw new IllegalArgumentException("null c: " + c);
}
return addCPEntry(
new CWHandle(
CONSTANT_MethodHandle,
c.getKind(),
c.getClassName(),
c.getElementName(),
c.getDescriptor()),
1);
}
/**
* Add a String to the constant pool if necessary.
*
* @return the index of a constant pool item with the right value
*/
public int addCPString(String s) {
return addCPString(s, CONSTANT_String);
}
/**
* Add a Class to the constant pool if necessary.
*
* @param s the class name, in JVM format (e.g., java/lang/Object)
* @return the index of a constant pool item with the right value
*/
public int addCPClass(String s) {
return addCPString(s, CONSTANT_Class);
}
/**
* Add a Class to the constant pool if necessary.
*
* @param s the class name, in JVM format (e.g., java/lang/Object)
* @return the index of a constant pool item with the right value
*/
public int addCPMethodType(String s) {
return addCPString(s, CONSTANT_MethodType);
}
/**
* Add a FieldRef to the constant pool if necessary.
*
* @param c the class name, in JVM format (e.g., java/lang/Object)
* @param n the field name
* @param t the field type, in JVM format (e.g., I, Z, or Ljava/lang/Object;)
* @return the index of a constant pool item with the right value
*/
public int addCPFieldRef(String c, String n, String t) {
return addCPEntry(new CWRef(CONSTANT_FieldRef, c, n, t), 1);
}
/**
* Add a MethodRef to the constant pool if necessary.
*
* @param c the class name, in JVM format (e.g., java/lang/Object)
* @param n the method name
* @param t the method type, in JVM format (e.g., V(ILjava/lang/Object;) )
* @return the index of a constant pool item with the right value
*/
public int addCPMethodRef(String c, String n, String t) {
return addCPEntry(new CWRef(CONSTANT_MethodRef, c, n, t), 1);
}
/**
* Add an InterfaceMethodRef to the constant pool if necessary.
*
* @param c the class name, in JVM format (e.g., java/lang/Object)
* @param n the field name
* @param t the method type, in JVM format (e.g., V(ILjava/lang/Object;) )
* @return the index of a constant pool item with the right value
*/
public int addCPInterfaceMethodRef(String c, String n, String t) {
return addCPEntry(new CWRef(CONSTANT_InterfaceMethodRef, c, n, t), 1);
}
/**
* Add a NameAndType to the constant pool if necessary.
*
* @param n the name
* @param t the type, in JVM format
* @return the index of a constant pool item with the right value
*/
public int addCPNAT(String n, String t) {
return addCPEntry(new CWNAT(n, t), 1);
}
/**
* Add an InvokeDynamic to the constant pool if necessary.
*
* @param n the name
* @param t the type, in JVM format
* @return the index of a constant pool item with the right value
*/
public int addCPInvokeDynamic(BootstrapMethod b, String n, String t) {
return addCPEntry(new CWInvokeDynamic(b, n, t), 1);
}
/** Set the access flags for the class. */
public void setAccessFlags(int f) {
if (f < 0 || f > 0xFFFF) {
throw new IllegalArgumentException("Access flags out of range: " + f);
}
accessFlags = f;
}
/** Set the constant pool index for the name of the class. */
public void setNameIndex(int c) throws IllegalArgumentException {
if (c < 1 || c > 0xFFFF) {
throw new IllegalArgumentException("Class name index out of range: " + c);
}
thisClass = c;
}
/** Set the constant pool index for the name of the superclass. */
public void setSuperNameIndex(int c) {
if (c < 0 || c > 0xFFFF) {
throw new IllegalArgumentException("Superclass name index out of range: " + c);
}
superClass = c;
}
/** Set the constant pool indices for the names of the implemented interfaces. */
public void setInterfaceNameIndices(int[] ifaces) {
if (ifaces != null) {
if (ifaces.length > 0xFFFF) {
throw new IllegalArgumentException("Too many interfaces implemented: " + ifaces.length);
}
for (int c : ifaces) {
if (c < 1 || c > 0xFFFF) {
throw new IllegalArgumentException("Interface name index out of range: " + c);
}
}
}
superInterfaces = ifaces;
}
/** Set the name of the class. */
public void setName(String c) {
setNameIndex(addCPClass(c));
}
/**
* Set the name of the superclass; if c is null, then there is no superclass (this must be
* java/lang/Object).
*/
public void setSuperName(String c) {
setSuperNameIndex(c == null ? 0 : addCPClass(c));
}
/** Set the names of the implemented interfaces. */
public void setInterfaceNames(String[] ifaces) {
if (ifaces == null) {
setInterfaceNameIndices((int[]) null);
} else {
int[] ifs = new int[ifaces.length];
for (int i = 0; i < ifaces.length; i++) {
ifs[i] = addCPClass(ifaces[i]);
}
setInterfaceNameIndices(ifs);
}
}
/**
* An Element is an object that can be serialized into a byte buffer. Serialization via 'copyInto'
* is performed when the user calls makeBytes() on the ClassWriter. At this time no new constant
* pool items can be allocated, so any item indices that need to be emitted must be allocated
* earlier.
*/
public abstract static class Element {
public Element() {}
/** @return the number of bytes that will be generated. */
public abstract int getSize();
/**
* Copy the bytes into 'buf' at offset 'offset'.
*
* @return the number of bytes copies, which must be equal to getSize()
*/
public abstract int copyInto(byte[] buf, int offset);
}
/** A RawElement is an Element that is already available as some chunk of a byte buffer. */
public static final class RawElement extends Element {
private final byte[] buf;
private final int offset;
private final int len;
/** Create an Element for the 'len' bytes in 'buf' at offset 'offset'. */
public RawElement(byte[] buf, int offset, int len) {
this.buf = buf;
this.offset = offset;
this.len = len;
}
@Override
public int getSize() {
return len;
}
@Override
public int copyInto(byte[] dest, int destOffset) {
System.arraycopy(buf, offset, dest, destOffset, len);
return destOffset + len;
}
}
/**
* Add a method to the class, the method data given as "raw" bytes (probably obtained from a
* ClassReader).
*/
public void addRawMethod(Element e) {
methods.add(e);
}
/**
* Add a field to the class, the field data given as "raw" bytes (probably obtained from a
* ClassReader).
*/
public void addRawField(Element e) {
fields.add(e);
}
/**
* Add a method to the class.
*
* @param access the access flags
* @param name the method name
* @param type the method type in JVM format (e.g., V(ILjava/lang/Object;) )
* @param attributes the attributes in raw form, one Element per attribute
*/
public void addMethod(int access, String name, String type, Element[] attributes) {
addMethod(access, addCPUtf8(name), addCPUtf8(type), attributes);
}
/**
* Add a field to the class.
*
* @param access the access flags
* @param name the field name
* @param type the field type in JVM format (e.g., I, Z, Ljava/lang/Object;)
* @param attributes the attributes in raw form, one Element per attribute
*/
public void addField(int access, String name, String type, Element[] attributes) {
addField(access, addCPUtf8(name), addCPUtf8(type), attributes);
}
static final class MemberElement extends Element {
private final int access;
private final int name;
private final int type;
private final Element[] attributes;
public MemberElement(int access, int name, int type, Element[] attributes) {
if (access < 0 || access > 0xFFFF) {
throw new IllegalArgumentException("Access flags out of range: " + access);
}
if (name < 1 || name > 0xFFFF) {
throw new IllegalArgumentException("Name constant pool index out of range: " + name);
}
if (type < 1 || type > 0xFFFF) {
throw new IllegalArgumentException("Type constant pool index out of range: " + name);
}
if (attributes == null) {
throw new IllegalArgumentException("Atrtributes are null");
}
if (attributes.length > 0xFFFF) {
throw new IllegalArgumentException("Too many attributes: " + attributes.length);
}
this.access = access;
this.name = name;
this.type = type;
this.attributes = attributes;
}
@Override
public int getSize() {
int size = 8;
if (attributes != null) {
for (Element attribute : attributes) {
size += attribute.getSize();
}
}
return size;
}
@Override
public int copyInto(byte[] buf, int offset) {
setUShort(buf, offset, access);
setUShort(buf, offset + 2, name);
setUShort(buf, offset + 4, type);
if (attributes != null) {
setUShort(buf, offset + 6, attributes.length);
offset += 8;
for (Element attribute : attributes) {
offset = attribute.copyInto(buf, offset);
}
} else {
setUShort(buf, offset + 6, 0);
offset += 8;
}
return offset;
}
}
/**
* Add a method to the class.
*
* @param access the access flags
* @param name the constant pool index of the method name
* @param type the constant pool index of the method type in JVM format (e.g.,
* V(ILjava/lang/Object;) )
* @param attributes the attributes in raw form, one Element per attribute
*/
public void addMethod(int access, int name, int type, Element[] attributes) {
// int idx=methods.size()-2;
// if (idx<0) idx=0;
// methods.add(0,new MemberElement(access, name, type, attributes));
methods.add(new MemberElement(access, name, type, attributes));
if (methods.size() > 0xFFFF) {
throw new IllegalArgumentException("Too many methods");
}
}
/**
* Add a field to the class.
*
* @param access the access flags
* @param name the constant pool index of the field name
* @param type the constant pool index of the field type in JVM format (e.g., I, Z,
* Ljava/lang/Object;)
* @param attributes the attributes in raw form, one Element per attribute
*/
public void addField(int access, int name, int type, Element[] attributes) {
fields.add(new MemberElement(access, name, type, attributes));
if (fields.size() > 0xFFFF) {
throw new IllegalArgumentException("Too many fields");
}
}
/**
* Add an atttribute to the class.
*
* @param attribute the attribute in raw form
*/
public void addClassAttribute(Element attribute) {
classAttributes.add(attribute);
if (classAttributes.size() > 0xFFFF) {
throw new IllegalArgumentException("Too many class attributes: " + classAttributes.size());
}
}
private int reserveBuf(int size) {
if (buf == null) {
buf = new byte[size];
} else if (bufLen + size > buf.length) {
byte[] newBuf = new byte[Math.max(buf.length * 2, bufLen + size)];
System.arraycopy(buf, 0, newBuf, 0, bufLen);
buf = newBuf;
}
int offset = bufLen;
bufLen += size;
return offset;
}
private void emitElement(Element e) {
int size = e.getSize();
int offset = reserveBuf(size);
int finalOffset = e.copyInto(buf, offset);
if (finalOffset - offset != size) {
throw new Error(
"Element failed to output the promised bytes: promised "
+ size
+ ", got "
+ (finalOffset - offset));
}
}
private static final char[] noChars = new char[0];
private void emitConstantPool() {
if (rawCP != null) {
int len = rawCP.getRawSize();
int offset = reserveBuf(len);
System.arraycopy(rawCP.getRawBytes(), rawCP.getRawOffset(), buf, offset, len);
}
char[] chars = noChars;
// BE CAREFUL: the newCPEntries array grows during this loop.
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < newCPEntries.size(); i++) {
Object o = newCPEntries.get(i);
if (o instanceof CWItem) {
CWItem item = (CWItem) o;
byte t = item.getType();
int offset;
switch (t) {
case CONSTANT_Class:
case CONSTANT_String:
case CONSTANT_MethodType:
offset = reserveBuf(3);
setUShort(buf, offset + 1, addCPUtf8(((CWStringItem) item).s));
break;
case CONSTANT_NameAndType:
{
offset = reserveBuf(5);
CWNAT nat = (CWNAT) item;
setUShort(buf, offset + 1, addCPUtf8(nat.n));
setUShort(buf, offset + 3, addCPUtf8(nat.t));
break;
}
case CONSTANT_InvokeDynamic:
{
offset = reserveBuf(5);
CWInvokeDynamic inv = (CWInvokeDynamic) item;
setUShort(buf, offset + 1, inv.b.getIndexInClassFile());
setUShort(buf, offset + 3, addCPNAT(inv.n, inv.t));
break;
}
case CONSTANT_MethodHandle:
{
offset = reserveBuf(4);
CWHandle handle = (CWHandle) item;
final byte kind = handle.getKind();
setUByte(buf, offset + 1, kind);
switch (kind) {
case REF_getStatic:
case REF_getField:
case REF_putField:
case REF_putStatic:
{
int x = addCPFieldRef(handle.c, handle.n, handle.t);
setUShort(buf, offset + 2, x);
break;
}
case REF_invokeVirtual:
case REF_newInvokeSpecial:
case REF_invokeSpecial:
case REF_invokeStatic:
{
int x = addCPMethodRef(handle.c, handle.n, handle.t);
setUShort(buf, offset + 2, x);
break;
}
case REF_invokeInterface:
{
int x = addCPInterfaceMethodRef(handle.c, handle.n, handle.t);
setUShort(buf, offset + 2, x);
break;
}
default:
throw new UnsupportedOperationException(
String.format("unexpected ref kind %s", kind));
}
break;
}
case CONSTANT_MethodRef:
case CONSTANT_FieldRef:
case CONSTANT_InterfaceMethodRef:
{
offset = reserveBuf(5);
CWRef ref = (CWRef) item;
setUShort(buf, offset + 1, addCPClass(ref.c));
setUShort(buf, offset + 3, addCPNAT(ref.n, ref.t));
break;
}
default:
throw new Error("Invalid type: " + t);
}
buf[offset] = t;
} else {
if (o instanceof String) {
String s = (String) o;
int slen = s.length();
if (chars.length < slen) {
chars = new char[slen];
}
s.getChars(0, slen, chars, 0);
int offset = reserveBuf(3);
buf[offset] = CONSTANT_Utf8;
int maxBytes = slen * 3;
int p = reserveBuf(maxBytes); // worst case reservation
for (int j = 0; j < slen; j++) {
char ch = chars[j];
if (ch == 0) {
setUShort(buf, p, 0xC080);
p += 2;
} else if (ch < 0x80) {
buf[p] = (byte) ch;
p += 1;
} else if (ch < 0x800) {
buf[p] = (byte) ((ch >> 6) | 0xC0);
buf[p + 1] = (byte) ((ch & 0x3F) | 0x80);
p += 2;
} else {
buf[p] = (byte) ((ch >> 12) | 0xE0);
buf[p + 1] = (byte) (((ch >> 6) & 0x3F) | 0x80);
buf[p + 2] = (byte) ((ch & 0x3F) | 0x80);
p += 3;
}
}
int bytes = p - (offset + 3);
reserveBuf(bytes - maxBytes); // negative reservation to push back buf
// size
if (bytes > 0xFFFF) {
throw new IllegalArgumentException("String too long: " + bytes + " bytes");
}
setUShort(buf, offset + 1, bytes);
} else if (o instanceof Integer) {
int offset = reserveBuf(5);
buf[offset] = CONSTANT_Integer;
setInt(buf, offset + 1, (Integer) o);
} else if (o instanceof Long) {
int offset = reserveBuf(9);
buf[offset] = CONSTANT_Long;
setLong(buf, offset + 1, (Long) o);
} else if (o instanceof Float) {
int offset = reserveBuf(5);
buf[offset] = CONSTANT_Float;
setFloat(buf, offset + 1, (Float) o);
} else if (o instanceof Double) {
int offset = reserveBuf(9);
buf[offset] = CONSTANT_Double;
setDouble(buf, offset + 1, (Double) o);
}
}
}
}
/**
* After you've added everything you need to the class, call this method to generate the actual
* class file data. This can only be called once.
*/
public byte[] makeBytes() throws IllegalArgumentException {
if (buf != null) {
throw new IllegalArgumentException("Can't call makeBytes() twice");
}
if (thisClass == 0) {
throw new IllegalArgumentException("No class name set");
}
reserveBuf(10);
setInt(buf, 0, MAGIC);
setUShort(buf, 4, minorVersion);
setUShort(buf, 6, majorVersion);
emitConstantPool();
// The constant pool can grow during emmission, so store the size last
setUShort(buf, 8, nextCPIndex);
// No new constant pool entries can be allocated; make sure we
// catch any such error by client code
cachedCPEntries = null;
int offset = reserveBuf(8);
setUShort(buf, offset, accessFlags);
setUShort(buf, offset + 2, thisClass);
setUShort(buf, offset + 4, superClass);
if (superInterfaces != null) {
setUShort(buf, offset + 6, superInterfaces.length);
reserveBuf(superInterfaces.length * 2);
for (int i = 0; i < superInterfaces.length; i++) {
setUShort(buf, offset + 8 + i * 2, superInterfaces[i]);
}
} else {
setUShort(buf, offset + 6, 0);
}
offset = reserveBuf(2);
int numFields = fields.size();
setUShort(buf, offset, numFields);
for (Element field : fields) {
emitElement(field);
}
offset = reserveBuf(2);
int numMethods = methods.size();
// Xiangyu, debug
// System.out.println("numMethods="+numMethods);
setUShort(buf, offset, numMethods);
for (Element method : methods) {
emitElement(method);
}
offset = reserveBuf(2);
int numAttrs = classAttributes.size();
setUShort(buf, offset, numAttrs);
for (Element classAttribute : classAttributes) {
emitElement(classAttribute);
}
if (buf.length == bufLen) {
return buf;
} else {
byte[] b = new byte[bufLen];
System.arraycopy(buf, 0, b, 0, bufLen);
return b;
}
}
/**
* Set the byte at offset 'offset' in 'buf' to the unsigned 8-bit value in v.
*
* @throws IllegalArgumentException if buf is null
*/
public static void setUByte(byte[] buf, int offset, int v) throws IllegalArgumentException {
if (buf == null) {
throw new IllegalArgumentException("buf is null");
}
try {
buf[offset] = (byte) v;
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid offset: " + offset, e);
}
}
/**
* Set the 4 bytes at offset 'offset' in 'buf' to the signed 32-bit value in v.
*
* @throws IllegalArgumentException if buf is null
*/
public static void setInt(byte[] buf, int offset, int v) throws IllegalArgumentException {
if (buf == null) {
throw new IllegalArgumentException("buf is null");
}
try {
buf[offset] = (byte) (v >> 24);
buf[offset + 1] = (byte) (v >> 16);
buf[offset + 2] = (byte) (v >> 8);
buf[offset + 3] = (byte) v;
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("illegal offset " + offset, e);
}
}
/** Set the 8 bytes at offset 'offset' in 'buf' to the signed 64-bit value in v. */
public static void setLong(byte[] buf, int offset, long v) throws IllegalArgumentException {
setInt(buf, offset, (int) (v >> 32));
setInt(buf, offset + 4, (int) v);
}
/** Set the 4 bytes at offset 'offset' in 'buf' to the float value in v. */
public static void setFloat(byte[] buf, int offset, float v) throws IllegalArgumentException {
setInt(buf, offset, Float.floatToIntBits(v));
}
/** Set the 8 bytes at offset 'offset' in 'buf' to the double value in v. */
public static void setDouble(byte[] buf, int offset, double v) throws IllegalArgumentException {
setLong(buf, offset, Double.doubleToRawLongBits(v));
}
/**
* Set the 2 bytes at offset 'offset' in 'buf' to the unsigned 16-bit value in v.
*
* @throws IllegalArgumentException if buf is null
*/
public static void setUShort(byte[] buf, int offset, int v) throws IllegalArgumentException {
if (buf == null) {
throw new IllegalArgumentException("buf is null");
}
if (offset < 0 || offset + 1 >= buf.length) {
throw new IllegalArgumentException("buf is too short " + buf.length + ' ' + offset);
}
try {
buf[offset] = (byte) (v >> 8);
buf[offset + 1] = (byte) v;
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid offset: " + offset, e);
}
}
}
| 33,035
| 29.41989
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/CodeReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/** This attribute reader reads Code attributes from methods. */
public final class CodeReader extends AttributeReader {
private final int codeLen;
private final int exnTableLen;
public CodeReader(ClassReader.AttrIterator iter) throws InvalidClassFileException {
super(iter, "Code");
int offset = attr + 6;
checkSize(offset, 8);
codeLen = cr.getInt(offset + 4);
offset += 8;
checkSize(offset, codeLen + 2);
offset += codeLen;
exnTableLen = cr.getUShort(offset);
offset += 2;
checkSize(offset, exnTableLen * 8 + 2);
offset += exnTableLen * 8;
int attrCount = cr.getUShort(offset);
offset += 2;
for (int i = 0; i < attrCount; i++) {
checkSize(offset, 6);
int len = cr.getInt(offset + 2);
offset += 6;
checkSize(offset, len);
offset += len;
}
}
/** @return the maximum stack size used by the code, in words */
public int getMaxStack() {
return cr.getUShort(attr + 6);
}
/** @return the maximum local variable size used by the code, in words */
public int getMaxLocals() {
return cr.getUShort(attr + 8);
}
/** @return the length of the bytecode array, in bytes */
public int getBytecodeLength() {
return codeLen;
}
/** @return the bytecode bytes */
public byte[] getBytecode() {
byte[] r = new byte[codeLen];
System.arraycopy(cr.getBytes(), attr + 14, r, 0, r.length);
return r;
}
/**
* @return the raw exception handler data, a flattened sequence of (startPC, endPC,
* catchClassIndex, catchPC) tuples
*/
public int[] getRawHandlers() {
int[] r = new int[exnTableLen * 4];
int offset = attr + 14 + codeLen + 2;
for (int i = 0; i < r.length; i++) {
r[i] = cr.getUShort(offset);
offset += 2;
}
return r;
}
/**
* Point iter at the list of attributes for this code.
*
* @throws IllegalArgumentException if iter is null
*/
public void initAttributeIterator(ClassReader.AttrIterator iter) {
if (iter == null) {
throw new IllegalArgumentException("iter is null");
}
iter.init(cr, attr + 14 + codeLen + 2 + exnTableLen * 8);
}
}
| 2,573
| 26.978261
| 85
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/CodeWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/**
* This class helps emit Code elements.
*
* <p>After constructing a CodeWriter, at least the max stack, max locals and bytecode bytes must be
* set before it can be used.
*/
public final class CodeWriter extends ClassWriter.Element {
private final int attrID;
private int maxLocals = -1;
private int maxStack = -1;
private byte[] code;
private int[] exnHandlers;
private ClassWriter.Element[] attributes;
/**
* Build an empty serializable Code attribute.
*
* @throws IllegalArgumentException if w is null
*/
public CodeWriter(ClassWriter w) {
if (w == null) {
throw new IllegalArgumentException("w is null");
}
attrID = w.addCPUtf8("Code");
}
private void verify() {
if (maxStack < 0) {
throw new IllegalArgumentException("maxStack not set");
}
if (maxLocals < 0) {
throw new IllegalArgumentException("maxLocals not set");
}
if (code == null) {
throw new IllegalArgumentException("No bytecodes set");
}
}
public int getCodeLength() throws IllegalStateException {
if (code == null) {
throw new IllegalStateException("code not initialized");
}
return code.length;
}
@Override
public int getSize() throws IllegalArgumentException {
verify();
int size = 14 + code.length + 2 + (exnHandlers == null ? 0 : exnHandlers.length) * 2 + 2;
if (attributes != null) {
for (ClassWriter.Element attribute : attributes) {
size += attribute.getSize();
}
}
return size;
}
@Override
public int copyInto(byte[] buf, int offset) throws IllegalArgumentException {
verify();
int start = offset;
ClassWriter.setUShort(buf, offset, attrID);
ClassWriter.setUShort(buf, offset + 6, maxStack);
ClassWriter.setUShort(buf, offset + 8, maxLocals);
ClassWriter.setInt(buf, offset + 10, code.length);
offset += 14;
System.arraycopy(code, 0, buf, offset, code.length);
offset += code.length;
ClassWriter.setUShort(buf, offset, (exnHandlers == null ? 0 : exnHandlers.length) / 4);
offset += 2;
if (exnHandlers != null) {
for (int exnHandler : exnHandlers) {
ClassWriter.setUShort(buf, offset, exnHandler);
offset += 2;
}
}
ClassWriter.setUShort(buf, offset, (attributes == null ? 0 : attributes.length));
offset += 2;
if (attributes != null) {
for (ClassWriter.Element attribute : attributes) {
offset = attribute.copyInto(buf, offset);
}
}
ClassWriter.setInt(buf, start + 2, offset - start - 6);
return offset;
}
/**
* Set the bytecodes for this Code attribute.
*
* @throws IllegalArgumentException if code is null
*/
public void setCode(byte[] code) throws IllegalArgumentException {
if (code == null) {
throw new IllegalArgumentException("code is null");
}
if (code.length > 0xFFFF) {
throw new IllegalArgumentException("Code array is too long: " + code.length);
}
if (code.length == 0) {
throw new IllegalArgumentException("Code array is empty");
}
this.code = code;
}
/**
* Set the raw handler data for this Code attribute.
*
* @param exnHandlers a flattened sequence of (startPC, endPC, catchClassIndex, catchPC) tuples
* @throws IllegalArgumentException if exnHandlers is null
*/
public void setRawHandlers(int[] exnHandlers) {
if (exnHandlers == null) {
throw new IllegalArgumentException("exnHandlers is null");
}
if (exnHandlers.length % 4 != 0) {
throw new IllegalArgumentException(
"Exception handlers array has bad length: " + exnHandlers.length);
}
if (exnHandlers.length / 4 > 0xFFFF) {
throw new IllegalArgumentException("Too many exception handlers: " + exnHandlers.length / 4);
}
for (int i = 0; i < exnHandlers.length; i++) {
int v = exnHandlers[i];
if (v < 0 || v > 0xFFFF) {
throw new IllegalArgumentException("Invalid exception handler entry at " + i);
}
}
this.exnHandlers = exnHandlers;
}
/** Set the maximum number of local variable space used, in words, by this Code. */
public void setMaxLocals(int maxLocals) {
this.maxLocals = maxLocals;
}
/** Set the maximum stack size, in words, in this Code. */
public void setMaxStack(int maxStack) {
this.maxStack = maxStack;
}
/** Set the attributes of this Code. */
public void setAttributes(ClassWriter.Element[] attributes) {
this.attributes = attributes;
}
}
| 4,934
| 28.201183
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/ConstantPoolParser.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.ClassReader.AttrIterator;
/** A ConstantPoolParser provides read-only access to the constant pool of a class file. */
public final class ConstantPoolParser implements ClassConstants {
public static class ReferenceToken {
private final byte kind;
private final String className;
private final String elementName;
private final String descriptor;
public ReferenceToken(byte kind, String className, String elementName, String descriptor) {
this.kind = kind;
this.className = className;
this.elementName = elementName;
this.descriptor = descriptor;
}
public byte getKind() {
return kind;
}
public String getClassName() {
return className;
}
public String getElementName() {
return elementName;
}
public String getDescriptor() {
return descriptor;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((className == null) ? 0 : className.hashCode());
result = prime * result + ((descriptor == null) ? 0 : descriptor.hashCode());
result = prime * result + ((elementName == null) ? 0 : elementName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ReferenceToken other = (ReferenceToken) obj;
if (kind != other.kind) {
return false;
}
if (className == null) {
if (other.className != null) return false;
} else if (!className.equals(other.className)) return false;
if (descriptor == null) {
if (other.descriptor != null) return false;
} else if (!descriptor.equals(other.descriptor)) return false;
if (elementName == null) {
if (other.elementName != null) return false;
} else if (!elementName.equals(other.elementName)) return false;
return true;
}
}
private final byte[] bytes;
private int[] cpOffsets;
private String[] cpItems;
private BootstrapMethodsReader invokeDynamicBootstraps;
// TODO: use JVM spec limit here?
private static final int MAX_CP_ITEMS = Integer.MAX_VALUE / 4;
private BootstrapMethodsReader getBootstrapReader() throws InvalidClassFileException {
if (invokeDynamicBootstraps == null) {
ClassReader thisClass = new ClassReader(bytes);
AttrIterator attrs = new AttrIterator();
thisClass.initClassAttributeIterator(attrs);
for (; attrs.isValid(); attrs.advance()) {
if (attrs.getName().equals("BootstrapMethods")) {
invokeDynamicBootstraps = new BootstrapMethodsReader(attrs);
break;
}
}
assert invokeDynamicBootstraps != null;
}
return invokeDynamicBootstraps;
}
/**
* @param bytes the raw class file data
* @param offset the start of the constant pool data
* @param itemCount the number of items in the pool
*/
public ConstantPoolParser(byte[] bytes, int offset, int itemCount)
throws InvalidClassFileException {
this.bytes = bytes;
if (offset < 0) {
throw new IllegalArgumentException("invalid offset: " + offset);
}
if (itemCount < 0 || itemCount > MAX_CP_ITEMS) {
throw new IllegalArgumentException("invalid itemCount: " + itemCount);
}
parseConstantPool(offset, itemCount);
}
/** @return the buffer holding the raw class file data */
public byte[] getRawBytes() {
return bytes;
}
/** @return the offset of the constant pool data in the raw class file buffer */
public int getRawOffset() throws IllegalStateException {
if (cpOffsets.length < 2) {
throw new IllegalStateException();
}
return cpOffsets[1];
}
/** @return the size of the constant pool data in the raw class file buffer */
public int getRawSize() throws IllegalStateException {
if (cpOffsets.length < 2) {
throw new IllegalStateException();
}
return cpOffsets[cpOffsets.length - 1] - cpOffsets[1];
}
/** @return the number of constant pool items (maximum item index plus one) */
public int getItemCount() {
return cpOffsets.length - 1;
}
private void checkLength(int offset, int required) throws InvalidClassFileException {
if (bytes.length < offset + required) {
throw new InvalidClassFileException(
offset,
"file truncated, expected " + required + " bytes, saw only " + (bytes.length - offset));
}
}
/** @return the type of constant pool item i, or 0 if i is an unused constant pool item */
public byte getItemType(int i) throws IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0) {
return 0;
} else {
return getByte(offset);
}
}
/**
* @return the name of the Class at constant pool item i, in JVM format (e.g., java/lang/Object)
*/
public String getCPClass(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_Class) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a Class");
}
String s = cpItems[i];
if (s == null) {
try {
s = getCPUtf8(getUShort(offset + 1));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid class name at constant pool item #" + i + ": " + ex.getMessage());
}
cpItems[i] = s;
}
return s;
}
/**
* @return the name of the method at constant pool item i, in JVM format (e.g., java/lang/Object)
*/
public String getCPMethodType(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_MethodType) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a MethodType");
}
String s = cpItems[i];
if (s == null) {
try {
s = getCPUtf8(getUShort(offset + 1));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid method type at constant pool item #" + i + ": " + ex.getMessage());
}
cpItems[i] = s;
}
return s;
}
/** @return the String at constant pool item i */
public String getCPString(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_String) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a String");
}
String s = cpItems[i];
if (s == null) {
try {
s = getCPUtf8(getUShort(offset + 1));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid string at constant pool item #" + i + ": " + ex.getMessage());
}
cpItems[i] = s;
}
return s;
}
/** Does b represent the tag of a constant pool reference to an (interface) method or field? */
public static boolean isRef(byte b) {
switch (b) {
case CONSTANT_MethodRef:
case CONSTANT_FieldRef:
case CONSTANT_InterfaceMethodRef:
return true;
default:
return false;
}
}
/**
* @return the name of the class part of the FieldRef, MethodRef, or InterfaceMethodRef at
* constant pool item i
*/
public String getCPRefClass(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || !isRef(getByte(offset))) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a Ref");
}
try {
return getCPClass(getUShort(offset + 1));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid Ref class at constant pool item #" + i + ": " + ex.getMessage());
}
}
/**
* @return the name part of the FieldRef, MethodRef, or InterfaceMethodRef at constant pool item i
*/
public String getCPRefName(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || !isRef(getByte(offset))) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a Ref");
}
try {
return getCPNATName(getUShort(offset + 3));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid Ref NameAndType at constant pool item #" + i + ": " + ex.getMessage());
}
}
/**
* @return the type part of the FieldRef, MethodRef, or InterfaceMethodRef at constant pool item
* i, in JVM format (e.g., I, Z, or Ljava/lang/Object;)
*/
public String getCPRefType(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || !isRef(getByte(offset))) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a Ref");
}
try {
return getCPNATType(getUShort(offset + 3));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid Ref NameAndType at constant pool item #" + i + ": " + ex.getMessage());
}
}
/** @return the name part of the NameAndType at constant pool item i */
public String getCPNATName(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_NameAndType) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a NameAndType");
}
try {
return getCPUtf8(getUShort(offset + 1));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid NameAndType name at constant pool item #" + i + ": " + ex.getMessage());
}
}
/**
* @return the type part of the NameAndType at constant pool item i, in JVM format (e.g., I, Z, or
* Ljava/lang/Object;)
*/
public String getCPNATType(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_NameAndType) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a NameAndType");
}
try {
return getCPUtf8(getUShort(offset + 3));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid NameAndType type at constant pool item #" + i + ": " + ex.getMessage());
}
}
/**
* @return the name part of the MethodHandle at constant pool item i, in JVM format (e.g., I, Z,
* or Ljava/lang/Object;)
*/
public String getCPHandleName(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_MethodHandle) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a MethodHandle");
}
try {
return getCPRefName(getUShort(offset + 2));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid NameAndType type at constant pool item #" + i + ": " + ex.getMessage());
}
}
/**
* @return the name part of the MethodHandle at constant pool item i, in JVM format (e.g., I, Z,
* or Ljava/lang/Object;)
*/
public String getCPHandleType(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_MethodHandle) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a MethodHandle");
}
try {
return getCPRefType(getUShort(offset + 2));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid NameAndType type at constant pool item #" + i + ": " + ex.getMessage());
}
}
/**
* @return the name part of the MethodHandle at constant pool item i, in JVM format (e.g., I, Z,
* or Ljava/lang/Object;)
*/
public String getCPHandleClass(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_MethodHandle) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a MethodHandle");
}
try {
return getCPRefClass(getUShort(offset + 2));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid NameAndType type at constant pool item #" + i + ": " + ex.getMessage());
}
}
/** @return the type of the MethodHandle at constant pool item i */
public byte getCPHandleKind(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_MethodHandle) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a MethodHandle");
}
try {
return getByte(offset + 1);
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid NameAndType type at constant pool item #" + i + ": " + ex.getMessage());
}
}
/** @return the value of the Integer at constant pool item i */
public int getCPInt(int i) throws IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_Integer) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not an Integer");
}
return getInt(offset + 1);
}
/** @return the value of the Float at constant pool item i */
public float getCPFloat(int i) throws IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_Float) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a Float");
}
return getFloat(offset + 1);
}
/** @return the value of the Long at constant pool item i */
public long getCPLong(int i) throws IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_Long) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a Long");
}
return getLong(offset + 1);
}
/** @return the value of the Double at constant pool item i */
public double getCPDouble(int i) throws IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_Double) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a Double");
}
return getDouble(offset + 1);
}
/** @return the BootstrapMethodTable index of the bootstrap method for this invokedynamic */
public BootstrapMethod getCPDynBootstrap(int i)
throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_InvokeDynamic) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not an InvokeDynamic");
}
try {
int index = getUShort(offset + 1);
return getBootstrapReader().getEntry(index);
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid Ref class at constant pool item #" + i + ": " + ex.getMessage());
}
}
public String getCPDynName(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_InvokeDynamic) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not an InvokeDynamic");
}
try {
return getCPNATName(getUShort(offset + 3));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid Ref class at constant pool item #" + i + ": " + ex.getMessage());
}
}
public String getCPDynType(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_InvokeDynamic) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not an InvokeDynamic");
}
try {
return getCPNATType(getUShort(offset + 3));
} catch (IllegalArgumentException ex) {
throw new InvalidClassFileException(
offset, "Invalid Ref class at constant pool item #" + i + ": " + ex.getMessage());
}
}
private InvalidClassFileException invalidUtf8(int item, int offset) {
return new InvalidClassFileException(
offset,
"Constant pool item #"
+ item
+ " starting at "
+ cpOffsets[item]
+ ", is an invalid Java Utf8 string (byte is "
+ getByte(offset)
+ ')');
}
/** @return the value of the Utf8 string at constant pool item i */
public String getCPUtf8(int i) throws InvalidClassFileException, IllegalArgumentException {
if (i < 1 || i >= cpItems.length) {
throw new IllegalArgumentException("Constant pool item #" + i + " out of range");
}
int offset = cpOffsets[i];
if (offset == 0 || getByte(offset) != CONSTANT_Utf8) {
throw new IllegalArgumentException("Constant pool item #" + i + " is not a Utf8");
}
String s = cpItems[i];
if (s == null) {
int count = getUShort(offset + 1);
int end = count + offset + 3;
StringBuilder buf = new StringBuilder(count);
offset += 3;
while (offset < end) {
byte x = getByte(offset);
if ((x & 0x80) == 0) {
if (x == 0) {
throw invalidUtf8(i, offset);
}
buf.append((char) x);
offset++;
} else if ((x & 0xE0) == 0xC0) {
if (offset + 1 >= end) {
throw invalidUtf8(i, offset);
}
byte y = getByte(offset + 1);
if ((y & 0xC0) != 0x80) {
throw invalidUtf8(i, offset);
}
buf.append((char) (((x & 0x1F) << 6) + (y & 0x3F)));
offset += 2;
} else if ((x & 0xF0) == 0xE0) {
if (offset + 2 >= end) {
throw invalidUtf8(i, offset);
}
byte y = getByte(offset + 1);
byte z = getByte(offset + 2);
if ((y & 0xC0) != 0x80 || (z & 0xC0) != 0x80) {
throw invalidUtf8(i, offset);
}
buf.append((char) (((x & 0x0F) << 12) + ((y & 0x3F) << 6) + (z & 0x3F)));
offset += 3;
} else {
throw invalidUtf8(i, offset);
}
}
// s = buf.toString().intern(); // removed intern() call --MS
s = buf.toString();
cpItems[i] = s;
}
return s;
}
private void parseConstantPool(int offset, int itemCount) throws InvalidClassFileException {
cpOffsets = new int[itemCount + 1];
cpItems = new String[itemCount];
for (int i = 1; i < itemCount; i++) {
cpOffsets[i] = offset;
byte tag = getByte(offset);
int itemLen;
switch (tag) {
case CONSTANT_String:
case CONSTANT_Class:
case CONSTANT_MethodType:
case CONSTANT_Module:
case CONSTANT_Package:
itemLen = 2;
break;
case CONSTANT_NameAndType:
case CONSTANT_MethodRef:
case CONSTANT_FieldRef:
case CONSTANT_InterfaceMethodRef:
case CONSTANT_Integer:
case CONSTANT_Float:
case CONSTANT_InvokeDynamic:
itemLen = 4;
break;
case CONSTANT_Long:
case CONSTANT_Double:
itemLen = 8;
i++; // ick
break;
case CONSTANT_Utf8:
itemLen = 2 + getUShort(offset + 1);
break;
case CONSTANT_MethodHandle:
itemLen = 3;
break;
default:
throw new InvalidClassFileException(offset, "unknown constant pool entry type" + tag);
}
checkLength(offset, itemLen);
offset += itemLen + 1;
}
cpOffsets[itemCount] = offset;
}
private byte getByte(int i) {
return bytes[i];
}
private int getUShort(int i) {
return ((bytes[i] & 0xFF) << 8) + (bytes[i + 1] & 0xFF);
}
// private short getShort(int i) {
// return (short) ((bytes[i] << 8) + (bytes[i + 1] & 0xFF));
// }
private int getInt(int i) {
return (bytes[i] << 24)
+ ((bytes[i + 1] & 0xFF) << 16)
+ ((bytes[i + 2] & 0xFF) << 8)
+ (bytes[i + 3] & 0xFF);
}
private long getLong(int i) {
return ((long) getInt(i) << 32) + (getInt(i + 4) & 0xFFFFFFFFL);
}
private float getFloat(int i) {
return Float.intBitsToFloat(getInt(i));
}
private double getDouble(int i) {
return Double.longBitsToDouble(getLong(i));
}
}
| 24,079
| 35.047904
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/ConstantValueReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/** This class reads ConstantValue attributes. */
public final class ConstantValueReader extends AttributeReader {
/** Build a reader for the attribute 'iter'. */
public ConstantValueReader(ClassReader.AttrIterator iter) throws InvalidClassFileException {
super(iter, "ConstantValue");
checkSizeEquals(attr + 6, 2);
}
/** @return the index of the constant pool item holding the value */
public int getValueCPIndex() {
return cr.getUShort(attr + 6);
}
}
| 891
| 32.037037
| 94
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/ConstantValueWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/**
* This class builds serializable ConstantValue attributes. These attributes are associated with
* final fields.
*
* <p>After constructing a ConstantValueWriter, you must call setValueCPIndex.
*/
public final class ConstantValueWriter extends ClassWriter.Element {
private final int attrID;
private int index = -1;
private final ClassWriter w;
/**
* Build an empty writer.
*
* @throws IllegalArgumentException if w is null
*/
public ConstantValueWriter(ClassWriter w) {
if (w == null) {
throw new IllegalArgumentException("w is null");
}
this.w = w;
attrID = w.addCPUtf8("ConstantValue");
}
/** Build an writer for a 'long' constant value. */
public ConstantValueWriter(ClassWriter w, long v) {
this(w);
setLong(v);
}
/** Build an writer for an 'int' constant value. */
public ConstantValueWriter(ClassWriter w, int v) {
this(w);
setInt(v);
}
/** Build an writer for a 'float' constant value. */
public ConstantValueWriter(ClassWriter w, float v) {
this(w);
setFloat(v);
}
/** Build an writer for a 'double' constant value. */
public ConstantValueWriter(ClassWriter w, double v) {
this(w);
setDouble(v);
}
/** Build an writer for a 'String' constant value. */
public ConstantValueWriter(ClassWriter w, String v) {
this(w);
setString(v);
}
private void verify() {
if (index < 0) {
throw new IllegalArgumentException("The value's constant pool index is not set");
}
}
@Override
public int getSize() {
verify();
return 8;
}
@Override
public int copyInto(byte[] buf, int offset) throws IllegalArgumentException {
verify();
ClassWriter.setUShort(buf, offset, attrID);
ClassWriter.setInt(buf, offset + 2, 2);
ClassWriter.setUShort(buf, offset + 6, index);
return offset + 8;
}
/** Set the constant value to a long. */
public void setLong(long value) {
this.index = w.addCPLong(value);
}
/** Set the constant value to a double. */
public void setDouble(double value) {
this.index = w.addCPDouble(value);
}
/** Set the constant value to an int. */
public void setInt(int value) {
this.index = w.addCPInt(value);
}
/** Set the constant value to a float. */
public void setFloat(float value) {
this.index = w.addCPFloat(value);
}
/** Set the constant value to a String. */
public void setString(String value) {
if (value == null) {
throw new IllegalArgumentException("null value");
}
this.index = w.addCPString(value);
}
/** Set the index of the constant pool item holding the constant value. */
public void setValueCPIndex(int index) throws IllegalArgumentException {
if (index < 1 || index > 0xFFFF) {
throw new IllegalArgumentException("Invalid CP index: " + index);
}
this.index = index;
}
}
| 3,286
| 24.88189
| 96
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/ExceptionsReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import java.util.Arrays;
/** This class reads Exceptions attributes. */
public final class ExceptionsReader extends AttributeReader {
/** Build a reader for the attribute 'iter'. */
public ExceptionsReader(ClassReader.AttrIterator iter) throws InvalidClassFileException {
super(iter, "Exceptions");
checkSize(attr, 8);
int count = cr.getUShort(attr + 6);
checkSizeEquals(attr + 8, 2 * count);
}
/** @return the indices of the constant pool items for the exceptions */
public int[] getRawTable() {
int count = cr.getUShort(attr + 6);
int[] r = new int[count];
Arrays.setAll(r, i -> cr.getUShort(attr + 8 + i * 2));
return r;
}
/** @return the classes of exceptions that can be thrown by the method */
public String[] getClasses() throws InvalidClassFileException {
int count = cr.getUShort(attr + 6);
String[] r = new String[count];
ConstantPoolParser cp = cr.getCP();
for (int i = 0; i < r.length; i++) {
r[i] = cp.getCPClass(cr.getUShort(attr + 8 + i * 2));
}
return r;
}
}
| 1,471
| 31.711111
| 91
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/ExceptionsWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/** This class builds serializable Exceptions attributes. */
public final class ExceptionsWriter extends ClassWriter.Element {
private final int attrID;
private int[] table;
/**
* Build an empty writer.
*
* @throws IllegalArgumentException if w is null
*/
public ExceptionsWriter(ClassWriter w) {
if (w == null) {
throw new IllegalArgumentException("w is null");
}
attrID = w.addCPUtf8("Exceptions");
}
@Override
public int getSize() {
return table == null ? 8 : 8 + table.length * 2;
}
@Override
public int copyInto(byte[] buf, int offset) throws IllegalArgumentException {
ClassWriter.setUShort(buf, offset, attrID);
ClassWriter.setInt(buf, offset + 2, getSize() - 6);
ClassWriter.setUShort(buf, offset + 6, table == null ? 0 : table.length);
offset += 8;
if (table != null) {
for (int element : table) {
ClassWriter.setUShort(buf, offset, element);
offset += 2;
}
}
return offset;
}
/**
* Set the list of exceptions that can be thrown.
*
* @param exceptions an array of indices to constant pool Class entries
* @throws IllegalArgumentException if exceptions is null
*/
public void setRawTable(int[] exceptions) {
if (exceptions == null) {
throw new IllegalArgumentException("exceptions is null");
}
for (int exception : exceptions) {
if (exception < 1 || exception > 0xFFFF) {
throw new IllegalArgumentException("Invalid CP index: " + exception);
}
}
this.table = exceptions;
}
}
| 1,980
| 27.3
| 79
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/InnerClassesReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import java.util.Arrays;
/** This class reads InnerClasses attributes. */
public final class InnerClassesReader extends AttributeReader {
/** Build a reader for the attribute 'iter'. */
public InnerClassesReader(ClassReader.AttrIterator iter) throws InvalidClassFileException {
super(iter, "InnerClasses");
checkSize(attr, 8);
int count = cr.getUShort(attr + 6);
checkSizeEquals(attr + 8, 8 * count);
}
/** @return the raw values that make up this attribute */
public int[] getRawTable() {
int count = cr.getUShort(attr + 6);
int[] r = new int[count * 4];
Arrays.setAll(r, i -> cr.getUShort(attr + 8 + i * 2));
return r;
}
/** @return the names of inner classes this attribute holds information about. */
public String[] getInnerClasses() throws InvalidClassFileException {
int count = cr.getUShort(attr + 6);
String[] r = new String[count];
ConstantPoolParser cp = cr.getCP();
for (int i = 0; i < r.length; i++) {
r[i] = cp.getCPClass(cr.getUShort(attr + 8 + i * 8));
}
return r;
}
/**
* return the name of the outer class recorded as the enclosing class for a class named s. return
* null if not found.
*/
public String getOuterClass(String s) throws InvalidClassFileException {
String[] inner = getInnerClasses();
for (int i = 0; i < inner.length; i++) {
if (inner[i].equals(s)) {
int x = cr.getUShort(attr + 8 + i * 8 + 2);
if (x != 0) {
ConstantPoolParser cp = cr.getCP();
return cp.getCPClass(cr.getUShort(attr + 8 + i * 8 + 2));
}
}
}
return null;
}
/**
* return the mask of flags recorded in the InnerClasses attribute for a class named s. return 0
* if not found.
*/
public int getAccessFlags(String s) throws InvalidClassFileException {
String[] inner = getInnerClasses();
for (int i = 0; i < inner.length; i++) {
if (inner[i].equals(s)) {
return cr.getUShort(attr + 8 + i * 8 + 6);
}
}
return 0;
}
}
| 2,447
| 30.792208
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/InnerClassesWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/** This class builds serializable InnerClasses attributes. */
public final class InnerClassesWriter extends ClassWriter.Element {
private final int attrID;
private int[] table;
/**
* Build an empty writer.
*
* @throws IllegalArgumentException if w is null
*/
public InnerClassesWriter(ClassWriter w) {
if (w == null) {
throw new IllegalArgumentException("w is null");
}
attrID = w.addCPUtf8("InnerClasses");
}
@Override
public int getSize() {
return table == null ? 8 : 8 + table.length * 2;
}
/**
* Copy the bytes into 'buf' at offset 'offset'.
*
* @return the number of bytes copies, which must be equal to getSize()
*/
@Override
public int copyInto(byte[] buf, int offset) throws IllegalArgumentException {
ClassWriter.setUShort(buf, offset, attrID);
ClassWriter.setInt(buf, offset + 2, getSize() - 6);
ClassWriter.setUShort(buf, offset + 6, table == null ? 0 : table.length);
offset += 8;
if (table != null) {
for (int element : table) {
ClassWriter.setUShort(buf, offset, element);
offset += 2;
}
}
return offset;
}
/**
* Set the raw values that make up this attribute
*
* @throws IllegalArgumentException if classes is null
*/
public void setRawTable(int[] classes) throws NullPointerException {
if (classes == null) {
throw new IllegalArgumentException("classes is null");
}
if (classes.length % 4 != 0) {
throw new IllegalArgumentException("Invalid raw table length: " + classes.length);
}
for (int i = 0; i < classes.length; i += 4) {
if (classes[i] < 1 || classes[i] > 0xFFFF) {
throw new IllegalArgumentException("Invalid CP index: " + classes[i]);
}
if (classes[i + 1] < 0 || classes[i + 1] > 0xFFFF) {
throw new IllegalArgumentException("Invalid CP index: " + classes[i]);
}
if (classes[i + 2] < 0 || classes[i + 2] > 0xFFFF) {
throw new IllegalArgumentException("Invalid CP index: " + classes[i]);
}
}
this.table = classes;
}
}
| 2,505
| 29.192771
| 88
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/InvalidClassFileException.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/**
* This exception is thrown when we detect that the incoming class file data was not a valid class
* file.
*/
public class InvalidClassFileException extends Exception {
private static final long serialVersionUID = -6224203694783674259L;
private final int offset;
/**
* The incoming class file is invalid.
*
* @param offset the offset within the data where the invalidity was detected
* @param s the reason the data is invalid
*/
public InvalidClassFileException(int offset, String s) {
super("Class file invalid at " + offset + ": " + s);
this.offset = offset;
}
/** @return the offset within the data where the problem was detected */
public int getOffset() {
return offset;
}
}
| 1,145
| 28.384615
| 98
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/LineNumberTableReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/**
* This class reads LineNumberTable attributes.
*
* <p>Instead of constructing a LineNumberTableReader directly, consider just calling
* LineNumberTableReader.makeBytecodeToSourceMap for convenient access to aggregate line number data
* from all the LineNumberTable attributes for a given Code.
*/
public final class LineNumberTableReader extends AttributeReader {
/** Build a reader for a LineNumberTable attribute. */
public LineNumberTableReader(ClassReader.AttrIterator iter) throws InvalidClassFileException {
super(iter, "LineNumberTable");
int offset = attr + 6;
checkSize(offset, 2);
int count = cr.getUShort(offset);
offset += 2;
checkSize(offset, count * 4);
}
/** @return the raw line number table data, a flattened sequence of (startPC, lineNumber) pairs */
public int[] getRawTable() {
int count = cr.getUShort(attr + 6);
int[] r = new int[count * 2];
int offset = attr + 8;
for (int i = 0; i < r.length; i++) {
r[i] = cr.getUShort(offset);
offset += 2;
}
return r;
}
/**
* Construct a "bytecode to source" map for the given code. This method aggregates all the
* LineNumberTable attributes for the code into one handy data structure.
*
* @return an array mapping each byte of the bytecode bytes to the line number that that byte
* belongs to, or null if there is no line number data in the Code
*/
public static int[] makeBytecodeToSourceMap(CodeReader code)
throws InvalidClassFileException, IllegalArgumentException {
if (code == null) {
throw new IllegalArgumentException();
}
int[] r = null;
ClassReader cr = code.getClassReader();
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
code.initAttributeIterator(iter);
for (; iter.isValid(); iter.advance()) {
if (iter.getName().equals("LineNumberTable")) {
if (r == null) {
r = new int[code.getBytecodeLength()];
}
// check length
@SuppressWarnings("unused")
LineNumberTableReader lineNumberTableReader = new LineNumberTableReader(iter);
int attr = iter.getRawOffset();
int count = cr.getUShort(attr + 6);
int offset = attr + 8;
for (int j = 0; j < count; j++) {
int startPC = cr.getUShort(offset);
int lineNum = cr.getUShort(offset + 2);
offset += 4;
if (startPC < 0 || startPC >= r.length) {
throw new InvalidClassFileException(
offset, "Invalid bytecode offset " + startPC + " in LineNumberTable");
}
r[startPC] = lineNum;
}
}
}
if (r != null) {
// fill in gaps in the old line number map
int last = 0;
for (int i = 0; i < r.length; i++) {
int cur = r[i];
if (cur == 0) {
r[i] = last;
} else {
last = cur;
}
}
}
return r;
}
}
| 3,361
| 31.326923
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/LineNumberTableWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/** This class helps emit LineNumberTable attributes. */
public final class LineNumberTableWriter extends ClassWriter.Element {
private final int attrID;
private int[] rawTable = emptyTable;
private static final int[] emptyTable = new int[0];
/**
* Build an empty LineNumberTable.
*
* @throws IllegalArgumentException if w is null
*/
public LineNumberTableWriter(ClassWriter w) {
if (w == null) {
throw new IllegalArgumentException("w is null");
}
attrID = w.addCPUtf8("LineNumberTable");
}
/**
* Set the raw table entries. Consider calling LineNumberTableWriter.makeRawTable to build the raw
* entries.
*
* @param table a flattened sequence of (startPC, lineNumber) pairs
*/
public void setRawTable(int[] table) {
if (table == null) {
table = emptyTable;
}
if (table.length % 2 != 0) {
throw new IllegalArgumentException("Line number table has bad length: " + table.length);
}
if (table.length / 2 > 0xFFFF) {
throw new IllegalArgumentException("Too many line number table entries: " + table.length / 2);
}
for (int i = 0; i < table.length; i++) {
int v = table[i];
if (v < 0 || v > 0xFFFF) {
throw new IllegalArgumentException("Bad line number table entry at " + i + ": " + v);
}
}
rawTable = table;
}
@Override
public int getSize() {
return 8 + rawTable.length * 2;
}
@Override
public int copyInto(byte[] buf, int offset) throws IllegalArgumentException {
ClassWriter.setUShort(buf, offset, attrID);
ClassWriter.setInt(buf, offset + 2, 2 + rawTable.length * 2);
ClassWriter.setUShort(buf, offset + 6, rawTable.length / 2);
offset += 8;
for (int element : rawTable) {
ClassWriter.setUShort(buf, offset, element);
offset += 2;
}
return offset;
}
/**
* @param newLineMap an array indexed by bytecode offset, mapping each bytecode offset to its line
* number (or 0 if there is no line or it's not known)
* @return the line numbers in "raw" format, a flattened sequence of (startPC, lineNumber) pairs
* @throws IllegalArgumentException if newLineMap == null
*/
public static int[] makeRawTable(int[] newLineMap) throws IllegalArgumentException {
if (newLineMap == null) {
throw new IllegalArgumentException("newLineMap == null");
}
int rawCount = 0;
int last = -1;
for (int next : newLineMap) {
if (next != last) {
rawCount++;
}
}
int[] rawTable = new int[rawCount * 2];
last = -1;
int index = 0;
for (int i = 0; i < newLineMap.length; i++) {
int next = newLineMap[i];
if (next != last) {
rawTable[index] = i;
rawTable[index + 1] = next;
index += 2;
}
}
return rawTable;
}
}
| 3,235
| 28.418182
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/LocalVariableTableReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import java.util.Arrays;
/**
* This class reads LocalVariableTable attributes.
*
* <p>Instead of constructing a LocalVariableTable directly, consider just calling
* LocalVariableTable.makeVarMap for convenient access to aggregate local variable data from all the
* LocalVariableTable attributes for a given Code.
*/
public final class LocalVariableTableReader extends AttributeReader {
public LocalVariableTableReader(ClassReader.AttrIterator iter) throws InvalidClassFileException {
super(iter, "LocalVariableTable");
int offset = attr + 6;
checkSize(offset, 2);
int count = cr.getUShort(offset);
offset += 2;
checkSize(offset, count * 10);
}
/**
* @return the raw line number table data, a flattened sequence of (startPC, PClength, nameIndex,
* typeIndex, var) tuples
*/
public int[] getRawTable() {
int count = cr.getUShort(attr + 6);
int[] r = new int[count * 5];
int offset = attr + 8;
for (int i = 0; i < r.length; i++) {
r[i] = cr.getUShort(offset);
offset += 2;
}
return r;
}
private static int[] makeVarVector(int[] curVector, int varIndex, int nameIndex, int typeIndex) {
int[] newVector;
if (curVector == null) {
newVector = new int[(varIndex + 1) * 2];
} else {
newVector = Arrays.copyOf(curVector, Math.max(curVector.length, (varIndex + 1) * 2));
}
newVector[varIndex * 2] = nameIndex;
newVector[varIndex * 2 + 1] = typeIndex;
return newVector;
}
/**
* @return an array mapping bytecode offsets to arrays representing the local variable maps for
* each offset; a local variable map is represented as an array of localVars*2 elements,
* containing a pair (nameIndex, typeIndex) for each local variable; a pair (0,0) indicates
* there is no information for that local variable at that offset
*/
public static int[][] makeVarMap(CodeReader code)
throws InvalidClassFileException, IllegalArgumentException {
if (code == null) {
throw new IllegalArgumentException();
}
int[][] r = null;
ClassReader cr = code.getClassReader();
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
code.initAttributeIterator(iter);
for (; iter.isValid(); iter.advance()) {
if (iter.getName().equals("LocalVariableTable")) {
if (r == null) {
r = new int[code.getBytecodeLength()][];
}
// check length
@SuppressWarnings("unused")
LocalVariableTableReader localVariableTableReader = new LocalVariableTableReader(iter);
int attr = iter.getRawOffset();
int count = cr.getUShort(attr + 6);
int offset = attr + 8;
for (int j = 0; j < count; j++) {
int startPC = cr.getUShort(offset);
int length = cr.getUShort(offset + 2);
int nameIndex = cr.getUShort(offset + 4);
int typeIndex = cr.getUShort(offset + 6);
int varIndex = cr.getUShort(offset + 8);
offset += 10;
if (varIndex < 0) {
throw new InvalidClassFileException(
offset, "Invalid variable index " + varIndex + " in LocalVariableTable");
} else if (startPC < 0) {
throw new InvalidClassFileException(
offset, "Invalid startPC " + startPC + " in LocalVariableTable");
} else if (startPC + length > r.length) {
throw new InvalidClassFileException(
offset,
"Invalid startPC+length "
+ (startPC + length)
+ " > "
+ r.length
+ " in LocalVariableTable");
}
for (int k = startPC; k < startPC + length; k++) {
int[] newVector = makeVarVector(r[k], varIndex, nameIndex, typeIndex);
r[k] = newVector;
}
}
}
}
return r;
}
}
| 4,325
| 33.887097
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/LocalVariableTableWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import com.ibm.wala.shrike.shrikeBT.Compiler;
import java.util.Arrays;
/** This class helps emit LocalVariableTable attributes. */
public final class LocalVariableTableWriter extends ClassWriter.Element {
private final int attrID;
private int[] rawTable = emptyTable;
private static final int[] emptyTable = new int[0];
/**
* Create a blank LocalVariableTable.
*
* @throws IllegalArgumentException if w is null
*/
public LocalVariableTableWriter(ClassWriter w) {
if (w == null) {
throw new IllegalArgumentException("w is null");
}
attrID = w.addCPUtf8("LocalVariableTable");
}
/**
* Set the raw local variable table values. Consider using LocalVariableTableWriter.makeRawTable
* to build the raw values.
*
* @param table the raw values, a flattened sequence of (startPC, length, nameIndex, typeIndex,
* var) tuples
*/
public void setRawTable(int[] table) {
if (table == null) {
table = emptyTable;
}
if (table.length % 5 != 0) {
throw new IllegalArgumentException("Local variable table has bad length: " + table.length);
}
if (table.length / 5 > 0xFFFF) {
throw new IllegalArgumentException(
"Too many local variable table entries: " + table.length / 5);
}
for (int i = 0; i < table.length; i++) {
int v = table[i];
if (v < 0 || v > 0xFFFF) {
throw new IllegalArgumentException("Bad local variable table entry at " + i + ": " + v);
}
}
rawTable = table;
}
@Override
public int getSize() {
return 8 + rawTable.length * 2;
}
@Override
public int copyInto(byte[] buf, int offset) throws IllegalArgumentException {
ClassWriter.setUShort(buf, offset, attrID);
ClassWriter.setInt(buf, offset + 2, 2 + rawTable.length * 2);
ClassWriter.setUShort(buf, offset + 6, rawTable.length / 5);
offset += 8;
for (int element : rawTable) {
ClassWriter.setUShort(buf, offset, element);
offset += 2;
}
return offset;
}
/**
* Build a raw local variable table from a formatted variable map.
*
* @param varMap an array mapping bytecode offsets to a variable map for each offset; a variable
* map is a array of 2*localVars elements, containing a (nameIndex, typeIndex) for each local
* variable; the pair (0,0) indicates that there is no information about that local variable
* at that offset
* @throws IllegalArgumentException if varMap == null
*/
public static int[] makeRawTable(int[][] varMap, Compiler.Output output)
throws IllegalArgumentException {
if (varMap == null) {
throw new IllegalArgumentException("varMap == null");
}
try {
int varCount = 0;
for (int[] element : varMap) {
if (element != null) {
varCount = Math.max(varCount, element.length);
}
}
varCount /= 2;
int[] entries = new int[20];
int[] varEnd = new int[varCount];
Arrays.fill(varEnd, -1);
int[] lastVector = null;
int entryCount = 0;
for (int i = 0; i < varMap.length; i++) {
if (varMap[i] != lastVector) {
lastVector = varMap[i];
if (lastVector != null) {
for (int k = 0; k < lastVector.length / 2 && k < output.getMaxLocals(); k++) {
if (lastVector[k * 2] > 0 && i >= varEnd[k]) {
int entryOffset = entryCount * 5;
entryCount++;
if (entryCount * 5 > entries.length) {
entries = Arrays.copyOf(entries, entries.length * 2);
}
int nameIndex = lastVector[k * 2];
int typeIndex = lastVector[k * 2 + 1];
int end = i + 1;
while (end < varMap.length) {
if (varMap[end] == null
|| k * 2 >= varMap[end].length
|| varMap[end][k * 2] != nameIndex
|| varMap[end][k * 2 + 1] != typeIndex) {
break;
}
end++;
}
varEnd[k] = end;
entries[entryOffset] = i;
entries[entryOffset + 1] = end - i;
entries[entryOffset + 2] = nameIndex;
entries[entryOffset + 3] = typeIndex;
entries[entryOffset + 4] = k;
}
}
}
}
}
if (entryCount == 0) {
return null;
} else {
int[] r = new int[entryCount * 5];
System.arraycopy(entries, 0, r, 0, r.length);
return r;
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("malformed varMap", e);
}
}
}
| 5,153
| 31.2125
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/SignatureReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/** This class reads Signature attributes. */
public final class SignatureReader extends AttributeReader {
/** Build a reader for the attribute 'iter'. */
public SignatureReader(ClassReader.AttrIterator iter) throws InvalidClassFileException {
super(iter, "Signature");
checkSizeEquals(attr + 6, 2);
}
/** @return the index of the constant pool item holding the value */
public int getSignatureCPIndex() {
return cr.getUShort(attr + 6);
}
public String getSignature() throws InvalidClassFileException {
return cr.getCP().getCPUtf8(getSignatureCPIndex());
}
}
| 1,006
| 31.483871
| 90
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/SourceDebugExtensionReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
public class SourceDebugExtensionReader extends AttributeReader {
public SourceDebugExtensionReader(ClassReader.AttrIterator iter)
throws InvalidClassFileException {
super(iter, "SourceDebugExtension");
checkSize(attr, 6);
}
}
| 658
| 30.380952
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/SourceDebugExtensionWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import java.io.UnsupportedEncodingException;
public class SourceDebugExtensionWriter extends ClassWriter.Element {
private final int attrID;
private byte[] table;
public SourceDebugExtensionWriter(ClassWriter w) {
if (w == null) {
throw new IllegalArgumentException("w is null");
}
attrID = w.addCPUtf8("SourceDebugExtension");
}
@Override
public int getSize() {
return table == null ? 6 : 6 + table.length;
}
@Override
public int copyInto(byte[] buf, int offset) throws IllegalArgumentException {
ClassWriter.setUShort(buf, offset, attrID);
ClassWriter.setInt(buf, offset + 2, getSize() - 6);
offset += 6;
if (table != null) {
for (byte element : table) {
ClassWriter.setUByte(buf, offset, element);
offset++;
}
}
return offset;
}
public void setRawTable(byte[] sourceDebug) {
if (sourceDebug == null) {
throw new IllegalArgumentException("sourceDebug is null");
}
for (byte element : sourceDebug) {
if (element < 1) {
throw new IllegalArgumentException("Invalid CP index: " + element);
}
}
this.table = sourceDebug;
}
public void setDebugInfo(String sourceDebug) {
if (sourceDebug == null) {
throw new IllegalArgumentException("sourceDebug is null");
}
try {
byte[] bytes = sourceDebug.getBytes("UTF8");
setRawTable(bytes);
} catch (UnsupportedEncodingException e) {
System.err.println(e);
}
}
}
| 1,909
| 26.285714
| 79
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/SourceFileReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/** This class reads SourceFile attributes. */
public final class SourceFileReader extends AttributeReader {
/** Build a reader for the attribute 'iter'. */
public SourceFileReader(ClassReader.AttrIterator iter) throws InvalidClassFileException {
super(iter, "SourceFile");
checkSizeEquals(attr + 6, 2);
}
/** @return the index of the constant pool item holding the value */
public int getSourceFileCPIndex() {
return cr.getUShort(attr + 6);
}
public String getSourceFile() throws IllegalArgumentException, InvalidClassFileException {
return cr.getCP().getCPUtf8(getSourceFileCPIndex());
}
}
| 1,039
| 32.548387
| 92
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/SourceFileWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
/**
* This class builds serializable SourceFile attributes.
*
* <p>After constructing a SourceFileWriter, you must call setSourceFileCPIndex.
*/
public final class SourceFileWriter extends ClassWriter.Element {
private final int attrID;
private int index = -1;
/**
* Build an empty writer.
*
* @throws IllegalArgumentException if w is null
*/
public SourceFileWriter(ClassWriter w) {
if (w == null) {
throw new IllegalArgumentException("w is null");
}
attrID = w.addCPUtf8("SourceFile");
}
private void verify() {
if (index < 0) {
throw new IllegalArgumentException("The value's constant pool index is not set");
}
}
@Override
public int getSize() throws IllegalArgumentException {
verify();
return 8;
}
@Override
public int copyInto(byte[] buf, int offset) throws IllegalArgumentException {
verify();
ClassWriter.setUShort(buf, offset, attrID);
ClassWriter.setInt(buf, offset + 2, 2);
ClassWriter.setUShort(buf, offset + 6, index);
return offset + 8;
}
/** Set the index of the constant pool item holding the source file name. */
public void setSourceFileCPIndex(int index) throws IllegalArgumentException {
if (index < 1 || index > 0xFFFF) {
throw new IllegalArgumentException("Invalid CP index: " + index);
}
this.index = index;
}
}
| 1,781
| 26.415385
| 87
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/SourcePositionTableReader.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import com.ibm.wala.shrike.shrikeCT.ClassReader.AttrIterator;
import com.ibm.wala.shrike.sourcepos.CRTable;
import com.ibm.wala.shrike.sourcepos.MethodPositions;
import com.ibm.wala.shrike.sourcepos.Range;
import java.io.IOException;
public final class SourcePositionTableReader extends AttributeReader {
private SourcePositionTableReader(AttrIterator attr) throws InvalidClassFileException {
super(attr, CRTable.ATTRIBUTE_NAME);
}
public static final class Position implements Comparable<Position> {
public final int firstLine;
public final int lastLine;
public final int firstCol;
public final int lastCol;
private Position(int firstLine, int lastLine, int firstCol, int lastCol) {
this.firstLine = firstLine;
this.lastLine = lastLine;
this.firstCol = firstCol;
this.lastCol = lastCol;
}
@Override
public int compareTo(Position p) {
if (firstLine != p.firstLine) {
return firstLine - p.firstLine;
} else if (firstCol != p.firstCol) {
return firstCol - p.firstCol;
} else if (lastLine != p.lastLine) {
return lastLine - p.lastLine;
} else if (lastCol != p.lastCol) {
return lastCol - p.lastCol;
} else {
return 0;
}
}
}
public static Position findParameterPosition(int methodNr, CodeReader code)
throws InvalidClassFileException, IOException {
if (code == null) {
throw new IllegalArgumentException();
}
Position params = null;
// read parameter positions
{
ClassReader.AttrIterator cIter = new ClassReader.AttrIterator();
ClassReader cr = code.getClassReader();
cr.initMethodAttributeIterator(methodNr, cIter);
for (; cIter.isValid(); cIter.advance()) {
if (MethodPositions.ATTRIBUTE_NAME.equals(cIter.getName())) {
byte data[] = getData(cr, cIter.getRawOffset(), cIter.getRawSize());
MethodPositions mPos = new MethodPositions(data);
Range r = mPos.getMethodInfo();
params = convert(r);
}
}
}
return params;
}
public static Position[] makeBytecodeToPositionMap(CodeReader code)
throws InvalidClassFileException, IOException {
if (code == null) {
throw new IllegalArgumentException();
}
Position pos[] = null;
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
code.initAttributeIterator(iter);
for (; iter.isValid(); iter.advance()) {
if (CRTable.ATTRIBUTE_NAME.equals(iter.getName())) {
if (pos == null) {
pos = new Position[code.getBytecodeLength()];
}
SourcePositionTableReader spRead = new SourcePositionTableReader(iter);
spRead.fillBytecodeToPositionMap(pos);
}
}
if (pos != null) {
// fill in gaps
Position last = new Position(0, 0, 0, 0);
for (int i = 0; i < pos.length; i++) {
Position cur = pos[i];
if (cur == null) {
pos[i] = last;
} else {
last = cur;
}
}
}
return pos;
}
private static final int ATTRIBUTE_HEADER_SIZE = 6;
private static byte[] getData(ClassReader cr, int rawOffset, int rawSize) {
// prepare raw data of attribute to pass to sourceinfo
byte klass[] = cr.getBytes();
int size = rawSize - ATTRIBUTE_HEADER_SIZE;
byte data[] = new byte[size];
System.arraycopy(klass, rawOffset + ATTRIBUTE_HEADER_SIZE, data, 0, size);
return data;
}
private void fillBytecodeToPositionMap(Position[] pos) throws IOException {
byte tableData[] = getData(getClassReader(), getRawOffset(), getRawSize());
CRTable crTable = new CRTable(tableData);
for (int pc = 0; pc < pos.length; pc++) {
Range r = crTable.getSourceInfo(pc);
Position p = convert(r);
pos[pc] = p;
}
}
private static Position convert(Range r) {
Position pos = null;
if (r != null) {
com.ibm.wala.shrike.sourcepos.Position start = r.getStartPosition();
com.ibm.wala.shrike.sourcepos.Position end = r.getEndPosition();
if (start != null && !start.isUndefined()) {
if (end != null && !end.isUndefined()) {
pos = new Position(start.getLine(), end.getLine(), start.getColumn(), end.getColumn());
} else {
pos = new Position(start.getLine(), start.getLine(), -1, -1);
}
}
}
return pos;
}
public static Position[] makeLineNumberToPositionMap(int[] lineNumberMap) {
Position pos[] = new Position[lineNumberMap.length];
for (int i = 0; i < pos.length; i++) {
int line = lineNumberMap[i];
pos[i] = new Position(line, line, -1, -1);
}
return pos;
}
}
| 5,127
| 28.471264
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/StackMapConstants.java
|
package com.ibm.wala.shrike.shrikeCT;
import static com.ibm.wala.shrike.shrikeCT.StackMapTableWriter.writeUByte;
import static com.ibm.wala.shrike.shrikeCT.StackMapTableWriter.writeUShort;
import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer;
import java.io.IOException;
import java.io.OutputStream;
public class StackMapConstants {
interface StackMapType {
void write(OutputStream s, ClassWriter writer) throws IOException;
int size();
boolean isObject();
}
public enum Item implements StackMapType {
ITEM_Top(0),
ITEM_Integer(1),
ITEM_Float(2),
ITEM_Double(3) {
@Override
public int size() {
return 2;
}
},
ITEM_Long(4) {
@Override
public int size() {
return 2;
}
},
ITEM_Null(5),
ITEM_UninitializedThis(6),
ITEM_Object(7) {
@Override
public boolean isObject() {
return true;
}
},
ITEM_Uninitalized(8) {
@Override
public boolean isObject() {
return true;
}
};
private final byte code;
Item(int code) {
this.code = (byte) code;
}
@Override
public boolean isObject() {
return false;
}
@Override
public int size() {
return 1;
}
@Override
public void write(OutputStream s, ClassWriter writer) throws IOException {
writeUByte(s, code);
}
}
public static class UninitializedType implements StackMapType {
private final String type;
private final int offset;
public UninitializedType(String type) {
assert type.startsWith("#");
this.type = Analyzer.stripSharp(type);
this.offset = Integer.parseInt(type.substring(1, type.lastIndexOf('#')));
}
@Override
public void write(OutputStream s, ClassWriter writer) throws IOException {
Item.ITEM_Uninitalized.write(s, writer);
writeUShort(s, offset);
}
@Override
public int size() {
return Item.ITEM_Uninitalized.size();
}
@Override
public boolean isObject() {
return true;
}
@Override
public String toString() {
return "uninit:" + type;
}
}
public static class ObjectType implements StackMapType {
private final String type;
ObjectType(ClassReader cr, int typeIndex)
throws IllegalArgumentException, InvalidClassFileException {
this(cr.getCP().getCPString(typeIndex));
}
ObjectType(String type) {
this.type = type;
}
@Override
public int size() {
return Item.ITEM_Object.size();
}
@Override
public boolean isObject() {
return true;
}
@Override
public String toString() {
return "obj:" + type;
}
@Override
public void write(OutputStream s, ClassWriter writer) throws IOException {
Item.ITEM_Object.write(s, writer);
if ("L;".equals(type)) {
writeUShort(s, writer.addCPClass("java/lang/Object"));
} else if (type.startsWith("L")) {
writeUShort(s, writer.addCPClass(type.substring(1, type.length() - 1)));
} else {
writeUShort(s, writer.addCPClass(type));
}
}
}
public static Item items[] = {
Item.ITEM_Top,
Item.ITEM_Integer,
Item.ITEM_Float,
Item.ITEM_Double,
Item.ITEM_Long,
Item.ITEM_Null,
Item.ITEM_UninitializedThis,
Item.ITEM_Object,
Item.ITEM_Uninitalized
};
public static class StackMapFrame {
public StackMapFrame(StackMapFrame frame, int newOffset) {
this(frame.frameType, newOffset, frame.localTypes, frame.stackTypes);
}
public StackMapFrame(
int frameType, int offset, StackMapType[] localTypes, StackMapType[] stackTypes) {
this.frameType = frameType;
this.offset = offset;
this.localTypes = localTypes;
this.stackTypes = stackTypes;
}
private final int frameType;
private final int offset;
private final StackMapType[] localTypes;
private final StackMapType[] stackTypes;
public int getFrameType() {
return frameType;
}
public int getOffset() {
return offset;
}
public StackMapType[] getLocalTypes() {
return localTypes;
}
public StackMapType[] getStackTypes() {
return stackTypes;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("frame type: ").append(frameType).append('\n');
sb.append(" offset: ").append(offset).append('\n');
sb.append(" locals\n");
for (StackMapType localType : localTypes) {
sb.append(" ").append(localType).append('\n');
}
sb.append(" stack\n");
for (StackMapType stackType : stackTypes) {
sb.append(" ").append(stackType).append('\n');
}
return sb.toString();
}
public void write(OutputStream out, ClassWriter writer) throws IOException {
// frame type
writeUByte(out, frameType);
// offset delta
writeUShort(out, offset);
// locals
if (localTypes != null) {
writeUShort(out, localTypes.length);
for (StackMapType type : localTypes) {
type.write(out, writer);
}
} else {
writeUShort(out, 0);
}
// stack
if (stackTypes != null) {
writeUShort(out, stackTypes.length);
for (int j = stackTypes.length; j > 0; ) {
stackTypes[--j].write(out, writer);
}
} else {
writeUShort(out, 0);
}
}
}
}
| 5,500
| 21.920833
| 90
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/StackMapTableReader.java
|
package com.ibm.wala.shrike.shrikeCT;
import com.ibm.wala.shrike.shrikeCT.ClassReader.AttrIterator;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.Item;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.ObjectType;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.StackMapFrame;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.StackMapType;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.UninitializedType;
import java.util.ArrayList;
import java.util.List;
public class StackMapTableReader extends AttributeReader {
private final List<StackMapFrame> frames;
public List<StackMapFrame> frames() {
return frames;
}
private StackMapType item(int offset) throws InvalidClassFileException {
Item item = StackMapConstants.items[cr.getByte(offset)];
if (Item.ITEM_Uninitalized == item) {
return new UninitializedType("#" + cr.getUShort(offset + 1) + "#unknown");
} else if (Item.ITEM_Object == item) {
return new ObjectType(cr.getCP().getCPClass(cr.getUShort(offset + 1)));
} else {
return item;
}
}
public StackMapTableReader(AttrIterator iter) throws InvalidClassFileException {
super(iter, "StackMapTable");
frames = new ArrayList<>();
int entries = cr.getUShort(attr + 6);
int ptr = attr + 8;
for (int i = 0; i < entries; i++) {
int frameType = (0x000000ff & cr.getByte(ptr++));
if (frameType < 64) {
int offset = frameType;
frames.add(new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[0]));
} else if (frameType < 128) {
int offset = frameType - 64;
StackMapType stack1 = item(ptr);
ptr += (stack1 instanceof ObjectType) ? 3 : 1;
frames.add(
new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[] {stack1}));
} else if (frameType == 247) {
int offset = cr.getUShort(ptr);
ptr += 2;
StackMapType stack1 = item(ptr);
ptr += (stack1 instanceof ObjectType) ? 3 : 1;
frames.add(
new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[] {stack1}));
} else if (frameType >= 248 && frameType <= 250) {
int offset = cr.getUShort(ptr);
ptr += 2;
frames.add(new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[0]));
} else if (frameType == 251) {
int offset = cr.getUShort(ptr);
ptr += 2;
frames.add(new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[0]));
} else if (frameType >= 252 && frameType <= 254) {
StackMapType[] locals = new StackMapType[frameType - 251];
int offset = cr.getUShort(ptr);
ptr += 2;
for (int j = 0; j < locals.length; j++) {
locals[j] = item(ptr);
ptr += (locals[j] instanceof ObjectType) ? 3 : 1;
}
frames.add(new StackMapFrame(frameType, offset, locals, new StackMapType[0]));
} else if (frameType == 255) {
int offset = cr.getUShort(ptr);
ptr += 2;
int numLocals = cr.getUShort(ptr);
ptr += 2;
StackMapType[] locals = new StackMapType[numLocals];
for (int j = 0; j < numLocals; j++) {
locals[j] = item(ptr);
ptr += (locals[j] instanceof ObjectType) ? 3 : 1;
}
int numStack = cr.getUShort(ptr);
ptr += 2;
StackMapType[] stack = new StackMapType[numStack];
for (int j = 0; j < numStack; j++) {
stack[j] = item(ptr);
ptr += stack[j].isObject() ? 3 : 1;
}
frames.add(new StackMapFrame(frameType, offset, locals, stack));
}
}
}
public static List<StackMapFrame> readStackMap(CodeReader code)
throws InvalidClassFileException, IllegalArgumentException {
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
code.initAttributeIterator(iter);
for (; iter.isValid(); iter.advance()) {
if (iter.getName().equals("StackMapTable")) {
StackMapTableReader r = new StackMapTableReader(iter);
return r.frames();
}
}
return null;
}
}
| 4,162
| 37.192661
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/StackMapTableWriter.java
|
package com.ibm.wala.shrike.shrikeCT;
import static com.ibm.wala.shrike.shrikeBT.Constants.TYPE_double;
import static com.ibm.wala.shrike.shrikeBT.Constants.TYPE_float;
import static com.ibm.wala.shrike.shrikeBT.Constants.TYPE_int;
import static com.ibm.wala.shrike.shrikeBT.Constants.TYPE_long;
import static com.ibm.wala.shrike.shrikeBT.Constants.TYPE_null;
import com.ibm.wala.shrike.shrikeBT.Compiler.Output;
import com.ibm.wala.shrike.shrikeBT.GotoInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer;
import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException;
import com.ibm.wala.shrike.shrikeBT.analysis.ClassHierarchyProvider;
import com.ibm.wala.shrike.shrikeBT.analysis.Verifier;
import com.ibm.wala.shrike.shrikeCT.ClassWriter.Element;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.Item;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.ObjectType;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.StackMapFrame;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.StackMapType;
import com.ibm.wala.shrike.shrikeCT.StackMapConstants.UninitializedType;
import com.ibm.wala.util.collections.HashMapFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class StackMapTableWriter extends Element {
private final byte[] data;
public StackMapTableWriter(ClassWriter writer, List<StackMapFrame> frames) throws IOException {
this.data = serialize(writer, frames);
}
private static byte[] serialize(ClassWriter writer, List<StackMapFrame> frames)
throws IOException {
ByteArrayOutputStream data = new ByteArrayOutputStream();
for (StackMapFrame frame : frames) {
frame.write(data, writer);
}
ByteArrayOutputStream bs = new ByteArrayOutputStream();
writeUShort(bs, writer.addCPUtf8("StackMapTable"));
writeInt(bs, data.size() + 2);
writeUShort(bs, frames.size());
data.writeTo(bs);
return bs.toByteArray();
}
public StackMapTableWriter(
ClassWriter writer,
MethodData method,
Output output,
ClassHierarchyProvider cha,
String[][] vars)
throws FailureException, IOException {
this(writer, stackMapTable(method, output, cha, vars, null));
}
public StackMapTableWriter(
ClassWriter writer,
MethodData method,
Output output,
ClassHierarchyProvider cha,
String[][] vars,
List<StackMapFrame> reuseFrames)
throws FailureException, IOException {
this(writer, stackMapTable(method, output, cha, vars, reuseFrames));
}
private static List<StackMapFrame> remapStackFrames(
List<StackMapFrame> sm, int[] newBytecodesToOldBytecodes) {
// mapping to new bytecode
Map<Integer, Integer> oldToNew = HashMapFactory.make();
for (int i = newBytecodesToOldBytecodes.length - 1; i >= 0; i--) {
oldToNew.put(newBytecodesToOldBytecodes[i], i);
}
// positions of frames
int i = 1;
int positions[] = new int[sm.size()];
Iterator<StackMapFrame> sms = sm.iterator();
int position = sms.next().getOffset();
positions[0] = oldToNew.get(position);
while (sms.hasNext()) {
position += sms.next().getOffset() + 1;
positions[i++] = oldToNew.get(position);
}
// positions turned into offsets
for (i = positions.length - 1; i > 0; i--) {
positions[i] = positions[i] - positions[i - 1] - 1;
}
// frames with new offsets
List<StackMapFrame> newFrames = new ArrayList<>(sm.size());
for (i = 0; i < sm.size(); i++) {
newFrames.add(new StackMapFrame(sm.get(i), positions[i]));
}
return newFrames;
}
public StackMapTableWriter(
ClassWriter w, List<StackMapFrame> sm, int[] newBytecodesToOldBytecodes) throws IOException {
this(w, remapStackFrames(sm, newBytecodesToOldBytecodes));
}
static StackMapType item(String type) {
if (type == null) {
return Item.ITEM_Top;
} else if (type.equals(TYPE_null)) {
return Item.ITEM_Null;
} else if (type.equals(Analyzer.topType)) {
return Item.ITEM_Top;
} else if (type.equals(Analyzer.thisType)) {
return Item.ITEM_UninitializedThis;
} else if (type.equals(TYPE_int)) {
return Item.ITEM_Integer;
} else if (type.equals(TYPE_float)) {
return Item.ITEM_Float;
} else if (type.equals(TYPE_double)) {
return Item.ITEM_Double;
} else if (type.equals(TYPE_long)) {
return Item.ITEM_Long;
} else {
if (type.startsWith("#")) {
return new UninitializedType(type);
} else {
return new ObjectType(type);
}
}
}
static void writeUByte(OutputStream s, int v) throws IOException {
byte bytes[] = new byte[1];
ClassWriter.setUByte(bytes, 0, v);
s.write(bytes);
}
static void writeUShort(OutputStream s, int v) throws IOException {
byte bytes[] = new byte[2];
ClassWriter.setUShort(bytes, 0, v);
s.write(bytes);
}
static void writeInt(OutputStream s, int v) throws IOException {
byte bytes[] = new byte[4];
ClassWriter.setInt(bytes, 0, v);
s.write(bytes);
}
static StackMapType[] trim(StackMapType[] types) {
int i = types.length - 1;
while (i >= 0
&& (types[i] == null || types[i] == Item.ITEM_Null || types[i] == Item.ITEM_Top)) {
i--;
}
if (i < 0) {
return new StackMapType[0];
} else if (i < types.length - 1) {
StackMapType[] trimmed = new StackMapType[i + 1];
System.arraycopy(types, 0, trimmed, 0, i + 1);
return trimmed;
} else {
return types;
}
}
private static String hackUnknown(String type) {
if (type == null) {
return type;
} else if (type.startsWith("[")) {
return '[' + hackUnknown(type.substring(1));
} else if ("L?;".equals(type)) {
return "Ljava/lang/Object;";
} else {
return type;
}
}
static StackMapType[] types(String[] types, boolean locals) {
StackMapType[] stackTypes = new StackMapType[types.length];
int x = 0;
for (int j = 0; j < types.length; j++) {
StackMapType stackType = item(hackUnknown(types[j]));
stackTypes[x++] = stackType;
if (locals && stackType.size() == 2) {
j++;
}
}
return trim(stackTypes);
}
private static boolean isUselessGoto(IInstruction inst, int index) {
if (inst instanceof GotoInstruction) {
if (((GotoInstruction) inst).getBranchTargets()[0] == index + 1) {
return true;
}
}
return false;
}
public static List<StackMapFrame> stackMapTable(
MethodData method,
Output output,
ClassHierarchyProvider cha,
String[][] vars,
List<StackMapFrame> reuseFrames)
throws FailureException {
int idx = 0;
List<StackMapFrame> frames = new ArrayList<>();
int[] instructionToBytecode = output.getInstructionOffsets();
IInstruction[] insts = method.getInstructions();
Verifier typeChecker = new Verifier(method, instructionToBytecode, vars);
if (cha != null) {
typeChecker.setClassHierarchy(cha);
}
typeChecker.computeTypes();
BitSet bbs = typeChecker.getBasicBlockStarts();
int offset = 0;
for (int i = 1; i < insts.length; i++) {
if (bbs.get(i)) {
// Shrike does not generate goto i+1
if (isUselessGoto(insts[i], i)) {
continue;
}
// offset delta
int position = instructionToBytecode[i];
assert position - offset > 0 || offset == 0;
int frameOffset = offset == 0 ? position : position - offset - 1;
offset = position;
if (reuseFrames != null) {
if (idx < reuseFrames.size() && reuseFrames.get(idx).getOffset() == frameOffset) {
frames.add(reuseFrames.get(idx++));
continue;
} else {
reuseFrames = null;
}
}
// full frame
byte frameType = (byte) 255;
// locals
String[] localTypes = typeChecker.getLocalTypes()[i];
StackMapType[] localWriteTypes;
if (localTypes != null) {
localWriteTypes = types(localTypes, true);
} else {
localWriteTypes = new StackMapType[0];
}
// stack
String[] stackTypes = typeChecker.getStackTypes()[i];
StackMapType[] stackWriteTypes;
if (stackTypes != null) {
stackWriteTypes = types(stackTypes, false);
} else {
stackWriteTypes = new StackMapType[0];
}
frames.add(new StackMapFrame(frameType, frameOffset, localWriteTypes, stackWriteTypes));
}
}
return frames;
}
@Override
public int getSize() {
return data.length;
}
@Override
public int copyInto(byte[] buf, int offset) {
System.arraycopy(data, 0, buf, offset + 0, data.length);
return data.length + offset;
}
}
| 9,110
| 29.471572
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeCT/TypeAnnotationsReader.java
|
/*
* Copyright (c) 2016 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Martin Hecker, KIT - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeCT;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* This class reads TypeAnnotations attributes, i.e.: RuntimeInvisibleTypeAnnotations and
* RuntimeVisibleTypeAnnotations
*
* @author Martin Hecker martin.hecker@kit.edu
*/
public class TypeAnnotationsReader extends AnnotationsReader {
/** required for {@link TypeAnnotationLocation#method_info} readers */
private final ExceptionsReader exceptionReader;
/** required for {@link TypeAnnotationLocation#Code} readers */
private final CodeReader codeReader;
/**
* required for {@link TypeAnnotationLocation#method_info} and for {@link
* TypeAnnotationLocation#ClassFile} readers
*/
private final SignatureReader signatureReader;
private final TypeAnnotationLocation location;
protected TypeAnnotationsReader(
ClassReader.AttrIterator iter,
String label,
ExceptionsReader exceptionReader,
CodeReader codeReader,
SignatureReader signatureReader,
TypeAnnotationLocation location)
throws InvalidClassFileException {
super(iter, label);
this.exceptionReader = exceptionReader;
this.codeReader = codeReader;
this.signatureReader = signatureReader;
this.location = location;
}
/**
* @return a TypeAnnotationReader for reading type annotations in the attributes table of a
* ClassFile structure
*/
public static TypeAnnotationsReader getTypeAnnotationReaderAtClassfile(
ClassReader.AttrIterator iter, String label, SignatureReader signatureReader)
throws InvalidClassFileException {
return new TypeAnnotationsReader(
iter, label, null, null, signatureReader, TypeAnnotationLocation.ClassFile);
}
/**
* @return a TypeAnnotationReader for reading type annotations in the attributes table of a
* method_info structure
*/
public static TypeAnnotationsReader getTypeAnnotationReaderAtMethodInfo(
ClassReader.AttrIterator iter,
String label,
ExceptionsReader exceptionReader,
SignatureReader signatureReader)
throws InvalidClassFileException {
return new TypeAnnotationsReader(
iter, label, exceptionReader, null, signatureReader, TypeAnnotationLocation.method_info);
}
/**
* @return a TypeAnnotationReader for reading type annotations in the attributes table of a
* field_info structure
*/
public static TypeAnnotationsReader getTypeAnnotationReaderAtFieldInfo(
ClassReader.AttrIterator iter, String label) throws InvalidClassFileException {
return new TypeAnnotationsReader(
iter, label, null, null, null, TypeAnnotationLocation.field_info);
}
/**
* @return a TypeAnnotationReader for reading type annotations in the attributes table of a Code
* attribute
*/
public static TypeAnnotationsReader getTypeAnnotationReaderAtCode(
ClassReader.AttrIterator iter, String label, CodeReader codeReader)
throws InvalidClassFileException {
return new TypeAnnotationsReader(
iter, label, null, codeReader, null, TypeAnnotationLocation.Code);
}
/**
* @return an array TypeAnnotationAttribute[] corresponding to the annotations[num_annotations]
* table specified as:
* <pre>
* RuntimeVisibleTypeAnnotations_attribute {
* u2 attribute_name_index;
* u4 attribute_length;
* u2 num_annotations;
* type_annotation annotations[num_annotations];
* }
* </pre>
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20">JLS
* (SE8), 4.7.20</a>
*/
public TypeAnnotationAttribute[] getAllTypeAnnotations() throws InvalidClassFileException {
TypeAnnotationAttribute[] result = new TypeAnnotationAttribute[getAnnotationCount()];
int offset = beginOffset + 8; // skip attribute_name_index,
// attribute_length, and num_annotations
for (int i = 0; i < result.length; i++) {
Pair<TypeAnnotationAttribute, Integer> attributeAndSize = getTypeAttributeAndSize(offset);
result[i] = attributeAndSize.fst;
offset += attributeAndSize.snd;
}
return result;
}
/**
* @param begin the offset from which to read a type annotation
* @return a Pair (a,i) such that "i" is the number of bytes read in order to construct "a", which
* is the {@link TypeAnnotationAttribute} that corresponds to the type_annotation structure at
* offset begin specified as:
* <pre>
* type_annotation {
* u1 target_type;
* union {
* type_parameter_target;
* supertype_target;
* type_parameter_bound_target;
* empty_target;
* method_formal_parameter_target;
* throws_target;
* localvar_target;
* catch_target;
* offset_target;
* type_argument_target;
* } target_info;
* type_path target_path;
* u2 type_index;
* u2 num_element_value_pairs;
* { u2 element_name_index;
* element_value value;
* } element_value_pairs[num_element_value_pairs];
* }
* </pre>
*/
private Pair<TypeAnnotationAttribute, Integer> getTypeAttributeAndSize(int begin)
throws InvalidClassFileException {
TargetType target_type = TargetType.fromValue(cr.getUnsignedByte(begin));
if (target_type == null) {
throw new InvalidClassFileException(
begin, "Unknown target_type: " + cr.getUnsignedByte(begin));
}
if (target_type.location != this.location) {
throw new InvalidClassFileException(
begin,
target_type
+ " annotation found while reading "
+ this.location
+ " annotations."
+ " Only valid at "
+ target_type.location);
}
final Pair<TypeAnnotationTarget, Integer> pAnnotationTargetAndSize =
getTypeAnnotationTargetAndSize(begin + 1, target_type.target_info);
final int type_path_offset = begin + 1 + pAnnotationTargetAndSize.snd;
checkSize(type_path_offset, 1);
final int path_length = cr.getUnsignedByte(type_path_offset);
checkSize(type_path_offset + 1, 2 * path_length);
ArrayList<Pair<TypePathKind, Integer>> type_path = new ArrayList<>(path_length);
int current_path_element = type_path_offset + 1;
for (int i = 0; i < path_length; i++) {
TypePathKind type_path_kind =
TypePathKind.fromValue(cr.getUnsignedByte(current_path_element));
int type_argument_index = cr.getUnsignedByte(current_path_element + 1);
type_path.add(i, Pair.make(type_path_kind, type_argument_index));
current_path_element += 2;
}
final int annotation_begin = type_path_offset + 1 + 2 * path_length;
Pair<AnnotationAttribute, Integer> pAttributeAndSize = getAttributeAndSize(annotation_begin);
return Pair.make(
new TypeAnnotationAttribute(
pAnnotationTargetAndSize.fst, pAttributeAndSize.fst, type_path, target_type),
1 + pAnnotationTargetAndSize.snd + 1 + 2 * path_length + pAttributeAndSize.snd);
}
private Pair<TypeAnnotationTarget, Integer> getTypeAnnotationTargetAndSize(
int begin, TargetInfo target_info) throws InvalidClassFileException {
switch (target_info) {
case type_parameter_target:
{
checkSize(begin, 1);
return Pair.<TypeAnnotationTarget, Integer>make(
new TypeParameterTarget(cr.getUnsignedByte(begin)), 1);
}
case supertype_target:
{
checkSize(begin, 2);
final int interfaceIndex = cr.getUShort(begin);
final String superType;
if (interfaceIndex == 65535) {
superType = cr.getSuperName();
} else {
superType = cr.getInterfaceName(interfaceIndex);
}
return Pair.<TypeAnnotationTarget, Integer>make(new SuperTypeTarget(superType), 2);
}
case type_parameter_bound_target:
{
checkSize(begin, 2);
return Pair.<TypeAnnotationTarget, Integer>make(
new TypeParameterBoundTarget(
cr.getUnsignedByte(begin),
cr.getUnsignedByte(begin + 1),
signatureReader.getSignature()),
2);
}
case empty_target:
{
return Pair.<TypeAnnotationTarget, Integer>make(new EmptyTarget(), 0);
}
case formal_parameter_target:
{
checkSize(begin, 1);
return Pair.<TypeAnnotationTarget, Integer>make(
new FormalParameterTarget(cr.getUnsignedByte(begin)), 1);
}
case throws_target:
{
assert exceptionReader != null;
checkSize(begin, 2);
final int throwsIndex = cr.getUShort(begin);
return Pair.<TypeAnnotationTarget, Integer>make(
new ThrowsTarget(exceptionReader.getClasses()[throwsIndex]), 2);
}
/*
* localvar_target {
* u2 table_length;
* { u2 start_pc;
u2 length;
u2 index;
* } table[table_length];
* }
*/
case localvar_target:
{
checkSize(begin, 2);
final int table_length = cr.getUShort(begin);
final int offset = begin + 2;
checkSize(offset, (2 + 2 + 2) * table_length);
int[] start_pc = new int[table_length];
int[] length = new int[table_length];
int[] index = new int[table_length];
for (int i = 0; i < table_length; i++) {
start_pc[i] = cr.getUShort(offset + (2 + 2 + 2) * i);
length[i] = cr.getUShort(offset + 2 + (2 + 2 + 2) * i);
index[i] = cr.getUShort(offset + 4 + (2 + 2 + 2) * i);
}
return Pair.<TypeAnnotationTarget, Integer>make(
new LocalVarTarget(start_pc, length, index), 2 + (2 + 2 + 2) * table_length);
}
case catch_target:
{
assert codeReader != null;
checkSize(begin, 2);
int exception_table_index = cr.getUShort(begin);
int[] rawHandler = new int[4];
System.arraycopy(
codeReader.getRawHandlers(), exception_table_index * 4, rawHandler, 0, 4);
final String catchType =
rawHandler[3] == 0
? CatchTarget.ALL_EXCEPTIONS
: cr.getCP().getCPClass(rawHandler[3]);
return Pair.<TypeAnnotationTarget, Integer>make(
new CatchTarget(rawHandler, catchType), 2);
}
case offset_target:
{
checkSize(begin, 2);
int offset = cr.getUShort(begin);
return Pair.<TypeAnnotationTarget, Integer>make(new OffsetTarget(offset), 2);
}
case type_argument_target:
{
checkSize(begin, 3);
int offset = cr.getUShort(begin);
int type_argument_index = cr.getUnsignedByte(begin);
return Pair.<TypeAnnotationTarget, Integer>make(
new TypeArgumentTarget(offset, type_argument_index), 3);
}
default:
Assertions.UNREACHABLE();
return null;
}
}
/**
* Enumeration of those Bytecode locations where type annotation may appear (in the corresponding
* attribute table).
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20">JLS
* (SE8), 4.7.20</a>
*/
public enum TypeAnnotationLocation {
ClassFile,
method_info,
field_info,
Code;
}
/**
* Possible target_type items.
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20">JLS
* (SE8), 4.7.20</a>
*/
public enum TargetInfo {
type_parameter_target,
supertype_target,
type_parameter_bound_target,
empty_target,
formal_parameter_target,
throws_target,
localvar_target,
catch_target,
offset_target,
type_argument_target
}
/**
* Known target_types for JSR 308 Type-Annotation.
*
* <p>Constant names taken from <a
* href="http://types.cs.washington.edu/jsr308/">http://types.cs.washington.edu/jsr308/</a>
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20">JLS
* (SE8), 4.7.20</a>
*/
// TODO: This somewhat mirrors com.sun.tools.javac.code.TargetType, maybe just use that instead?
public enum TargetType {
CLASS_TYPE_PARAMETER(0x00, TargetInfo.type_parameter_target, TypeAnnotationLocation.ClassFile),
METHOD_TYPE_PARAMETER(
0x01, TargetInfo.type_parameter_target, TypeAnnotationLocation.method_info),
CLASS_EXTENDS(0x10, TargetInfo.supertype_target, TypeAnnotationLocation.ClassFile),
CLASS_TYPE_PARAMETER_BOUND(
0x11, TargetInfo.type_parameter_bound_target, TypeAnnotationLocation.ClassFile),
METHOD_TYPE_PARAMETER_BOUND(
0x12, TargetInfo.type_parameter_bound_target, TypeAnnotationLocation.method_info),
FIELD(0x13, TargetInfo.empty_target, TypeAnnotationLocation.field_info),
METHOD_RETURN(0x14, TargetInfo.empty_target, TypeAnnotationLocation.method_info),
METHOD_RECEIVER(0x15, TargetInfo.empty_target, TypeAnnotationLocation.method_info),
METHOD_FORMAL_PARAMETER(
0x16, TargetInfo.formal_parameter_target, TypeAnnotationLocation.method_info),
THROWS(0x17, TargetInfo.throws_target, TypeAnnotationLocation.method_info),
LOCAL_VARIABLE(0x40, TargetInfo.localvar_target, TypeAnnotationLocation.Code),
RESOURCE_VARIABLE(0x41, TargetInfo.localvar_target, TypeAnnotationLocation.Code),
EXCEPTION_PARAMETER(0x42, TargetInfo.catch_target, TypeAnnotationLocation.Code),
INSTANCEOF(0x43, TargetInfo.offset_target, TypeAnnotationLocation.Code),
NEW(0x44, TargetInfo.offset_target, TypeAnnotationLocation.Code),
CONSTRUCTOR_REFERENCE(0x45, TargetInfo.offset_target, TypeAnnotationLocation.Code),
METHOD_REFERENCE(0x46, TargetInfo.offset_target, TypeAnnotationLocation.Code),
CAST(0x47, TargetInfo.type_argument_target, TypeAnnotationLocation.Code),
CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT(
0x48, TargetInfo.type_argument_target, TypeAnnotationLocation.Code),
METHOD_INVOCATION_TYPE_ARGUMENT(
0x49, TargetInfo.type_argument_target, TypeAnnotationLocation.Code),
CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT(
0x4A, TargetInfo.type_argument_target, TypeAnnotationLocation.Code),
METHOD_REFERENCE_TYPE_ARGUMENT(
0x4B, TargetInfo.type_argument_target, TypeAnnotationLocation.Code);
private static final Map<Integer, TargetType> fromValue;
static {
final TargetType[] targetTypes = TargetType.values();
fromValue = HashMapFactory.make(targetTypes.length);
for (TargetType targetType : targetTypes) {
fromValue.put(targetType.target_type, targetType);
}
}
public static TargetType fromValue(int value) {
return fromValue.get(value);
}
public final int target_type;
public final TargetInfo target_info;
public final TypeAnnotationLocation location;
TargetType(int target_type, TargetInfo target_info, TypeAnnotationLocation location) {
if (!(0 <= target_type && target_type <= Byte.MAX_VALUE)) {
throw new IllegalArgumentException(
"Code may break for target_type that does not fit in a Java (signed!) byte");
}
this.target_type = target_type;
this.target_info = target_info;
this.location = location;
}
}
/**
* A {@link TypeAnnotationTarget} represents one of the possible target_info structure
*
* <pre>
* union {
* type_parameter_target;
* supertype_target;
* type_parameter_bound_target;
* empty_target;
* method_formal_parameter_target;
* throws_target;
* localvar_target;
* catch_target;
* offset_target;
* type_argument_target;
* } target_info;
* </pre>
*
* @author Martin Hecker martin.hecker@kit.edu
*/
public abstract static class TypeAnnotationTarget {
private final TargetInfo targetInfo;
protected TypeAnnotationTarget(TargetInfo targetInfo) {
this.targetInfo = targetInfo;
}
public TargetInfo getTargetInfo() {
return targetInfo;
}
public abstract <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor);
}
public interface TypeAnnotationTargetVisitor<R> {
R visitTypeParameterTarget(TypeParameterTarget target);
R visitSuperTypeTarget(SuperTypeTarget target);
R visitTypeParameterBoundTarget(TypeParameterBoundTarget target);
R visitEmptyTarget(EmptyTarget target);
R visitFormalParameterTarget(FormalParameterTarget target);
R visitThrowsTarget(ThrowsTarget target);
R visitLocalVarTarget(LocalVarTarget target);
R visitCatchTarget(CatchTarget target);
R visitOffsetTarget(OffsetTarget target);
R visitTypeArgumentTarget(TypeArgumentTarget target);
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-A.1">
* JLS (SE8), 4.7.20.1 A</a>
*/
public static class TypeParameterTarget extends TypeAnnotationTarget {
private final int type_parameter_index;
public TypeParameterTarget(int type_parameter_index) {
super(TargetInfo.type_parameter_target);
this.type_parameter_index = type_parameter_index;
}
public int getIndex() {
return type_parameter_index;
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitTypeParameterTarget(this);
}
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-B.1">
* JLS (SE8), 4.7.20.1 B</a>
*/
public static class SuperTypeTarget extends TypeAnnotationTarget {
private final String superType;
public SuperTypeTarget(String superType) {
super(TargetInfo.supertype_target);
this.superType = superType;
}
public String getSuperType() {
return superType;
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitSuperTypeTarget(this);
}
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-C.1">
* JLS (SE8), 4.7.20.1 C</a>
*/
public static class TypeParameterBoundTarget extends TypeAnnotationTarget {
private final int type_parameter_index;
private final int bound_index;
private final String boundSignature;
public TypeParameterBoundTarget(
int type_parameter_index, int bound_index, String boundSignature) {
super(TargetInfo.type_parameter_bound_target);
this.type_parameter_index = type_parameter_index;
this.bound_index = bound_index;
this.boundSignature = boundSignature;
}
public int getParameterIndex() {
return type_parameter_index;
}
public int getBoundIndex() {
return bound_index;
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitTypeParameterBoundTarget(this);
}
public String getBoundSignature() {
return boundSignature;
}
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-D.1">
* JLS (SE8), 4.7.20.1 D</a>
*/
public static class EmptyTarget extends TypeAnnotationTarget {
public EmptyTarget() {
super(TargetInfo.empty_target);
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitEmptyTarget(this);
}
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-E.1">
* JLS (SE8), 4.7.20.1 E</a>
*/
public static class FormalParameterTarget extends TypeAnnotationTarget {
private final int formal_parameter_index;
public FormalParameterTarget(int index) {
super(TargetInfo.formal_parameter_target);
this.formal_parameter_index = index;
}
public int getIndex() {
return formal_parameter_index;
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitFormalParameterTarget(this);
}
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-F.1">
* JLS (SE8), 4.7.20.1 F</a>
*/
public static class ThrowsTarget extends TypeAnnotationTarget {
private final String throwType;
public ThrowsTarget(String throwType) {
super(TargetInfo.supertype_target);
this.throwType = throwType;
}
public String getThrowType() {
return throwType;
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitThrowsTarget(this);
}
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-G.1">
* JLS (SE8), 4.7.20.1 G</a>
*/
public static class LocalVarTarget extends TypeAnnotationTarget {
private final int[] start_pc;
private final int[] length;
private final int[] index;
public LocalVarTarget(int[] start_pc, int[] length, int[] index) {
super(TargetInfo.localvar_target);
if (!(start_pc.length == length.length && length.length == index.length))
throw new IllegalArgumentException();
// TODO: do we really need to copy here? Can't we trust callees not to change arrays after the
// fact?
this.start_pc = Arrays.copyOf(start_pc, start_pc.length);
this.length = Arrays.copyOf(length, length.length);
this.index = Arrays.copyOf(index, index.length);
}
public int getNrOfRanges() {
return start_pc.length;
}
public int getStartPc(int range) {
return start_pc[range];
}
public int getLength(int range) {
return length[range];
}
public int getIndex(int range) {
return index[range];
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitLocalVarTarget(this);
}
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-H.1">
* JLS (SE8), 4.7.20.1 H</a>
*/
public static class CatchTarget extends TypeAnnotationTarget {
private final int[] rawHandler;
private final String catchType;
public static final String ALL_EXCEPTIONS = null;
public CatchTarget(int[] rawHandler, String catchType) {
super(TargetInfo.catch_target);
this.rawHandler = rawHandler;
this.catchType = catchType;
}
/**
* @return The type-annotations targets raw handler, i.e.: a 4 tuple (startPC, endPC, catchPC,
* catchClassIndex)
* @see CodeReader
*/
public int[] getRawHandler() {
// TODO: do we really need to copy here? Can't we trust callees not to change arrays after the
// fact?
return Arrays.copyOf(rawHandler, rawHandler.length);
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitCatchTarget(this);
}
public String getCatchType() {
return catchType;
}
public int getStartPC() {
return rawHandler[0];
}
public int getEndPC() {
return rawHandler[1];
}
public int getCatchPC() {
return rawHandler[2];
}
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-I.1">
* JLS (SE8), 4.7.20.1 I</a>
*/
public static class OffsetTarget extends TypeAnnotationTarget {
private final int offset;
public OffsetTarget(int offset) {
super(TargetInfo.offset_target);
this.offset = offset;
}
public int getOffset() {
return offset;
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitOffsetTarget(this);
}
}
/**
* @see <a
* href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.20.1-100-J.1">
* JLS (SE8), 4.7.20.1 J</a>
*/
public static class TypeArgumentTarget extends TypeAnnotationTarget {
private final int offset;
private final int type_argument_index;
public TypeArgumentTarget(int offset, int type_argument_index) {
super(TargetInfo.type_argument_target);
this.offset = offset;
this.type_argument_index = type_argument_index;
}
public int getOffset() {
return offset;
}
public int getTypeArgumentIndex() {
return type_argument_index;
}
@Override
public <R> R acceptVisitor(TypeAnnotationTargetVisitor<R> visitor) {
return visitor.visitTypeArgumentTarget(this);
}
}
public enum AnnotationType {
RuntimeInvisibleTypeAnnotations,
RuntimeVisibleTypeAnnotations
}
public enum TypePathKind {
DEEPER_IN_ARRAY(0),
DEEPER_IN_NESTED(1),
WILDCARD_BOUND(2),
TYPE_ARGUMENT(3);
private final int type_path_kind;
TypePathKind(int type_path_kind) {
this.type_path_kind = type_path_kind;
}
private static final Map<Integer, TypePathKind> fromValue;
static {
final TypePathKind[] typePathKinds = TypePathKind.values();
fromValue = HashMapFactory.make(typePathKinds.length);
for (TypePathKind typePathKind : typePathKinds) {
fromValue.put(typePathKind.type_path_kind, typePathKind);
}
}
public static TypePathKind fromValue(int value) {
return fromValue.get(value);
}
}
public static final List<Pair<TypePathKind, Integer>> TYPEPATH_EMPTY = Collections.emptyList();
public static class TypeAnnotationAttribute {
public final TypeAnnotationTarget annotationTarget;
public final AnnotationAttribute annotationAttribute;
public final List<Pair<TypePathKind, Integer>> typePath;
public final TargetType targetType;
public TypeAnnotationAttribute(
TypeAnnotationTarget annotationTarget,
AnnotationAttribute annotationAttribute,
List<Pair<TypePathKind, Integer>> typePath,
TargetType targetType) {
this.annotationTarget = annotationTarget;
this.annotationAttribute = annotationAttribute;
this.typePath = Collections.unmodifiableList(typePath);
this.targetType = targetType;
}
}
public static boolean isKnownAnnotation(String name) {
for (AnnotationType t : AnnotationType.values()) {
if (t.name().equals(name)) {
return true;
}
}
return false;
}
private interface Action {
TypeAnnotationsReader apply() throws InvalidClassFileException;
}
public static TypeAnnotationsReader getReaderForAnnotationAtClassfile(
final AnnotationType type,
final ClassReader.AttrIterator iter,
final SignatureReader signatureReader) {
return advanceIter(
type,
iter,
() -> getTypeAnnotationReaderAtClassfile(iter, type.toString(), signatureReader));
}
public static TypeAnnotationsReader getReaderForAnnotationAtMethodInfo(
final AnnotationType type,
final ClassReader.AttrIterator iter,
final ExceptionsReader exceptionReader,
final SignatureReader signatureReader) {
return advanceIter(
type,
iter,
() ->
getTypeAnnotationReaderAtMethodInfo(
iter, type.toString(), exceptionReader, signatureReader));
}
public static TypeAnnotationsReader getReaderForAnnotationAtFieldInfo(
final AnnotationType type, final ClassReader.AttrIterator iter) {
return advanceIter(type, iter, () -> getTypeAnnotationReaderAtFieldInfo(iter, type.toString()));
}
public static TypeAnnotationsReader getReaderForAnnotationAtCode(
final AnnotationType type, final ClassReader.AttrIterator iter, final CodeReader codereader) {
return advanceIter(
type, iter, () -> getTypeAnnotationReaderAtCode(iter, type.toString(), codereader));
}
private static TypeAnnotationsReader advanceIter(
AnnotationType type, ClassReader.AttrIterator iter, Action newReader) {
// search for the desired attribute
final String attrName = type.toString();
try {
for (; iter.isValid(); iter.advance()) {
if (iter.getName().equals(attrName)) return newReader.apply();
}
} catch (InvalidClassFileException e) {
Assertions.UNREACHABLE();
}
return null;
}
}
| 29,241
| 32.079186
| 101
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/CRTData.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* CRTData.java
*
* Created on 7. Juni 2005, 11:48
*/
package com.ibm.wala.shrike.sourcepos;
import com.ibm.wala.shrike.sourcepos.InvalidRangeException.Cause;
/**
* This class represents an entry in the CharacterRangeTable.
*
* @see CRTFlags
* @see CRTable
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
public final class CRTData {
private static final String WARN_INVALID_PC_RANGE =
"Error at CRT entry %1$s: the program counter start index (%2$s) must be greater or equal than the end index (%3$s).";
private static final String WARN_INVALID_START_LINE_NUMBER =
"Error at CRT entry %1$s: the line number of the source start position must not be 0.";
private static final String WARN_INVALID_START_COLUMN_NUMBER =
"Error at CRT entry %1$s: the column number of the source start position not be 0.";
private static final String WARN_INVALID_END_LINE_NUMBER =
"Error at CRT entry %1$s: the line number of the source end position must not be 0.";
private static final String WARN_INVALID_END_COLUMN_NUMBER =
"Error at CRT entry %1$s: the column number of the source end position must not be 0.";
private static final String WARN_END_BEFORE_START =
"Error at CRT entry %1$s: the source end position (%3$s) is before the source start position (%2$s).";
private static final String WARN_START_UNDEFINED =
"Error at CRT entry %1$s: the source start position is undefined.";
private static final String WARN_END_UNDEFINED =
"Error at CRT entry %1$s: the source end position is undefined.";
/** start index in the code array of the code attribute */
private final int pc_start_index;
/** end index in the code array of the code attribute */
private final int pc_end_index;
/** positions in the source file */
private final Range source_positions;
/**
* flags
*
* @see CRTFlags
*/
private final CRTFlags flags;
/**
* Creates a new instance of CRTData. {@code source_start_position} and {@code
* source_end_position} can be {@code 0} to show that a range in the code array of the code
* attribute has no source positions.
*
* @param pc_start_index start index in the code array of the code attribute as unsigned short
* @param pc_end_index end index in the code array of the code attribute as unsigned short
* @param source_start_position start position in the source file as unsigned int
* @param source_end_position end position in the source file as unsigned int
* @param flags flags defined in {@link CRTFlags}
* @throws InvalidCRTDataException if a parameter violates one of the following conditions:
* <ul>
* <li>{@code pc_start_index < pc_end_index}
* <li>{@code source_start_position} is a valid position.
* <li>{@code source_end_position} is a valid position.
* <li>{@code source_start_position <= source_end_position}
* <li>{@code source_start_position} and {@code source_end_position} must be a valid range.
* <li>{@code flags} must contain valid flags.
* </ul>
*/
CRTData(
short pc_start_index,
short pc_end_index,
int source_start_position,
int source_end_position,
short flags)
throws InvalidCRTDataException {
this.pc_start_index = pc_start_index & 0xFFFF;
this.pc_end_index = pc_end_index & 0xFFFF;
if (pc_start_index > pc_end_index)
throw new InvalidCRTDataException(
WARN_INVALID_PC_RANGE, this.pc_start_index, this.pc_end_index);
Position source_start = null;
try {
source_start = new Position(source_start_position);
} catch (InvalidPositionException e) {
switch (e.getThisCause()) {
case LINE_NUMBER_ZERO:
throw new InvalidCRTDataException(WARN_INVALID_START_LINE_NUMBER);
case COLUMN_NUMBER_ZERO:
throw new InvalidCRTDataException(WARN_INVALID_START_COLUMN_NUMBER);
default:
assert false;
}
}
Position source_end = null;
try {
source_end = new Position(source_end_position);
} catch (InvalidPositionException e) {
switch (e.getThisCause()) {
case LINE_NUMBER_ZERO:
throw new InvalidCRTDataException(WARN_INVALID_END_LINE_NUMBER);
case COLUMN_NUMBER_ZERO:
throw new InvalidCRTDataException(WARN_INVALID_END_COLUMN_NUMBER);
default:
assert false;
}
}
Range range = null;
try {
range = new Range(source_start, source_end);
} catch (InvalidRangeException e) {
final Cause cause = e.getThisCause();
switch (cause) {
case END_BEFORE_START:
throw new InvalidCRTDataException(
WARN_END_BEFORE_START, source_start.toString(), source_end.toString());
case START_UNDEFINED:
throw new InvalidCRTDataException(WARN_START_UNDEFINED);
case END_UNDEFINED:
throw new InvalidCRTDataException(WARN_END_UNDEFINED);
default:
throw new UnsupportedOperationException(
String.format("cannot convert %s into an InvalidCRTDataException", cause));
}
} finally {
this.source_positions = range;
}
this.flags = new CRTFlags(flags);
}
public CRTFlags getFlags() {
return this.flags;
}
/**
* Tests whether the given index lies within the range of this data.
*
* @param pc the index to test
* @return whether the given index lies within the range of this data or not.
*/
public boolean isInRange(int pc) {
return pc_start_index <= pc && pc <= pc_end_index;
}
/**
* Tests whether the given data is consistently with this data. To be consistently with another
* data this data has to be equal or more precise. Otherwise the datas are contradictory.
*
* @param d the data to test with
* @return whether the given data is consistently.
*/
public boolean matches(CRTData d) {
return d != null && (isMorePrecise(d) || d.isMorePrecise(this));
}
/**
* Tests whether this data is equal to or more precise than the given data. This data is equal or
* more precise if the program counter range and the source range lie within the range of the
* given data. If this data or the parameter have no source positions, only program counter range
* decides.
*
* @param d the data to test with
* @return whether this data is equal to or more precise than the given one.
*/
public boolean isMorePrecise(CRTData d) {
return d != null
&& pc_start_index >= d.pc_start_index
&& pc_end_index <= d.pc_end_index
&& (source_positions.isWithin(d.source_positions) || hasNoPosition() || d.hasNoPosition());
}
/**
* Returns {@code true} if this data has no source position.
*
* @return {@code true} if this data has no source position.
*/
private boolean hasNoPosition() {
return source_positions.isUndefined();
}
/**
* Returns the source positions.
*
* @return The returned array consists of four positions: the start line number, the start column
* number, the end line number, the end column number
*/
public Range getSourceInfo() {
return source_positions;
}
@Override
public String toString() {
return "(Range [pc]: "
+ pc_start_index
+ '-'
+ pc_end_index
+ ") => "
+ source_positions.toString();
}
}
| 7,810
| 34.995392
| 124
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.