Reputation: 83
I am using ASM to monitor field accesses (putfield and getfield). (For putfield,) My problem is that when the top of stack is a basic value (X) and the second top is an object reference (Y), how can I insert some Java instructions to invoke my method with the second object reference (Y) as its one argument and, after returning from my method, the two (X and Y) will not be lost?
In summary, how can I access the second top object reference without affecting the top value of the stack (after my access) in Java at Java bytecode level?
I want to use dup, but it can only handle the top value of the stack. So, it works for the getfield since there isn't a value and I can directly dup it.
Is there a better way to do that?
Thanks.
Upvotes: 3
Views: 845
Reputation: 2694
Case 1... The basic value is not Long or Double -
Lets say that the top of the stack looks something like this...
Y,X (the rightmost element being the top of the stack.)
The following sequence of instructions should do the trick...
DUP2
POP
The DUP2 will duplicate the top two instructions. Thus resulting in Y,X,Y,X. The POP will pop the X (the basic value) off. And you will be left with Y,X,Y. And then you can invoke your function.
Case 2... The basic value is a Long or Double -
The the top of the stack look like this... Y,X1,X2. For this you can use the following sequence of instructions...
DUP2_X1 // this will result in X1,X2,Y,X1,X2
POP2 // this will result in X1,X2,Y
DUP_X2 // this will result in Y,X1,X2,Y
Thus again, you have Y on top of the stack. And everything below it is just as it was before.
In both these cases, what you finally get is the Object Ref (Y) on top of the stack, allowing you to use it for any operation of your choice, e.g. a method call. Once that operation is complete, the state of the stack is exactly as it was before you carried out the manipulations.
Upvotes: 3