注入 jar 并替换正在运行的 JVM 中的类

Inject Jar and replace classes in running JVM

本文关键字:JVM 运行 jar 替换 注入      更新时间:2023-10-16

我希望能够替换一些类并将其添加到已经在运行的JVM中。我读到我需要使用CreateRemoteThread,但我不完全明白。我读了这篇关于如何做到这一点(软件 RnD(的文章,但我无法弄清楚它的作用和原因。除此之外,它只引入了新类,但不会更改现有类。我怎样才能用C++做到这一点?

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

  1. 您需要一个调用 Instrumentation.redefineClasses 的 Java 代理。

    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));
    }
    

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

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

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

    文章中有更多细节。

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