PAGalaxyLab / YAHFA

Yet Another Hook Framework for ART
GNU General Public License v3.0
1.56k stars 350 forks source link

如何从native直接调用YAHFA native,不通过加载APK的方式从JNI到native? #169

Closed yetnelson closed 2 years ago

yetnelson commented 2 years ago

请问下如何修改可以类似AndHook这种方式使用YAHFA?

static jint (JNICALL *originJNI_CreateJavaVM)(JavaVM **p_vm, JNIEnv **p_env, void *vm_args);
    jint JNICALL myJNI_CreateJavaVM(JavaVM **p_vm, JNIEnv **p_env, void *vm_args) {
    jint j = originJNI_CreateJavaVM(p_vm, p_env, vm_args);
    jclass Instrumentation = (*p_env)->FindClass("android/app/Instrumentation");
    jmethodID Instrumentation_callApplicationOnCreate = (*p_env)->GetMethodID(Instrumentation, "callApplicationOnCreate", "(Landroid/app/Application;)V");
    //AKForceNativeMethod(*p_env, Instrumentation_callApplicationOnCreate, reinterpret_cast<void *>(my_Instrumentation_callApplicationOnCreate), true, &ori_Instrumentation_callApplicationOnCreate);
    return j;
}
yetnelson commented 2 years ago

如下方式是否有问题?烦请指正

jboolean YAHFAbackupAndHookNative(JNIEnv *env, jobject target, void *hook, void *backup) {
    if (!doBackupAndHook(
            getArtMethod(env, target),
            hook,
            backup
    )) {
        (*env)->NewGlobalRef(env, hook); // keep a global ref so that the hook method would not be GCed
        if(backup) (*env)->NewGlobalRef(env, backup);
        return JNI_TRUE;
    } else {
        return JNI_FALSE;
    }
}

static jmethodID ori_Instrumentation_callApplicationOnCreate;
static void JNICALL my_Instrumentation_callApplicationOnCreate(jobject obj, jobject thisApp) {
  if (thisApp != NULL) {
    LOGI("p:%d callApplicationOnCreate app = %p", getpid(), thisApp);
  } //if
  //env->CallVoidMethod(obj, ori_Instrumentation_callApplicationOnCreate, thisApp);
}

static jint (JNICALL *originJNI_CreateJavaVM)(JavaVM **p_vm, JNIEnv **p_env, void *vm_args);
jint JNICALL myJNI_CreateJavaVM(JavaVM **p_vm, JNIEnv **p_env, void *vm_args) {
  jint j = originJNI_CreateJavaVM(p_vm, p_env, vm_args);
  YAHFAinit(*p_env, jint(28));
  (*p_env)->PushLocalFrame(128);
  while (j >= JNI_OK) {
    jclass Instrumentation = (*p_env)->FindClass("android/app/Instrumentation");
    jobject target = YAHFAfindMethodNative(*p_env, Instrumentation, (*p_env)->NewStringUTF("callApplicationOnCreate"), (*p_env)->NewStringUTF("(Landroid/app/Application;)V"));
    YAHFAbackupAndHookNative(*p_env, target, reinterpret_cast<void *>(my_Instrumentation_callApplicationOnCreate), &ori_Instrumentation_callApplicationOnCreate); 
  }
  (*p_env)->PopLocalFrame(NULL);

  return j;
}
yetnelson commented 2 years ago

惯例,自己来回答下。因为是ArtMethod方式所以只能Java 跳板函数,最后注入时间点要注意在register_jni_procs之后,否则基础so没有进来