Dynamically Generating Dalvik Bytecode into a running Dalvik/Android application

后端 未结 5 974
我在风中等你
我在风中等你 2020-12-08 01:09

This question has been asked(and answered) many times about dynamically generating and loading java bytecodes at runtime into a running Dalvik VM, but is there any way to lo

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 01:48

    If inside any C or C++ program, you want to load and call into the DEX classes, you can see how the Dalvik VM is started, inside the AndroidRuntime - for example frameworks/base/cmds/app_process/app_main.cpp:

    status_t app_init(const char* className, int argc, const char* const argv[])
    {
        LOGV("Entered app_init()!\n");
    
        AndroidRuntime* jr = AndroidRuntime::getRuntime();
        jr->callMain(className, argc, argv);
    
        LOGV("Exiting app_init()!\n");
        return NO_ERROR;
    }
    

    As "jr" AndroidRuntime is already started, callMain() will be called:

    status_t AndroidRuntime::callMain(
        const char* className, int argc, const char* const argv[])
    {
        JNIEnv* env;
        jclass clazz;
        jmethodID methodId;
    
        LOGD("Calling main entry %s", className);
    
        env = getJNIEnv();
        if (env == NULL)
            return UNKNOWN_ERROR;
    
        clazz = findClass(env, className);
        if (clazz == NULL) {
            LOGE("ERROR: could not find class '%s'\n", className);
            return UNKNOWN_ERROR;
        }
    
        methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
        if (methodId == NULL) {
            LOGE("ERROR: could not find method %s.main(String[])\n", className);
            return UNKNOWN_ERROR;
        }
    <...>
        env->CallStaticVoidMethod(clazz, methodId, strArray);
        return NO_ERROR;
    }
    

    From above, we can see how the DEX classes' codes are loaded and CallStaticVoidMethod() will start interpreting the DEX codes.

提交回复
热议问题