Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

java - Attach to already running JVM

Is there a way to attach to an already running JVM?

For example, in JNI you can use JNI_CreateJavaVM to create a VM and run a jar and inspect all its classes..

However, if the jar is already running, I cannot find a way to attach to its JVM and communicate with its classes or get its env pointer..

Another problem is that if the jar loads my native library (.dll) and I want to create a JVM inside the .dll, I cannot.. Nor can I attach the jar's current JVM either without the jar calling my function..

Example on the Java side:

class Foo
{
    static {loadLibrary("Foo")}
}

on the C++ side:

void Foo()
{
    //CreateJVM
    //Attach to the current process..
    //Call function from the jar that loaded me.
}

This cannot be done without the jar calling Foo first.

Any ideas? Is there no way to get the current JVM or to attach to it or an external jvm instance?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes you can.

1) Inject a DLL in the process hosting the JVM (eg, java.exe, or javaw.exe, or iexplore.exe). A common injection technique is to use SetWindowsHookEx

2) In the DLL, get the module handle of the jvm.dll using GetModuleHandle

3) Get the address of the JNI_GetCreatedJavaVMs function, using GetProcAddress

4) Call the function and, if successfull, attach your thread to the first JVM found, using the AttachCurrentThread function pointer from the JavaVM struture.

5) Done.

Usefull link: The Invocation API


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...