http://bbs.pediy.com/showthread.php?t=200398, 很早就有大大给出方法了.
记得看雪已经有人发过一份源码:用来hook jni 用来打印日志的,http://bbs.pediy.com/showthread.php?t=209914.,使用的是ELF-ARM-HOOK-Library库,
因为我的缘由常用模拟器测试app,目前比较好用的模拟器都是基于x86的,上面两位提供的都是基于arm的.
Cydia Substrate支持arm和x86 hook
参考上面两位的方法,和dvm源码
JNINativeInterface 具体实现方法,如GetMethodIDphp
static jmethodID GetMethodID(JNIEnv* env, jclass jclazz, const char* name, const char* sig) { ScopedJniThreadState ts(env){ .... }
编译事后没有导出函数.没法经过dlsym拿到函数地址.想要hook这个函数就要拿到这个函数的地址.
查看jni.h 函数头.
JNIEnv结构:android
typedef _JNIEnv JNIEnv;
_JNIEnv结构:c++
struct _JNIEnv { /* do not rename this; it does not seem to be entirely opaque */ const struct JNINativeInterface* functions; #if defined(__cplusplus) jint GetVersion() { return functions->GetVersion(this); } ....
JNINativeInterface结构:git
struct JNINativeInterface { void* reserved0; void* reserved1; void* reserved2; void* reserved3; jint (*GetVersion)(JNIEnv *); jclass (*DefineClass)(JNIEnv*, const char*, jobject, const jbyte*, jsize); jclass (*FindClass)(JNIEnv*, const char*); ....
能够看到JNINativeInterfac结构全是函数的指针:拿到这个结构体中函数的指针,就拿到具体函数的指针.
这些结构体中的方法初始化实现,能够参考:JNIEnv*dvmCreateJNIEnv(Thread* self);github
关键部分代码:hook RegisterNatives方法app
void Jnimethod::startHookJni(JNIEnv * env) { #if defined(__i386__) MSHookFunction((void*)*(unsigned int*)((*(unsigned int*)env) + 0x35C), (void*)&myRegisterNatives, (void**)&oldRegisterNatives); return; #else ....
其中关键部分:函数
(void*)*(unsigned int*)((*(unsigned int*)env) + 0x35C)
解析:*(unsigned int*)env+ 0x35C 先取JNINativeInterface结构体的地址,0x35C为RegisterNatives在结构体中的偏移.即拿到:测试
jint (*RegisterNatives)(JNIEnv*, jclass, const JNINativeMethod*, jint);
这个函数指针this
*(unsigned int*)((*(unsigned int*)env) + 0x35C)//拿到RegisterNatives函数的地址
拿到函数指针便可实现hook.指针
jint(*oldRegisterNatives)(JNIEnv* env, jclass c, const JNINativeMethod* m, jint n); jint myRegisterNatives(JNIEnv* env, jclass c, const JNINativeMethod* m, jint n) { const char*clazzName = getClassName(env, c); __android_log_print(ANDROID_LOG_INFO, "RegisterNatives", "start! jclass[%s] methods[0x%x]%d ", clazzName, (unsigned int)m, n); for (int i = 0; i < n; i++) { __android_log_print(ANDROID_LOG_INFO, "RegisterNatives", "method[%s%s] fnPtr[0x%x]", m[i].name, m[i].signature, (unsigned int)m[i].fnPtr); } __android_log_print(ANDROID_LOG_INFO, "RegisterNatives", "end! jclass[%s] ", clazzName); return oldRegisterNatives(env, c, m, n); } void Jnimethod::startHookJni(JNIEnv * env) { MSHookFunction((void*)*(unsigned int*)((*(unsigned int*)env) + 0x35C), (void*)&myRegisterNatives, (void**)&oldRegisterNatives); return;
之前,打印jni日志老是在手机上打印.如今能够在模拟器上打印了,也能够丢掉:ELF-ARM-HOOK-Library,这个库了(主要是cydia之处arm和x86,我的比较喜欢cydia).