zaz
zaz

Reputation: 505

Access variable/constant values in method call

I want to view arguments for method calls. So if I call foo:

x = 4;

y = 5;

...

foo(x, y, 20, 25);

I want to print the arguments(4,5,20,25) I understand these arguments are pushed onto the stack before the method is invoked. How do I get the value(if initialized or a constant) from the method's local variable array?

visitVarInsn() and VarInsnNode do not have a way to lookup the actual value from the array.

Do I need to use an Analyzer and Interpreter to do this, or is there an easier way?

EDIT: Figured out how to do this. I modified BasicValue and BasicInterpreter to account for bytecode instruction arguments. So Values representing instructions like BIPUSH contain information about the value being pushed, instead of only type information. Frames are examined the same way with an Analyzer

Upvotes: 1

Views: 270

Answers (2)

henry
henry

Reputation: 6096

Constant numeric values passed directly to the method call (20 and 25) are easy to retrieve statically - they will result in push instructions that you can read in visitIntInsn. Smaller values will result in const instructions you can catch with visitInsn, large values can be caught with visitLdcInsn.

I don't believe it is generally possible to determine the values bound to variables at the point of the method call statically. You will need to do a dataflow analysis (using Analyzer and Interpreter as you suggest) which should be able to provide the range of possible values for each variable. This won't give you definite values in the general case, but will in the specific cases of variables that are only assigned once or assigned multiple times, but unconditionally.

Upvotes: 1

jdevelop
jdevelop

Reputation: 12296

it's not related to asm and bytecode manipulation, but just in case -

if method foo belongs to a class with interface method foo you may use Proxy to wrap interface implementation and intercept method names.

Also, you may found this answer useful for ASM bytecode modifications.

Upvotes: 0

Related Questions