Search code examples
javabytecodejava-bytecode-asm

Polymorphic call: resolving target method from bytecode


Given Java bytecode and ASM bytecode analysis framework,
how can I resolve a target method when polymorphic call occurs?

For instance:

class ClassA { 
    public void foo() {…}
}

class ClassB extends ClassA {
    public void foo() {…}
}
…
ClassA inst = new ClassB();
inst.foo();

The following bytecode is generated for the latter line:

…
INVOKEVIRTUAL ClassA.foo()V
…

This instructure targets a parent method.
But the actual method is ClassB.foo().

How can I resolve the "real" method that will be called?


Solution

  • In general: you can't. It's undecidable. But there are special case which can be analyzed. One way to do it is to apply a points-to-analysis. Which usually is a whole program analysis. In the presence of bytecode rewriting and or reflection additional problems occur.

    So basically you have to decide how much effort you are willing to spend. You have the following options:

    • You perform an ad-hoc analysis which would be able to detect your trivial case from above.
    • You apply a lot of theory of static analysis to this problem.
    • You find someone else who already performed the second option.

    What do you want to achieve in the first place?