从JVM获取运行的字节码 [英] fetching running bytecode from a JVM

查看:121
本文介绍了从JVM获取运行的字节码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出在将函数加载到JVM之后是否可以获得字节码.

I am trying to find out if it is possible to get the bytecode of a function after it was loaded to the JVM.

我知道我可以使用ClassLoder从.class文件中获取代码,也可以使用Instrumentation对其进行操作,但这不是问题所在.

I know I can get the code from the .class file using ClassLoder and I can manipulate it using Instrumentation, but this is not the issue here.

假设我有一个名为Test.class的已编译Java程序并且运行了,它的字节码将被加载到JVM中,从这一点上我可以得到字节码吗?

Suppose I have a compiled Java program called Test.class and I run, its bytecode will be loaded the JVM, from this point can I get the bytecode?

按照我想再次指出的答案,我的目的是检查在JVM上运行的代码,但我无权访问其编译文件.

Following the answers I want to point again, my intention is to inspect code which is running on the JVM but I dont have access to its compiled file.

推荐答案

HotSpot可服务性代理可以做到这一点!

这里是一个示例,该示例如何获取test.HelloWorld类中的远程main(String[])方法的字节码:

Here is an example how to get the bytecode of remote main(String[]) method in test.HelloWorld class:

import sun.jvm.hotspot.oops.InstanceKlass;
import sun.jvm.hotspot.oops.Method;
import sun.jvm.hotspot.runtime.VM;
import sun.jvm.hotspot.tools.Tool;

public class GetBytecode extends Tool {

    @Override
    public void run() {
        VM.getVM().getSystemDictionary().allClassesDo(klass -> {
            if (klass.getName().asString().equals("test/HelloWorld")) {
                Method method = ((InstanceKlass) klass).findMethod("main", "([Ljava/lang/String;)V");
                for (byte bc : method.getByteCode()) {
                    System.out.printf("%02x ", bc);
                }
            }
        });
    }

    public static void main(String[] args) {
        new GetBytecode().execute(args);
    }
}

运行java -cp <JDK_HOME>/lib/sa-jdi.jar:. GetBytecode <PID>

这篇关于从JVM获取运行的字节码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆