Wednesday, April 16, 2008

Debugging JNI code using Eclipse and Visual Studio

Debugging Java Native Interface code (JNI) can be quite an adventure, but fortunately it works quite nice when you have Eclipse and Visual Studio (and preferrably at least 2 monitors). I have Eclipse on the primary monitor, and Visual Studio on the secondary. This is how it goes:

  1. Start your java program, with a breakpoint before entering the native method you want to debug. You probably want to break after the native code has been loaded, but you don't have to.
  2. Switch to Visual Studio, and bring up the "Attach to process" dialog (Ctrl-Alt-P). Select the java process (javaw.exe or java.exe) by typing "j" (possible several times, epending on how many processes you have starting with the letter "j"). Press return. Visual Studio should now switch to debugging and the title bar should include the test "(Running)", indicating that you are debugging a running process.
  3. Set a breakpoint to cause Visual Studio to stop in your native code.
  4. Switch back to Eclipse, and start running. When eclipse enters your native code, Visual Studio will break the debugged java program. (Eclipse may note that the debugged program is not responding, since it is suspended by Visual Studio).
  5. When you're done debugging, you can "release" the java-program using the "Stop Debugging" command in Visual Studio. This will cause the java program to continue running normally (and terminate, unless Eclipse has a breakpoint on it).

Some things you may want to pay special attention to:

  • Eclipse and Visual Studio have different shortcuts for run/step/step-over, etc. This is a major pain, and I think my muscle memory is permanently damaged when it comes to learning them.
  • You need to keep track of who is debugging. This can be confusing.

People are working on making JDT and CDT cooperate in debugging JNI code, allowing seamless stepping in and out of Java/JNI code and integrated debugger views (callstack with both Java and native frames displayed, for example), but it is still in the early prototyping phase.