在运行的JVM中注入Jar并替换类 [英] Inject Jar and replace classes in running JVM

查看:405
本文介绍了在运行的JVM中注入Jar并替换类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够替换一些类并将其添加到已经运行的JVM中。我读到我需要使用 CreateRemoteThread ,但是我没有完全理解它。我阅读了有关如何操作的信息(软件RnD ),但我不知道它的作用和原因。除此之外,它仅引入新的类,而不会更改现有的类。我该如何使用C ++?

I want to be able to replace and add some classes to an already running JVM. I read that I need to use CreateRemoteThread, but I don't completely get it. I read this post on how to do it (Software RnD), but I can't figure out what it does and why. Besides that, it only introduces new classes, but doesn't change existing ones. How can I do it with C++?

推荐答案

您甚至不需要 CreateRemoteThread -有一种官方方法可以连接到远程JVM并使用附加API

You don't even need CreateRemoteThread - there is an official way to connect to remote JVM and replace loaded classes by using Attach API.


  1. 您需要 Java代理会调用 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文件中。

You'll have to add MANIFEST.MF with Agent-Class attribute and pack the agent into a jar file.


  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 实用工具。

If you insist on using C/C++ instead of Java API, you may look at my jattach utility.

这篇关于在运行的JVM中注入Jar并替换类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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