安卓调试JNI_OnLoad

先查看包名,然后以调试的模式启动程序

1
2
3
./adb shell am monitor  # 查看当前活动对象包名(quit结束监控)

abd shell am start -D 包名/.入口

然后当我们IDA 打开某个so附加上去之后,程序还是处在等待调试的状态

IDA调试选项选中 Suspend on library load/unload

我们用jdb使程序运行起来

1
2
adb forward tcp:8700 jdwp:<pid>  
jdb -connect com.sun.jdi.SocketAttach:hostname=127.0.0.1,port=8700

这样如果在JNI_ONLOAD下断点的话,程序就可以断下来了

下面是一个简单的动态注册native的示例

1
2
3
4
5
6
7
8
9
10
public class TextJni {

static {
System.loadLibrary("textjni_lib");
}

native int text(String message);

static native int static_text(String message);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <jni.h>
#include <string>
#include <android/log.h>

jint native_text(JNIEnv *env, jobject jobject1, jstring msg) {
const char *p_msg = env->GetStringUTFChars(msg, JNI_FALSE);
__android_log_print(ANDROID_LOG_INFO, "mmm", "method = %s, msg = %s", __FUNCTION__, p_msg);

return 0;
}

jint native_staic_text(JNIEnv *env, jobject jclass1, jstring meg) {
const char *p_msg = env->GetStringUTFChars(meg, JNI_FALSE);
__android_log_print(ANDROID_LOG_INFO, "mmm", "method = %s, msg = %s", __FUNCTION__, p_msg);

return 0;
}


static const JNINativeMethod nativeMethod[] = {
{"text", "(Ljava/lang/String;)I", (void *) native_text},
{"static_text", "(Ljava/lang/String;)I", (void *) native_staic_text}
};

static int registNativeMethod(JNIEnv *env) {
int result = -1;

jclass class_text = env->FindClass("com.text.ndk1.TextJni");
if (env->RegisterNatives(class_text, nativeMethod,
sizeof(nativeMethod) / sizeof(nativeMethod[0])) == JNI_OK) {
result = 0;
}
return result;
}

jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env = NULL;
int result = -1;

if (vm->GetEnv((void **) &env, JNI_VERSION_1_1) == JNI_OK) {
if (registNativeMethod(env) == JNI_OK) {
result = JNI_VERSION_1_6;
}
return result;
}
}

调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MainActivity extends AppCompatActivity {

// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextJni.static_text("我是静态方法,哈哈");
new TextJni().text("我是普通方法,哈哈");
}
}