I want to obtain index number of a bytecode in a method when visiting this bytecode. For example, given a bytecode sequence below, the index number for the invokevirtual is 7 (The method body is visited with SKIP_DEBUG).
public calculate(IILjava/lang/String;J)J
L0
LINENUMBER 17 L0
ICONST_3 //0
ISTORE 6 //1
L1
LINENUMBER 18 L1
LDC 10.0 //2
DSTORE 7 //3
L2
LINENUMBER 19 L2
ALOAD 0 //4
GETFIELD code/sxu/asm/Callee._call2 : Lcode/sxu/asm/Callee2; //5
LDC "xushijie" //6
INVOKEVIRTUAL code/sxu/asm/Callee2.sayHello (Ljava/lang/String;)I //7
ISTORE 9
}
My code is like:
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS);
cr.accept(new SomeMethodVisitor(api, owner, access, name, desc, cw.visitMethod(access, name, desc, owner, null)), SKIP_DEBUG);
class SomeMethodVisitor extends MethodVisitor{
@Override
public void visitMethodInsn(final int opcode, final String owner,
final String name, final String desc, final boolean itf) {
int index = ??? //Get the current bytecode index number here.
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
}
This is relative easy with Tree-based ASM API, where we can use:
class MethodNode{
public InsnList instructions;
}
But I do not have a good solution inside of event-based mode. Also, it is not a good solution to override all visitXXX
methods of MethodVisitor and counts all bytecodes that have already past.