Search code examples
eclipsedebuggingjvmjava-native-interface

How to debug Java code running inside native code-created JVM?


How can I use Eclipse to debug Java code running inside my own C++-created JVM? I have a native application doing the following things:

JavaVM *javaVM;
JNIEnv *jniEnv;
long flag = JNI_CreateJavaVM(&javaVM, (void**) &jniEnv, &vmArgs);
jclass jcls = env->FindClass("my/namespace/Demo");
// then run code 
[...]

I run some of my Java code from there. It is critical that I have a full blown Eclipse environment and debugger, so that I can write and debug my Java code in good conditions, on a daily basis.

My question is the following: how I can set things up?

For instance, on Windows with Visual Studio, I can:

  • create a .NET VM from within a C++ application
  • write some C# code to be run from this VM.
  • to debug my C# code, which will be hosted in a DLL (not a JAR obviously), I just have to specify that the debugger should launch the C++ application executable. C# breakpoints will automatically be reached when I start debugging. I can also use ::DebugBreak() facilities (or C# equivalents).

The only thing I have found that is remotely similar to my question is

Debug a java application without starting the JVM with debug arguments

and the question is 9 years old.

Best,

MF

NB: please note that I am NOT trying to debug JNI C++ code that is being run from a Java application. I am adding the jni tag in my question as I suspect JNI people may be able to help here.


Solution

  • In order to use full Java debugging features of Eclipse, you need to start JVM with JDWP agent, that is, pass the following JVM argument:

    -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=9999
    

    JDWP requires some JVM TI cababilities that available only at VM startup. This means you cannot attach debugger later if JVM is started without JDWP agent.

    I'd suggest to set some command-line argument or environment variable to indicate that your C++ program should add the above agentlib argument to vmArgs before creating JVM. Then you will be able to attach Java debugger to the port specified in address parameter.