I am using the ASM bytecode manipulation framework to perform static analysis on Java code. I wish to detect when fields of an object are reassigned, i.e. when this kind of code occurs:
class MyObject {
private int value;
void setValue(int newValue) { this.value = newValue; }
}
Using the following code (in a class implementing ClassVisitor
) can detect the above situation:
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
if(opcode == Opcodes.PUTFIELD) {
// do whatever here
}
}
However, this code is called regardless of the object which owns the field. I would like to find the more specific case where the PUTFIELD operation is executed on the this
object. For example, I want to distinguish between the first code snippet, and code such as this:
public MyObject createNewObjectWithDifferentField() {
MyObject newObject = new MyObject();
newObject.value = 43;
return newObject;
}
In the above case, the PUTFIELD operation is still executed, but here it's on a local variable (newObject
) rather than the this
object. This will depend on the state of the stack at the time of the assignment, but I have came across a few different scenarios where the bytecode is totally different, and I'm looking for ways to handle this complexity.
How do I check that PUTFIELD is reassigning a field belonging to this
object?
Edit
I'm using ASM to perform analysis only, rather than instrumenting existing bytecode. Preferably I'd like to find a way of discovering this without altering the bytecode, if possible.