package org.aspectj.apache.bcel.classfile;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnos;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeInvisAnnos;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeInvisParamAnnos;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeParamAnnos;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisAnnos;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisParamAnnos;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.util.ByteSequence;
public abstract class Utility {
private static boolean wide = false;
public static final String accessToString(int access_flags) {
return accessToString(access_flags, false);
}
public static final String accessToString(int access_flags, boolean for_class) {
StringBuffer buf = new StringBuffer();
int p = 0;
for (int i = 0; p < Constants.MAX_ACC_FLAG; i++) {
p = pow2(i);
if ((access_flags & p) != 0) {
if (for_class && ((p == Constants.ACC_SUPER) || (p == Constants.ACC_INTERFACE))) {
continue;
}
buf.append(Constants.ACCESS_NAMES[i]).append(" ");
}
}
return buf.toString().trim();
}
public static final String classOrInterface(int access_flags) {
return ((access_flags & Constants.ACC_INTERFACE) != 0) ? "interface" : "class";
}
public static final String codeToString(byte[] code, ConstantPool constant_pool, int index, int length, boolean verbose) {
StringBuffer buf = new StringBuffer(code.length * 20);
ByteSequence stream = new ByteSequence(code);
try {
for (int i = 0; i < index; i++) {
codeToString(stream, constant_pool, verbose);
}
for (int i = 0; stream.available() > 0; i++) {
if ((length < 0) || (i < length)) {
String indices = fillup(stream.getIndex() + ":", 6, true, ' ');
buf.append(indices + codeToString(stream, constant_pool, verbose) + '\n');
}
}
} catch (IOException e) {
System.out.println(buf.toString());
e.printStackTrace();
throw new ClassFormatException("Byte code error: " + e);
}
return buf.toString();
}
public static final String codeToString(byte[] code, ConstantPool constant_pool, int index, int length) {
return codeToString(code, constant_pool, index, length, true);
}
public static final String codeToString(ByteSequence bytes, ConstantPool constant_pool) throws IOException {
return codeToString(bytes, constant_pool, true);
}
public static final String compactClassName(String str) {
return compactClassName(str, true);
}
public static final String compactClassName(String str, String prefix, boolean chopit) {
str = str.replace('/', '.');
if (chopit) {
int len = prefix.length();
if (str.startsWith(prefix)) {
String result = str.substring(len);
if (result.indexOf('.') == -1) {
str = result;
}
}
}
return str;
}
public static final String compactClassName(String str, boolean chopit) {
return compactClassName(str, "java.lang.", chopit);
}
public static final String methodSignatureToString(String signature, String name, String access) {
return methodSignatureToString(signature, name, access, true);
}
public static final String methodSignatureToString(String signature, String name, String access, boolean chopit) {
return methodSignatureToString(signature, name, access, chopit, null);
}
public static final String methodSignatureToString(String signature, String name, String access, boolean chopit,
LocalVariableTable vars) throws ClassFormatException {
StringBuffer buf = new StringBuffer("(");
String type;
int index;
int var_index = (access.indexOf("static") >= 0) ? 0 : 1;
try {
if (signature.charAt(0) != '(') {
throw new ClassFormatException("Invalid method signature: " + signature);
}
index = 1;
while (signature.charAt(index) != ')') {
ResultHolder rh = signatureToStringInternal(signature.substring(index), chopit);
String param_type = rh.getResult();
buf.append(param_type);
if (vars != null) {
LocalVariable l = vars.getLocalVariable(var_index);
if (l != null) {
buf.append(" " + l.getName());
}
} else {
buf.append(" arg" + var_index);
}
if ("double".equals(param_type) || "long".equals(param_type)) {
var_index += 2;
} else {
var_index++;
}
buf.append(", ");
index += rh.getConsumedChars();
}
index++;
type = signatureToString(signature.substring(index), chopit);
} catch (StringIndexOutOfBoundsException e) {
throw new ClassFormatException("Invalid method signature: " + signature);
}
if (buf.length() > 1) {
buf.setLength(buf.length() - 2);
}
buf.append(")");
return access + ((access.length() > 0) ? " " : "") +
type + " " + name + buf.toString();
}
public static final String replace(String str, String old, String new_) {
int index, old_index;
StringBuffer buf = new StringBuffer();
try {
index = str.indexOf(old);
if (index != -1) {
old_index = 0;
while ((index = str.indexOf(old, old_index)) != -1) {
buf.append(str.substring(old_index, index));
buf.append(new_);
old_index = index + old.length();
}
buf.append(str.substring(old_index));
str = buf.toString();
}
} catch (StringIndexOutOfBoundsException e) {
System.err.println(e);
}
return str;
}
public static final String signatureToString(String signature) {
return signatureToString(signature, true);
}
public static final String signatureToString(String signature, boolean chopit) {
ResultHolder rh = signatureToStringInternal(signature, chopit);
return rh.getResult();
}
public static final ResultHolder signatureToStringInternal(String signature, boolean chopit) {
int processedChars = 1;
try {
switch (signature.charAt(0)) {
case 'B':
return ResultHolder.BYTE;
case 'C':
return ResultHolder.CHAR;
case 'D':
return ResultHolder.DOUBLE;
case 'F':
return ResultHolder.FLOAT;
case 'I':
return ResultHolder.INT;
case 'J':
return ResultHolder.LONG;
case 'L': {
int index = signature.indexOf(';');
if (index < 0) {
throw new ClassFormatException("Invalid signature: " + signature);
}
if (signature.length() > index + 1 && signature.charAt(index + 1) == '>') {
index = index + 2;
}
int genericStart = signature.indexOf('<');
if (genericStart != -1) {
int genericEnd = signature.indexOf('>');
ResultHolder rh = signatureToStringInternal(signature.substring(genericStart + 1, genericEnd), chopit);
StringBuffer sb = new StringBuffer();
sb.append(signature.substring(1, genericStart));
sb.append("<").append(rh.getResult()).append(">");
ResultHolder retval = new ResultHolder(compactClassName(sb.toString(), chopit), genericEnd + 1);
return retval;
} else {
processedChars = index + 1;
ResultHolder retval = new ResultHolder(compactClassName(signature.substring(1, index), chopit), processedChars);
return retval;
}
}
case 'S':
return ResultHolder.SHORT;
case 'Z':
return ResultHolder.BOOLEAN;
case '[': {
StringBuffer brackets;
int consumedChars, n;
brackets = new StringBuffer();
for (n = 0; signature.charAt(n) == '['; n++) {
brackets.append("[]");
}
consumedChars = n;
ResultHolder restOfIt = signatureToStringInternal(signature.substring(n), chopit);
consumedChars += restOfIt.getConsumedChars();
brackets.insert(0, restOfIt.getResult());
return new ResultHolder(brackets.toString(), consumedChars);
}
case 'V':
return ResultHolder.VOID;
default:
throw new ClassFormatException("Invalid signature: `" + signature + "'");
}
} catch (StringIndexOutOfBoundsException e) {
throw new ClassFormatException("Invalid signature: " + e + ":" + signature);
}
}
public static final byte typeOfMethodSignature(String signature) throws ClassFormatException {
int index;
try {
if (signature.charAt(0) != '(') {
throw new ClassFormatException("Invalid method signature: " + signature);
}
index = signature.lastIndexOf(')') + 1;
return typeOfSignature(signature.substring(index));
} catch (StringIndexOutOfBoundsException e) {
throw new ClassFormatException("Invalid method signature: " + signature);
}
}
private static final short byteToShort(byte b) {
return (b < 0) ? (short) (256 + b) : (short) b;
}
public static final String toHexString(byte[] bytes) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
short b = byteToShort(bytes[i]);
String hex = Integer.toString(b, 0x10);
if (b < 0x10) {
buf.append('0');
}
buf.append(hex);
if (i < bytes.length - 1) {
buf.append(' ');
}
}
return buf.toString();
}
public static final String format(int i, int length, boolean left_justify, char fill) {
return fillup(Integer.toString(i), length, left_justify, fill);
}
public static final String fillup(String str, int length, boolean left_justify, char fill) {
int len = length - str.length();
char[] buf = new char[(len < 0) ? 0 : len];
for (int j = 0; j < buf.length; j++) {
buf[j] = fill;
}
if (left_justify) {
return str + new String(buf);
} else {
return new String(buf) + str;
}
}
public static final String convertString(String label) {
char[] ch = label.toCharArray();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < ch.length; i++) {
switch (ch[i]) {
case '\n':
buf.append("\\n");
break;
case '\r':
buf.append("\\r");
break;
case '\"':
buf.append("\\\"");
break;
case '\'':
buf.append("\\'");
break;
case '\\':
buf.append("\\\\");
break;
default:
buf.append(ch[i]);
break;
}
}
return buf.toString();
}
public static Collection<RuntimeAnnos> getAnnotationAttributes(ConstantPool cp, List<AnnotationGen> annotations) {
if (annotations.size() == 0) {
return null;
}
try {
int countVisible = 0;
int countInvisible = 0;
for (AnnotationGen a : annotations) {
if (a.isRuntimeVisible()) {
countVisible++;
} else {
countInvisible++;
}
}
ByteArrayOutputStream rvaBytes = new ByteArrayOutputStream();
ByteArrayOutputStream riaBytes = new ByteArrayOutputStream();
DataOutputStream rvaDos = new DataOutputStream(rvaBytes);
DataOutputStream riaDos = new DataOutputStream(riaBytes);
rvaDos.writeShort(countVisible);
riaDos.writeShort(countInvisible);
for (AnnotationGen a : annotations) {
if (a.isRuntimeVisible()) {
a.dump(rvaDos);
} else {
a.dump(riaDos);
}
}
rvaDos.close();
riaDos.close();
byte[] rvaData = rvaBytes.toByteArray();
byte[] riaData = riaBytes.toByteArray();
int rvaIndex = -1;
int riaIndex = -1;
if (rvaData.length > 2) {
rvaIndex = cp.addUtf8("RuntimeVisibleAnnotations");
}
if (riaData.length > 2) {
riaIndex = cp.addUtf8("RuntimeInvisibleAnnotations");
}
List<RuntimeAnnos> newAttributes = new ArrayList<RuntimeAnnos>();
if (rvaData.length > 2) {
newAttributes.add(new RuntimeVisAnnos(rvaIndex, rvaData.length, rvaData, cp));
}
if (riaData.length > 2) {
newAttributes.add(new RuntimeInvisAnnos(riaIndex, riaData.length, riaData, cp));
}
return newAttributes;
} catch (IOException e) {
System.err.println("IOException whilst processing annotations");
e.printStackTrace();
}
return null;
}
public static Attribute[] getParameterAnnotationAttributes(ConstantPool cp, List<AnnotationGen>[] vec) {
int visCount[] = new int[vec.length];
int totalVisCount = 0;
int invisCount[] = new int[vec.length];
int totalInvisCount = 0;
try {
for (int i = 0; i < vec.length; i++) {
List<AnnotationGen> l = vec[i];
if (l != null) {
for (AnnotationGen element : l) {
if (element.isRuntimeVisible()) {
visCount[i]++;
totalVisCount++;
} else {
invisCount[i]++;
totalInvisCount++;
}
}
}
}
ByteArrayOutputStream rvaBytes = new ByteArrayOutputStream();
DataOutputStream rvaDos = new DataOutputStream(rvaBytes);
rvaDos.writeByte(vec.length);
for (int i = 0; i < vec.length; i++) {
rvaDos.writeShort(visCount[i]);
if (visCount[i] > 0) {
List<AnnotationGen> l = vec[i];
for (AnnotationGen element : l) {
if (element.isRuntimeVisible()) {
element.dump(rvaDos);
}
}
}
}
rvaDos.close();
ByteArrayOutputStream riaBytes = new ByteArrayOutputStream();
DataOutputStream riaDos = new DataOutputStream(riaBytes);
riaDos.writeByte(vec.length);
for (int i = 0; i < vec.length; i++) {
riaDos.writeShort(invisCount[i]);
if (invisCount[i] > 0) {
List<AnnotationGen> l = vec[i];
for (AnnotationGen element : l) {
if (!element.isRuntimeVisible()) {
element.dump(riaDos);
}
}
}
}
riaDos.close();
byte[] rvaData = rvaBytes.toByteArray();
byte[] riaData = riaBytes.toByteArray();
int rvaIndex = -1;
int riaIndex = -1;
if (totalVisCount > 0) {
rvaIndex = cp.addUtf8("RuntimeVisibleParameterAnnotations");
}
if (totalInvisCount > 0) {
riaIndex = cp.addUtf8("RuntimeInvisibleParameterAnnotations");
}
List<RuntimeParamAnnos> newAttributes = new ArrayList<RuntimeParamAnnos>();
if (totalVisCount > 0) {
newAttributes.add(new RuntimeVisParamAnnos(rvaIndex, rvaData.length, rvaData, cp));
}
if (totalInvisCount > 0) {
newAttributes.add(new RuntimeInvisParamAnnos(riaIndex, riaData.length, riaData, cp));
}
return newAttributes.toArray(new Attribute[] {});
} catch (IOException e) {
System.err.println("IOException whilst processing parameter annotations");
e.printStackTrace();
}
return null;
}
public static class ResultHolder {
private String result;
private int consumed;
public static final ResultHolder BYTE = new ResultHolder("byte", 1);
public static final ResultHolder CHAR = new ResultHolder("char", 1);
public static final ResultHolder DOUBLE = new ResultHolder("double", 1);
public static final ResultHolder FLOAT = new ResultHolder("float", 1);
public static final ResultHolder INT = new ResultHolder("int", 1);
public static final ResultHolder LONG = new ResultHolder("long", 1);
public static final ResultHolder SHORT = new ResultHolder("short", 1);
public static final ResultHolder BOOLEAN = new ResultHolder("boolean", 1);
public static final ResultHolder VOID = new ResultHolder("void", 1);
public ResultHolder(String s, int c) {
result = s;
consumed = c;
}
public String getResult() {
return result;
}
public int getConsumedChars() {
return consumed;
}
}
public static final byte typeOfSignature(String signature) throws ClassFormatException {
try {
switch (signature.charAt(0)) {
case 'B':
return Constants.T_BYTE;
case 'C':
return Constants.T_CHAR;
case 'D':
return Constants.T_DOUBLE;
case 'F':
return Constants.T_FLOAT;
case 'I':
return Constants.T_INT;
case 'J':
return Constants.T_LONG;
case 'L':
return Constants.T_REFERENCE;
case '[':
return Constants.T_ARRAY;
case 'V':
return Constants.T_VOID;
case 'Z':
return Constants.T_BOOLEAN;
case 'S':
return Constants.T_SHORT;
default:
throw new ClassFormatException("Invalid method signature: " + signature);
}
} catch (StringIndexOutOfBoundsException e) {
throw new ClassFormatException("Invalid method signature: " + signature);
}
}
public static final byte typeOfSignature(char c) throws ClassFormatException {
switch (c) {
case 'B':
return Constants.T_BYTE;
case 'C':
return Constants.T_CHAR;
case 'D':
return Constants.T_DOUBLE;
case 'F':
return Constants.T_FLOAT;
case 'I':
return Constants.T_INT;
case 'J':
return Constants.T_LONG;
case 'L':
return Constants.T_REFERENCE;
case '[':
return Constants.T_ARRAY;
case 'V':
return Constants.T_VOID;
case 'Z':
return Constants.T_BOOLEAN;
case 'S':
return Constants.T_SHORT;
default:
throw new ClassFormatException("Invalid type of signature: " + c);
}
}
public static final String codeToString(ByteSequence bytes, ConstantPool constant_pool, boolean verbose) throws IOException {
short opcode = (short) bytes.readUnsignedByte();
int default_offset = 0, low, high, npairs;
int index, vindex, constant;
int[] match, jump_table;
int no_pad_bytes = 0, offset;
StringBuffer buf = new StringBuffer(Constants.OPCODE_NAMES[opcode]);
if ((opcode == Constants.TABLESWITCH) || (opcode == Constants.LOOKUPSWITCH)) {
int remainder = bytes.getIndex() % 4;
no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder;
for (int i = 0; i < no_pad_bytes; i++) {
byte b = bytes.readByte();
if (b != 0) {
System.err.println("Warning: Padding byte != 0 in " + Constants.OPCODE_NAMES[opcode] + ":" + b);
}
}
default_offset = bytes.readInt();
}
switch (opcode) {
case Constants.TABLESWITCH:
low = bytes.readInt();
high = bytes.readInt();
offset = bytes.getIndex() - 12 - no_pad_bytes - 1;
default_offset += offset;
buf.append("\tdefault = " + default_offset + ", low = " + low + ", high = " + high + "(");
jump_table = new int[high - low + 1];
for (int i = 0; i < jump_table.length; i++) {
jump_table[i] = offset + bytes.readInt();
buf.append(jump_table[i]);
if (i < jump_table.length - 1) {
buf.append(", ");
}
}
buf.append(")");
break;
case Constants.LOOKUPSWITCH: {
npairs = bytes.readInt();
offset = bytes.getIndex() - 8 - no_pad_bytes - 1;
match = new int[npairs];
jump_table = new int[npairs];
default_offset += offset;
buf.append("\tdefault = " + default_offset + ", npairs = " + npairs + " (");
for (int i = 0; i < npairs; i++) {
match[i] = bytes.readInt();
jump_table[i] = offset + bytes.readInt();
buf.append("(" + match[i] + ", " + jump_table[i] + ")");
if (i < npairs - 1) {
buf.append(", ");
}
}
buf.append(")");
}
break;
case Constants.GOTO:
case Constants.IFEQ:
case Constants.IFGE:
case Constants.IFGT:
case Constants.IFLE:
case Constants.IFLT:
case Constants.JSR:
case Constants.IFNE:
case Constants.IFNONNULL:
case Constants.IFNULL:
case Constants.IF_ACMPEQ:
case Constants.IF_ACMPNE:
case Constants.IF_ICMPEQ:
case Constants.IF_ICMPGE:
case Constants.IF_ICMPGT:
case Constants.IF_ICMPLE:
case Constants.IF_ICMPLT:
case Constants.IF_ICMPNE:
buf.append("\t\t#" + ((bytes.getIndex() - 1) + bytes.readShort()));
break;
case Constants.GOTO_W:
case Constants.JSR_W:
buf.append("\t\t#" + ((bytes.getIndex() - 1) + bytes.readInt()));
break;
case Constants.ALOAD:
case Constants.ASTORE:
case Constants.DLOAD:
case Constants.DSTORE:
case Constants.FLOAD:
case Constants.FSTORE:
case Constants.ILOAD:
case Constants.ISTORE:
case Constants.LLOAD:
case Constants.LSTORE:
case Constants.RET:
if (wide) {
vindex = bytes.readUnsignedShort();
wide = false;
} else {
vindex = bytes.readUnsignedByte();
}
buf.append("\t\t%" + vindex);
break;
case Constants.WIDE:
wide = true;
buf.append("\t(wide)");
break;
case Constants.NEWARRAY:
buf.append("\t\t<" + Constants.TYPE_NAMES[bytes.readByte()] + ">");
break;
case Constants.GETFIELD:
case Constants.GETSTATIC:
case Constants.PUTFIELD:
case Constants.PUTSTATIC:
index = bytes.readUnsignedShort();
buf.append("\t\t" + constant_pool.constantToString(index, Constants.CONSTANT_Fieldref)
+ (verbose ? " (" + index + ")" : ""));
break;
case Constants.NEW:
case Constants.CHECKCAST:
buf.append("\t");
case Constants.INSTANCEOF:
index = bytes.readUnsignedShort();
buf.append("\t<" + constant_pool.constantToString(index) + ">" + (verbose ? " (" + index + ")" : ""));
break;
case Constants.INVOKESPECIAL:
case Constants.INVOKESTATIC:
case Constants.INVOKEVIRTUAL:
index = bytes.readUnsignedShort();
buf.append("\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")" : ""));
break;
case Constants.INVOKEINTERFACE:
index = bytes.readUnsignedShort();
int nargs = bytes.readUnsignedByte();
buf.append("\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")\t" : "") + nargs + "\t"
+ bytes.readUnsignedByte());
break;
case Constants.INVOKEDYNAMIC:
index = bytes.readUnsignedShort();
bytes.readUnsignedShort();
buf.append("\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")" : ""));
break;
case Constants.LDC_W:
case Constants.LDC2_W:
index = bytes.readUnsignedShort();
buf.append("\t\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")" : ""));
break;
case Constants.LDC:
index = bytes.readUnsignedByte();
buf.append("\t\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")" : ""));
break;
case Constants.ANEWARRAY:
index = bytes.readUnsignedShort();
buf.append("\t\t<" + compactClassName(constant_pool.getConstantString(index, Constants.CONSTANT_Class), false) + ">"
+ (verbose ? " (" + index + ")" : ""));
break;
case Constants.MULTIANEWARRAY: {
index = bytes.readUnsignedShort();
int dimensions = bytes.readUnsignedByte();
buf.append("\t<" + compactClassName(constant_pool.getConstantString(index, Constants.CONSTANT_Class), false) + ">\t"
+ dimensions + (verbose ? " (" + index + ")" : ""));
}
break;
case Constants.IINC:
if (wide) {
vindex = bytes.readUnsignedShort();
constant = bytes.readShort();
wide = false;
} else {
vindex = bytes.readUnsignedByte();
constant = bytes.readByte();
}
buf.append("\t\t%" + vindex + "\t" + constant);
break;
default:
if ((Constants.iLen[opcode] - 1) > 0) {
for (int i = 0; i < Constants.TYPE_OF_OPERANDS[opcode].length; i++) {
buf.append("\t\t");
switch (Constants.TYPE_OF_OPERANDS[opcode][i]) {
case Constants.T_BYTE:
buf.append(bytes.readByte());
break;
case Constants.T_SHORT:
buf.append(bytes.readShort());
break;
case Constants.T_INT:
buf.append(bytes.readInt());
break;
default:
System.err.println("Unreachable default case reached!");
System.exit(-1);
}
}
}
}
return buf.toString();
}
private static final int pow2(int n) {
return 1 << n;
}
public static String toMethodSignature(Type returnType, Type[] argTypes) {
StringBuffer buf = new StringBuffer("(");
int length = (argTypes == null) ? 0 : argTypes.length;
for (int i = 0; i < length; i++) {
buf.append(argTypes[i].getSignature());
}
buf.append(')');
buf.append(returnType.getSignature());
return buf.toString();
}
}