多态调用:从字节码解析目标方法

发布于 2024-12-17 15:10:02 字数 392 浏览 5 评论 0原文

给出Java字节码和ASM字节码分析框架,
发生多态调用时如何解析目标方法?

例如:

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

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

为后一行生成以下字节码:

…
INVOKEVIRTUAL ClassA.foo()V
…

该结构针对父方法。
但实际的方法是ClassB.foo()

如何解析将被调用的“真实”方法?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

燃情 2024-12-24 15:10:03

一般来说:你不能。这是无法确定的。但也有特殊情况可以分析。一种方法是应用points-to-analysis。这通常是整个程序分析。在存在字节码重写和/或反射的情况下,会出现其他问题。

所以基本上你必须决定你愿意花费多少努力。您有以下选择:

  • 您执行临时分析,这将能够从上面检测您的琐碎案例。
  • 您将大量静态分析理论应用于这个问题。
  • 您找到已经执行了第二个选项的其他人。

您首先想实现什么目标?

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?

蓝戈者 2024-12-24 15:10:03

我对ASM一无所知,但我怀疑你也不会。字节码在运行时解释。因此,所调用的方法将在运行时调用。因此,根据应用程序的状态,可能会在 ClassBClassC 上调用 foo()

免责声明如果 ASM 允许询问正在运行的 JVM(如调试器),那么您应该能够这样做!

I don't know anything about ASM, but I suspect that you can't. Bytecode is interpreted at runtime. As such, the method that's invoked will be invoked at runtime. So foo() might be invoked on ClassB and on ClassC depending on the state of the application.

Disclaimer if ASM allows interrogation of a running JVM (like a debugger) then you should be able to!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文