0
我希望能夠替換某些類並將其添加到已運行的JVM中。我讀到我需要使用CreateRemoteThread
,但我不完全明白。我閱讀這篇文章,如何做到這一點(Software RnD),但我無法弄清楚它的功能和原因。除此之外,它只引入新類,但不會改變現有類。我怎樣才能用C++做到這一點?注入Jar並替換正在運行的JVM中的類
我希望能夠替換某些類並將其添加到已運行的JVM中。我讀到我需要使用CreateRemoteThread
,但我不完全明白。我閱讀這篇文章,如何做到這一點(Software RnD),但我無法弄清楚它的功能和原因。除此之外,它只引入新類,但不會改變現有類。我怎樣才能用C++做到這一點?注入Jar並替換正在運行的JVM中的類
你甚至不需要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文件。
然後使用動態連接以注入所述試劑水罐裏的運行中的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
效用。
你需要創建一個包含你想要的代碼的DLL(IE:用於替換當前JVM中的Java類的代碼)。當dll加載時,它會創建一個加載你的jar文件的線程。然後將該dll注入到JVM中。 – Brandon