Thursday, December 15, 2011

Debugging JNI apps with Eclipse

Sooner or later you will find a bug in your JNI. And I am very sorry for you, because debugging JNI is not a simple task.

Native libraries are not compiled to bytecode, which implies that they cannot be debugged with standard Java Platform Debugger. That means that no matter how much you try you will have to face it - you need a second, native debugger (like gdb), which has to be attached to your vm. Then you debug your java app as long as possible in Eclipse, and at some point you switch to the other debugger (which may or may not be in Eclipse).

There was some effort in the Eclipse community to workaround this problem by launching two debuggers simultaneously - you can find results here, but as Doug Shaefer says, "it's maybe 5% of what needs to be done".


I am afraid that your problem has no easy solution.


But wait... Isn't a significant part of Eclipse (namely SWT) native? How it was written? And, what's more important, how it was debugged?


To find an answer for that it is necessary to reach to the roots of Eclipse, to the document the document dated to 2001, which states:
Internally, the SWT implementation provides separate and distinct implementations in Java for each native window system.[...] This strategy greatly simplifies implementing, debugging, and maintaining SWT because it allows all interesting development to be done in Java.
The idea behind that approach is fairly simple - the JNI layer needs to be as thin as possible, and leave no space for bugs. All the platform specific logic needs to be put in java code, so you could debug your code in Eclipse Debugger to the point where native library API is involved, which means that one of the following statements is true:

  • you have bug in your java code
  • the native library you are using has a bug

That approach solves a lot of problems, doesn't it?


Do you think other Eclipse projects that use native code has preserved that knowledge? 
I am tempted to check - are you?.


Edit: I have found out that Apache Harmony had support for debugging JNI libraries, which was then used by Intel JNI Debugger. The bad news is that it is no longer maintained, and therefore all hope in this area is lost.

No comments:

Post a Comment