thatidiotguy
thatidiotguy

Reputation: 8991

Debugging Objective C JNI code

Here is the situation:

I have a client's java project open in eclipse. It uses a JNI library created by an Xcode Objective C project. Is there any good way for me to debug the C code from eclipse when I execute the Java code? Obviously eclipse's default debugger cannot step into the jni library file and we lose the thread (thread meaning investigative thread here, not programming thread).

Any advice or input is appreciated as the code base is large enough that following the client's code will be radically faster than other options.

Thanks.

EDIT:

It should be noted that the reason that the jni library is written in Objective-C is because it is integrating with Mac OSX. It is using the Cocoa framework to integrate with the Apple speech api.

Upvotes: 5

Views: 2590

Answers (4)

Aubin
Aubin

Reputation: 14853

Here are the steps I follow to debug JNI (C/C++) under Windows, I presume ObjectiveC need the same. For Linux it's very similar (replace ; by :, %XXX% by ${XXX}...).

  1. Create a file named MyDebug.gdbinit
  2. Add these 4 lines into it:

    set args -classpath .;xxxx.jar;yyy.jar path.to.your.Main

    show args

    run

    bt

  3. launch gdb and Java: gdb "%JAVA_HOME%\bin\java"

  4. Use the GUI of the Java layer to reproduce the error
  5. If you want to execute step by step your JNI code, gdb allows you to put some breakpoints

Upvotes: 0

maba
maba

Reputation: 48045

I am not sure that I have fully understood your setup and if you require this to be done from eclipse or not. Anyhow I was interested in doing a little test program using JNI and a Cocoa library doing nothing just to try the debugging of the obj-c/c code.

I succeeded to do this setup and also to debug the code. I use IntelliJ for Java and Xcode for the objc/c part but doing the java part in eclipse is a no-brainer.

So you should be able to set up exactly my project structure and get going with the debugging. And from there you should be able to apply this knowledge to your own more complex code.

This is how I started off:

  • Create a new project in Xcode by choosing Cocoa Library.

Cocoa Library

  • Name the project libnative and make it of Type Dynamic.

Choose Options

  • Choose a place for your new project. I use ~/Development/ and skip the Create local git... part.

  • This will create a new project called lib native.xcodeproj in your selected folder. Two files have been automatically created: libnative.h and libnative.m.

  • First you must change the Project Settings.

    • Executable Extension in the Packaging section must be changed from dynlib to jnilib.
    • Framework Search Paths in the Search Paths section must be updated to point to the JNI framework: /System/Library/Frameworks/JavaVM.framework/Frameworks/JavaNativeFoundation.framework/

enter image description here

  • Now its time to add some code. Be aware that with this setup you will have to use <JavaVM/jni.h>. Update the libnative.m to look like the following code:

//
//  libnative.m
//  libnative
//
//  Created by maba on 2012-10-09.
//  Copyright (c) 2012 maba. All rights reserved.
//

#import "libnative.h"
#include <JavaVM/jni.h>

@implementation libnative

@end

#ifdef __cplusplus
extern "C" {
#endif

#ifndef VEC_LEN
#define VEC_LEN(v) (sizeof(v)/sizeof(v[0]))
#endif/*VEC_LEN*/

static JavaVM *javaVM;

static void print();

static JNINativeMethod Main_methods[] =
{
    { "print", "()V", (void*)print },
};

static struct {
    const char      *class_name;
    JNINativeMethod *methods;
    int             num_methods;
} native_methods[] = {
    { "com/stackoverflow/Main", Main_methods, VEC_LEN(Main_methods) },
};

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
    JNIEnv *env = 0;
    jclass cls  = 0;
    jint   rs   = 0;

    if ((*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_4)) {
        return JNI_ERR;
    }

    javaVM = jvm;

    for (unsigned int i = 0; i < VEC_LEN(native_methods); i++) {
        cls = (*env)->FindClass(env, native_methods[i].class_name);
        if (cls == NULL) {
            return JNI_ERR;
        }
        rs = (*env)->RegisterNatives(env, cls, native_methods[i].methods, native_methods[i].num_methods);
        assert(rs == JNI_OK);
    }

    return JNI_VERSION_1_4;
}

static void print(JNIEnv *env, jclass cls) {
    printf("Hello from C");
}

#ifdef __cplusplus
}
#endif
  • Build the code by pressing +B.

  • And now it is time to create the Java code. I simply created a class called Main in package com.stackoverflow.

com.stackoverflow.Main.java

package com.stackoverflow;

/**
 * @author maba, 2012-10-09
 */
public class Main {

    static native void print();

    static {
        System.out.println(System.getProperty("java.library.path"));
        System.loadLibrary("native");
    }

    public static void main(String[] args) {
        System.out.println("Loading native");
        Main.print();
    }
}
  • Set a breakpoint on the line before Main.print();. Start the debugger with the following JVM option:

-Djava.library.path="/Users/maba/Library/Developer/Xcode/DerivedData/libnative-cquleqohzyhghnercyqdwpnznjdf/Build/Products/Debug/"

This line is a little long and also user specific. You will have to look for yourself what the directory names are but they will be more or less the same as mine except for the generated libnative-cquleqohzyhghnercyqdwpnznjdf path.

  • The program should be running and waiting at the breakpoint. Time to attach the Xcode debugger to the running application.

  • Choose menu Product -> Attach to Process > and point to the running java process in the System part of the drop down. If there are several java processes then it is most likely the one with the highest PID but not always. You'll have to try.

  • Create a breakpoint in the c code on the line printf("Hello from C");.

  • Go back to the Java IDE and continue the execution from where it was halting.

  • Go back to Xcode and see that it is waiting at the breakpoint!

At Breakpoint


As I stated earlier this is a very simple approach to the obj-c/JNI and your project is probably quite large but with this small test project you can at least see how it works and then continue to your own project setup.

Upvotes: 5

marko
marko

Reputation: 9159

In the past when doing JNI I have built a test-harness to facilitate the development of the native part of the application - and JNI code - which is notorious easy to screw up, avoiding the need to debug simultaneously from both sides.

This was written as a native application that invokes the JVM programmatically rather than starting with a Java application and then attempting to attach to JVM.

You can of course, start this and debug it in Xcode - which is an infinitely preferable experience to Eclipse with CDT.

The Java side of this arrangement is usually pretty simple and non-contriverial - basically a method which is called from the native part of the app that then makes one or more calls back into the native portion through JNI.

Upvotes: 1

bbum
bbum

Reputation: 162712

You might be able to attach with gdb (or lldb) from the Terminal. If the launching of the process w/the native code is the result of a fork()/exec() -- i.e. if you can't type gdb /some/command/line -- then you can likely use the --waitfor option (see the man page) to wait for the launch of the inferior.

Loading symbols will be tricky.


This is a Mac OS X project using the cocoa framework. Does that affect this?

It shouldn't. If anything, it'll make it easier in that, hopefully, the symbol files are of a usable format. The key is typically finding the right spot to break at the boundary between java and native code.

Is the native code in a dylib that is loaded into the JVM or do you have a custom executable that fires up the JVM internally?

In any case, you need to attach the native debugger to whatever process is running that native code. Probably after you've set up the java based debugging session appropriately.

Upvotes: 1

Related Questions