我希望能够替换一些类并将其添加到已经运行的JVM中。我读到我需要使用CreateRemoteThread,但是我没有完全理解它。我阅读了有关如何执行此操作的文章(Software RnD),但无法弄清楚它的作用以及原因。除此之外,它仅引入新的类,而不会更改现有的类。我该如何使用C ++?

最佳答案

您甚至不需要CreateRemoteThread-有一种官方方法来连接到远程JVM,并使用Attach API替换加载的类。


您需要一个Java Agent调用Instrumentation.redefineClasses

public static void agentmain(String args, Instrumentation instr) throws Exception {
    Class oldClass = Class.forName("org.pkg.MyClass");
    Path newFile = Paths.get("/path/to/MyClass.class");
    byte[] newData = Files.readAllBytes(newFile);

    instr.redefineClasses(new ClassDefinition(oldClass, newData));
}


您必须添加具有MANIFEST.MF属性的Agent-Class并将代理打包到jar文件中。





然后使用动态附加将代理jar注入正在运行的VM(进程ID = pid)。

import com.sun.tools.attach.VirtualMachine;
...

    VirtualMachine vm = VirtualMachine.attach(pid);
    try {
        vm.loadAgent(agentJarPath, options);
    } finally {
        vm.detach();
    }


the article中有更多详细信息。


如果您坚持使用C / C ++而不是Java API,则可以查看我的jattach实用程序。

关于c++ - 在运行的JVM中注入(inject)Jar并替换类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43157989/

10-12 00:12
查看更多