在运行JVM中注入Jar并替换类

时间:2017-04-01 14:17:57

标签: c++ jvm java-native-interface code-injection

我希望能够替换并向已经运行的JVM添加一些类。我读到我需要使用CreateRemoteThread,但我还没有完全理解它。我读了这篇关于如何做的帖子(Software RnD),但我无法弄清楚它的作用和原因。除此之外,它只引入了新的类,但并没有改变现有的类。我怎么能用C ++做到这一点?

1 个答案:

答案 0 :(得分:0)

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

  1. 您需要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文件中。

    1. 然后使用动态附加将代理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中的更多细节。

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