Android Framework学习条记(4)----Zygote进程

打印 上一主题 下一主题

主题 839|帖子 839|积分 2517

Zygote的启动流程

Init进程启动后,会加载并执行init.rc文件。该.rc文件中,就包含启动Zygote进程的Action。详见“RC文件剖析”章节
根据Zygote对应的RC文件,可知Zygote进程是由/system/bin/app_process程序来创建的。
app_process大抵处理流程如下,详见“app_process剖析”章节

  • 创建AppRuntime
  • 整理传参,并将相应参数传给Runtime或Zygote进程。
  • 利用Runtime调用start方法,传入“com.android.internal.os.ZygoteInit”类和zygote传参,启动zygote。
class AppRuntime 继承自 public AndroidRuntime。调用start方法后,将执行以下步调。详见"AndroidRuntime剖析"章节

  • 搜集JVM参数,启动VM
  • 注册JNI方法。
  • 利用java的反射,调用com.android.internal.os.ZygoteInit类中的main方法,创建zygote进程。

Zygote代码分析

RC文件剖析

Init.rc中的Zygote内容

init.rc中涉及Zygote的部分有五处。从代码中可以看出,在初始化晚期阶段late-init,会触发Zygote-start行为,而该行为会创建zygote,以及zygote_secondary两个进程。
  1. import /system/etc/init/hw/init.${ro.zygote}.rc
  2. import /system/etc/init/hw/init.boringssl.${ro.zygote}.rc
  3. ...
  4. on late-init
  5.    trigger zygote-start
  6. ...
  7. on zygote-start
  8.     wait_for_prop odsign.verification.done 1
  9.     # A/B update verifier that marks a successful boot.
  10.     exec_start update_verifier
  11.     start statsd
  12.     start netd
  13.     start zygote
  14.     start zygote_secondary
  15. ...
  16. on userspace-reboot-resume
  17.   trigger userspace-reboot-fs-remount
  18.   trigger post-fs-data
  19.   trigger zygote-start
  20.   trigger early-boot
  21.   trigger boot
复制代码
关于怎样启动这两个进程,可以参照init.${ro.zygote}.rc。${ro.zygote}的值,可以通过shell指令“getprop ro.zygote”获取。以下图为例,zygote64_32代表64模式为主,32位模式为辅。

init.zygote64_32.rc

引用了init.zygote64.rc
声明了一个名字为“zygote_secondary”的service。该service将有/system/bin/app_process进程来启动。其中以“-”开头的是JVM参数,-Xzygote /system/bin。以“--”开头的是进程参数,--zygote --socket-name=zygote_secondary --enable-lazy-preload。
创建了两个socket,名字为zygote_secondary和usap_pool_secondary。
  1. import /system/etc/init/hw/init.zygote64.rc
  2. service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary --enable-lazy-preload
  3.     class main
  4.     priority -20
  5.     user root
  6.     group root readproc reserved_disk
  7.     socket zygote_secondary stream 660 root system
  8.     socket usap_pool_secondary stream 660 root system
  9.     onrestart restart zygote
  10.     task_profiles ProcessCapacityHigh MaxPerformance
复制代码
init.zygote64.rc

声明了一个名字为“zygote”的service。该service将有/system/bin/app_process进程来启动。其中以“-”开头的是JVM参数,-Xzygote /system/bin。以“--”开头的是进程参数,--zygote --start-system-server --socket-name=zygote。
创建了两个socket,名字为zygote和usap_pool_primary。
  1. service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote
  2.     class main
  3.     priority -20
  4.     user root
  5.     group root readproc reserved_disk
  6.     socket zygote stream 660 root system
  7.     socket usap_pool_primary stream 660 root system
  8.     onrestart exec_background - system system -- /system/bin/vdc volume abort_fuse
  9.     onrestart write /sys/power/state on
  10.     # NOTE: If the wakelock name here is changed, then also
  11.     # update it in SystemSuspend.cpp
  12.     onrestart write /sys/power/wake_lock zygote_kwl
  13.     onrestart restart audioserver
  14.     onrestart restart cameraserver
  15.     onrestart restart media
  16.     onrestart restart --only-if-running media.tuner
  17.     onrestart restart netd
  18.     onrestart restart wificond
  19.     task_profiles ProcessCapacityHigh MaxPerformance
  20.     critical window=${zygote.critical_window.minute:-off} target=zygote-fatal
复制代码
init.boringssl.zygote64_32.rc

包含的都是在某些条件下触发的自测进程。相识即可。
  1. on init && property:ro.product.cpu.abilist32=*
  2.     exec_start boringssl_self_test32
  3. on init && property:ro.product.cpu.abilist64=*
  4.     exec_start boringssl_self_test64
  5. on property:apexd.status=ready && property:ro.product.cpu.abilist32=*
  6.     exec_start boringssl_self_test_apex32
  7. on property:apexd.status=ready && property:ro.product.cpu.abilist64=*
  8.     exec_start boringssl_self_test_apex64
复制代码
app_process剖析 

frameworks/base/cmds/app_process/app_main.cpp
  1. int main(int argc, char* const argv[])
  2. {
  3.     if (!LOG_NDEBUG) {
  4.       String8 argv_String;
  5.       for (int i = 0; i < argc; ++i) {
  6.         argv_String.append(""");
  7.         argv_String.append(argv[i]);
  8.         argv_String.append("" ");
  9.       }
  10.       ALOGV("app_process main with argv: %s", argv_String.c_str());
  11.     }
  12. //步骤1:创建Runtime.--------------------------------------------
  13.     AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
  14.     // Process command line arguments
  15.     // ignore argv[0]
  16.     argc--;
  17.     argv++;
  18.     // Everything up to '--' or first non '-' arg goes to the vm.
  19.     //
  20.     // The first argument after the VM args is the "parent dir", which
  21.     // is currently unused.
  22.     //
  23.     // After the parent dir, we expect one or more the following internal
  24.     // arguments :
  25.     //
  26.     // --zygote : Start in zygote mode
  27.     // --start-system-server : Start the system server.
  28.     // --application : Start in application (stand alone, non zygote) mode.
  29.     // --nice-name : The nice name for this process.
  30.     //
  31.     // For non zygote starts, these arguments will be followed by
  32.     // the main class name. All remaining arguments are passed to
  33.     // the main method of this class.
  34.     //
  35.     // For zygote starts, all remaining arguments are passed to the zygote.
  36.     // main function.
  37.     //
  38.     // Note that we must copy argument string values since we will rewrite the
  39.     // entire argument block when we apply the nice name to argv0.
  40.     //
  41.     // As an exception to the above rule, anything in "spaced commands"
  42.     // goes to the vm even though it has a space in it.
  43.     const char* spaced_commands[] = { "-cp", "-classpath" };
  44.     // Allow "spaced commands" to be succeeded by exactly 1 argument (regardless of -s).
  45.     bool known_command = false;
  46. //步骤2:解析传参,将'-'开头的参数传给Runtime.--------------------------------------------
  47.     int i;
  48.     for (i = 0; i < argc; i++) {
  49.         if (known_command == true) {
  50.           runtime.addOption(strdup(argv[i]));
  51.           // The static analyzer gets upset that we don't ever free the above
  52.           // string. Since the allocation is from main, leaking it doesn't seem
  53.           // problematic. NOLINTNEXTLINE
  54.           ALOGV("app_process main add known option '%s'", argv[i]);
  55.           known_command = false;
  56.           continue;
  57.         }
  58.         for (int j = 0;
  59.              j < static_cast<int>(sizeof(spaced_commands) / sizeof(spaced_commands[0]));
  60.              ++j) {
  61.           if (strcmp(argv[i], spaced_commands[j]) == 0) {
  62.             known_command = true;
  63.             ALOGV("app_process main found known command '%s'", argv[i]);
  64.           }
  65.         }
  66.         if (argv[i][0] != '-') {
  67.             break;
  68.         }
  69.         if (argv[i][1] == '-' && argv[i][2] == 0) {
  70.             ++i; // Skip --.
  71.             break;
  72.         }
  73.         runtime.addOption(strdup(argv[i]));
  74.         // The static analyzer gets upset that we don't ever free the above
  75.         // string. Since the allocation is from main, leaking it doesn't seem
  76.         // problematic. NOLINTNEXTLINE
  77.         ALOGV("app_process main add option '%s'", argv[i]);
  78.     }
  79.     // Parse runtime arguments.  Stop at first unrecognized option.
  80.     bool zygote = false;
  81.     bool startSystemServer = false;
  82.     bool application = false;
  83.     String8 niceName;
  84.     String8 className;
  85. //步骤3:整理zygote进程的传参.--------------------------------------------
  86.     ++i;  // Skip unused "parent dir" argument.
  87.     while (i < argc) {
  88.         const char* arg = argv[i++];
  89.         if (strcmp(arg, "--zygote") == 0) {
  90.             zygote = true;
  91.             niceName = ZYGOTE_NICE_NAME;
  92.         } else if (strcmp(arg, "--start-system-server") == 0) {
  93.             startSystemServer = true;
  94.         } else if (strcmp(arg, "--application") == 0) {
  95.             application = true;
  96.         } else if (strncmp(arg, "--nice-name=", 12) == 0) {
  97.             niceName = (arg + 12);
  98.         } else if (strncmp(arg, "--", 2) != 0) {
  99.             className = arg;
  100.             break;
  101.         } else {
  102.             --i;
  103.             break;
  104.         }
  105.     }
  106. //步骤4:根据整理的zygote传参,判断是否是zygote进程,并根据判断结果,补充“--abi-list”和“start-system-server”传参.--------------------------------------------
  107.     Vector<String8> args;
  108.     if (!className.empty()) {
  109.         // We're not in zygote mode, the only argument we need to pass
  110.         // to RuntimeInit is the application argument.
  111.         //
  112.         // The Remainder of args get passed to startup class main(). Make
  113.         // copies of them before we overwrite them with the process name.
  114.         args.add(application ? String8("application") : String8("tool"));
  115.         runtime.setClassNameAndArgs(className, argc - i, argv + i);
  116.         if (!LOG_NDEBUG) {
  117.           String8 restOfArgs;
  118.           char* const* argv_new = argv + i;
  119.           int argc_new = argc - i;
  120.           for (int k = 0; k < argc_new; ++k) {
  121.             restOfArgs.append(""");
  122.             restOfArgs.append(argv_new[k]);
  123.             restOfArgs.append("" ");
  124.           }
  125.           ALOGV("Class name = %s, args = %s", className.c_str(), restOfArgs.c_str());
  126.         }
  127.     } else {
  128.         // We're in zygote mode.
  129.         maybeCreateDalvikCache();
  130.         if (startSystemServer) {
  131.             args.add(String8("start-system-server"));
  132.         }
  133.         char prop[PROP_VALUE_MAX];
  134.         if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) {
  135.             LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.",
  136.                 ABI_LIST_PROPERTY);
  137.             return 11;
  138.         }
  139.         String8 abiFlag("--abi-list=");
  140.         abiFlag.append(prop);
  141.         args.add(abiFlag);
  142.         // In zygote mode, pass all remaining arguments to the zygote
  143.         // main() method.
  144.         for (; i < argc; ++i) {
  145.             args.add(String8(argv[i]));
  146.         }
  147.     }
  148.     if (!niceName.empty()) {
  149.         runtime.setArgv0(niceName.c_str(), true /* setProcName */);
  150.     }
  151. //步骤5:使用runtime,调用“com.android.internal.os.ZygoteInit”类,并传入传参,启动zygote.--------------------------------------------
  152.     if (zygote) {
  153.         runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
  154.     } else if (!className.empty()) {
  155.         runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
  156.     } else {
  157.         fprintf(stderr, "Error: no class name or --zygote supplied.\n");
  158.         app_usage();
  159.         LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
  160.     }
  161. }
复制代码
AndroidRuntime剖析

frameworks/base/core/jni/AndroidRuntime.cpp
Runtime的start方法

  1. void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
  2. {
  3.     ALOGD(">>>>>> START %s uid %d <<<<<<\n",
  4.             className != NULL ? className : "(unknown)", getuid());
  5.     static const String8 startSystemServer("start-system-server");
  6.     // Whether this is the primary zygote, meaning the zygote which will fork system server.
  7.     bool primary_zygote = false;
  8. //步骤1:必要的参数及环境变量检查。-----------------------------------
  9.     /*
  10.      * 'startSystemServer == true' means runtime is obsolete and not run from
  11.      * init.rc anymore, so we print out the boot start event here.
  12.      */
  13.     for (size_t i = 0; i < options.size(); ++i) {
  14.         if (options[i] == startSystemServer) {
  15.             primary_zygote = true;
  16.            /* track our progress through the boot sequence */
  17.            const int LOG_BOOT_PROGRESS_START = 3000;
  18.            LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,  ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
  19.         }
  20.     }
  21.     const char* rootDir = getenv("ANDROID_ROOT");
  22.     if (rootDir == NULL) {
  23.         rootDir = "/system";
  24.         if (!hasDir("/system")) {
  25.             LOG_FATAL("No root directory specified, and /system does not exist.");
  26.             return;
  27.         }
  28.         setenv("ANDROID_ROOT", rootDir, 1);
  29.     }
  30.     const char* artRootDir = getenv("ANDROID_ART_ROOT");
  31.     if (artRootDir == NULL) {
  32.         LOG_FATAL("No ART directory specified with ANDROID_ART_ROOT environment variable.");
  33.         return;
  34.     }
  35.     const char* i18nRootDir = getenv("ANDROID_I18N_ROOT");
  36.     if (i18nRootDir == NULL) {
  37.         LOG_FATAL("No runtime directory specified with ANDROID_I18N_ROOT environment variable.");
  38.         return;
  39.     }
  40.     const char* tzdataRootDir = getenv("ANDROID_TZDATA_ROOT");
  41.     if (tzdataRootDir == NULL) {
  42.         LOG_FATAL("No tz data directory specified with ANDROID_TZDATA_ROOT environment variable.");
  43.         return;
  44.     }
  45.     //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
  46.     //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
  47. //步骤2:启动VM。-----------------------------------
  48.     /* start the virtual machine */
  49.     JniInvocation jni_invocation;
  50.     jni_invocation.Init(NULL);
  51.     JNIEnv* env;
  52.     if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {
  53.         return;
  54.     }
  55.     onVmCreated(env);
  56.     /*
  57.      * Register android functions.
  58.      */
  59. //步骤3:注册JNI方法。-----------------------------------
  60.     if (startReg(env) < 0) {
  61.         ALOGE("Unable to register all android natives\n");
  62.         return;
  63.     }
  64.     /*
  65.      * We want to call main() with a String array with arguments in it.
  66.      * At present we have two arguments, the class name and an option string.
  67.      * Create an array to hold them.
  68.      */
  69.     jclass stringClass;
  70.     jobjectArray strArray;
  71.     jstring classNameStr;
  72.     stringClass = env->FindClass("java/lang/String");
  73.     assert(stringClass != NULL);
  74.     strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
  75.     assert(strArray != NULL);
  76.     classNameStr = env->NewStringUTF(className);
  77.     assert(classNameStr != NULL);
  78.     env->SetObjectArrayElement(strArray, 0, classNameStr);
  79.     for (size_t i = 0; i < options.size(); ++i) {
  80.         jstring optionsStr = env->NewStringUTF(options.itemAt(i).c_str());
  81.         assert(optionsStr != NULL);
  82.         env->SetObjectArrayElement(strArray, i + 1, optionsStr);
  83.     }
  84. //步骤4:利用java的反射,调用com.android.internal.os.ZygoteInit类中的main方法,创建zygote进程。-----------------------------------
  85.     /*
  86.      * Start VM.  This thread becomes the main thread of the VM, and will
  87.      * not return until the VM exits.
  88.      */
  89.     char* slashClassName = toSlashClassName(className != NULL ? className : "");
  90.     jclass startClass = env->FindClass(slashClassName);
  91.     if (startClass == NULL) {
  92.         ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
  93.         /* keep going */
  94.     } else {
  95.         jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
  96.             "([Ljava/lang/String;)V");
  97.         if (startMeth == NULL) {
  98.             ALOGE("JavaVM unable to find main() in '%s'\n", className);
  99.             /* keep going */
  100.         } else {
  101.             env->CallStaticVoidMethod(startClass, startMeth, strArray);
  102. #if 0
  103.             if (env->ExceptionCheck())
  104.                 threadExitUncaughtException(env);
  105. #endif
  106.         }
  107.     }
  108.     free(slashClassName);
  109.     ALOGD("Shutting down VM\n");
  110.     if (mJavaVM->DetachCurrentThread() != JNI_OK)
  111.         ALOGW("Warning: unable to detach main thread\n");
  112.     if (mJavaVM->DestroyJavaVM() != 0)
  113.         ALOGW("Warning: VM did not shut down cleanly\n");
  114. }
复制代码
启动VM

该方法有600+行,都是网络VM参数,并调用JNI_CreateJavaVM启动VM。参数是一个可以做性能优化的点。相识即可。
  1. int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote, bool primary_zygote)
  2. {
  3.     JavaVMInitArgs initArgs;
  4.     char propBuf[PROPERTY_VALUE_MAX];
  5.     char jniOptsBuf[sizeof("-Xjniopts:")-1 + PROPERTY_VALUE_MAX];
  6.     char heapstartsizeOptsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
  7.     char heapsizeOptsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
  8.     char heapgrowthlimitOptsBuf[sizeof("-XX:HeapGrowthLimit=")-1 + PROPERTY_VALUE_MAX];
  9.     char heapminfreeOptsBuf[sizeof("-XX:HeapMinFree=")-1 + PROPERTY_VALUE_MAX];
  10.     char heapmaxfreeOptsBuf[sizeof("-XX:HeapMaxFree=")-1 + PROPERTY_VALUE_MAX];
  11.     char usejitOptsBuf[sizeof("-Xusejit:")-1 + PROPERTY_VALUE_MAX];
  12.     char jitpthreadpriorityOptsBuf[sizeof("-Xjitpthreadpriority:")-1 + PROPERTY_VALUE_MAX];
  13.     char jitmaxsizeOptsBuf[sizeof("-Xjitmaxsize:")-1 + PROPERTY_VALUE_MAX];
  14.     char jitinitialsizeOptsBuf[sizeof("-Xjitinitialsize:")-1 + PROPERTY_VALUE_MAX];
  15.     char jitthresholdOptsBuf[sizeof("-Xjitthreshold:")-1 + PROPERTY_VALUE_MAX];
  16.     char jitprithreadweightOptBuf[sizeof("-Xjitprithreadweight:")-1 + PROPERTY_VALUE_MAX];
  17.     char jittransitionweightOptBuf[sizeof("-Xjittransitionweight:")-1 + PROPERTY_VALUE_MAX];
  18.     char hotstartupsamplesOptsBuf[sizeof("-Xps-hot-startup-method-samples:")-1 + PROPERTY_VALUE_MAX];
  19.     char saveResolvedClassesDelayMsOptsBuf[
  20.             sizeof("-Xps-save-resolved-classes-delay-ms:")-1 + PROPERTY_VALUE_MAX];
  21.     char profileMinSavePeriodOptsBuf[sizeof("-Xps-min-save-period-ms:")-1 + PROPERTY_VALUE_MAX];
  22.     char profileMinFirstSaveOptsBuf[sizeof("-Xps-min-first-save-ms:") - 1 + PROPERTY_VALUE_MAX];
  23.     char profileInlineCacheThresholdOptsBuf[
  24.             sizeof("-Xps-inline-cache-threshold:") - 1 + PROPERTY_VALUE_MAX];
  25.     char madviseWillNeedFileSizeVdex[
  26.             sizeof("-XMadviseWillNeedVdexFileSize:")-1 + PROPERTY_VALUE_MAX];
  27.     char madviseWillNeedFileSizeOdex[
  28.             sizeof("-XMadviseWillNeedOdexFileSize:")-1 + PROPERTY_VALUE_MAX];
  29.     char madviseWillNeedFileSizeArt[
  30.             sizeof("-XMadviseWillNeedArtFileSize:")-1 + PROPERTY_VALUE_MAX];
  31.     char gctypeOptsBuf[sizeof("-Xgc:")-1 + PROPERTY_VALUE_MAX];
  32.     char backgroundgcOptsBuf[sizeof("-XX:BackgroundGC=")-1 + PROPERTY_VALUE_MAX];
  33.     char heaptargetutilizationOptsBuf[sizeof("-XX:HeapTargetUtilization=")-1 + PROPERTY_VALUE_MAX];
  34.     char foregroundHeapGrowthMultiplierOptsBuf[
  35.             sizeof("-XX:ForegroundHeapGrowthMultiplier=")-1 + PROPERTY_VALUE_MAX];
  36.     char finalizerTimeoutMsOptsBuf[sizeof("-XX:FinalizerTimeoutMs=")-1 + PROPERTY_VALUE_MAX];
  37.     char threadSuspendTimeoutOptsBuf[sizeof("-XX:ThreadSuspendTimeout=")-1 + PROPERTY_VALUE_MAX];
  38.     char cachePruneBuf[sizeof("-Xzygote-max-boot-retry=")-1 + PROPERTY_VALUE_MAX];
  39.     char dex2oatXmsImageFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
  40.     char dex2oatXmxImageFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
  41.     char dex2oatCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
  42.     char dex2oatImageCompilerFilterBuf[sizeof("--compiler-filter=")-1 + PROPERTY_VALUE_MAX];
  43.     char dex2oatThreadsBuf[sizeof("-j")-1 + PROPERTY_VALUE_MAX];
  44.     char dex2oatThreadsImageBuf[sizeof("-j")-1 + PROPERTY_VALUE_MAX];
  45.     char dex2oatCpuSetBuf[sizeof("--cpu-set=")-1 + PROPERTY_VALUE_MAX];
  46.     char dex2oatCpuSetImageBuf[sizeof("--cpu-set=")-1 + PROPERTY_VALUE_MAX];
  47.     char dex2oat_isa_variant_key[PROPERTY_KEY_MAX];
  48.     char dex2oat_isa_variant[sizeof("--instruction-set-variant=") -1 + PROPERTY_VALUE_MAX];
  49.     char dex2oat_isa_features_key[PROPERTY_KEY_MAX];
  50.     char dex2oat_isa_features[sizeof("--instruction-set-features=") -1 + PROPERTY_VALUE_MAX];
  51.     char dex2oatFlagsBuf[PROPERTY_VALUE_MAX];
  52.     char dex2oatImageFlagsBuf[PROPERTY_VALUE_MAX];
  53.     char extraOptsBuf[PROPERTY_VALUE_MAX];
  54.     char perfettoHprofOptBuf[sizeof("-XX:PerfettoHprof=") + PROPERTY_VALUE_MAX];
  55.     char perfettoJavaHeapStackOptBuf[
  56.             sizeof("-XX:PerfettoJavaHeapStackProf=") + PROPERTY_VALUE_MAX];
  57.     enum {
  58.       kEMDefault,
  59.       kEMIntPortable,
  60.       kEMIntFast,
  61.       kEMJitCompiler,
  62.     } executionMode = kEMDefault;
  63.     char localeOption[sizeof("-Duser.locale=") + PROPERTY_VALUE_MAX];
  64.     char lockProfThresholdBuf[sizeof("-Xlockprofthreshold:")-1 + PROPERTY_VALUE_MAX];
  65.     char nativeBridgeLibrary[sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX];
  66.     char cpuAbiListBuf[sizeof("--cpu-abilist=") + PROPERTY_VALUE_MAX];
  67.     char corePlatformApiPolicyBuf[sizeof("-Xcore-platform-api-policy:") + PROPERTY_VALUE_MAX];
  68.     char methodTraceFileBuf[sizeof("-Xmethod-trace-file:") + PROPERTY_VALUE_MAX];
  69.     char methodTraceFileSizeBuf[sizeof("-Xmethod-trace-file-size:") + PROPERTY_VALUE_MAX];
  70.     std::string fingerprintBuf;
  71.     char javaZygoteForkLoopBuf[sizeof("-XX:ForceJavaZygoteForkLoop=") + PROPERTY_VALUE_MAX];
  72.     char jdwpProviderBuf[sizeof("-XjdwpProvider:") - 1 + PROPERTY_VALUE_MAX];
  73.     char opaqueJniIds[sizeof("-Xopaque-jni-ids:") - 1 + PROPERTY_VALUE_MAX];
  74.     char bootImageBuf[sizeof("-Ximage:") - 1 + PROPERTY_VALUE_MAX];
  75.     // Read if we are using the profile configuration, do this at the start since the last ART args
  76.     // take precedence.
  77.     std::string profile_boot_class_path_flag =
  78.             server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
  79.                                                                  PROFILE_BOOT_CLASS_PATH,
  80.                                                                  /*default_value=*/"");
  81.     bool profile_boot_class_path;
  82.     switch (ParseBool(profile_boot_class_path_flag)) {
  83.         case ParseBoolResult::kError:
  84.             // Default to the system property.
  85.             profile_boot_class_path =
  86.                     GetBoolProperty("dalvik.vm.profilebootclasspath", /*default_value=*/false);
  87.             break;
  88.         case ParseBoolResult::kTrue:
  89.             profile_boot_class_path = true;
  90.             break;
  91.         case ParseBoolResult::kFalse:
  92.             profile_boot_class_path = false;
  93.             break;
  94.     }
  95.     if (profile_boot_class_path) {
  96.         addOption("-Xcompiler-option");
  97.         addOption("--count-hotness-in-compiled-code");
  98.         addOption("-Xps-profile-boot-class-path");
  99.         addOption("-Xps-profile-aot-code");
  100.         addOption("-Xjitsaveprofilinginfo");
  101.     }
  102.     std::string use_jitzygote_image_flag =
  103.             server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
  104.                                                                  ENABLE_JITZYGOTE_IMAGE,
  105.                                                                  /*default_value=*/"");
  106.     // Use the APEX boot image for boot class path profiling to get JIT samples on BCP methods.
  107.     // Also use the APEX boot image if it's explicitly enabled via configuration flag.
  108.     const bool use_apex_image = profile_boot_class_path || (use_jitzygote_image_flag == "true");
  109.     if (use_apex_image) {
  110.         ALOGI("Using JIT Zygote image: '%s'\n", kJitZygoteImageOption);
  111.         addOption(kJitZygoteImageOption);
  112.     } else if (parseRuntimeOption("dalvik.vm.boot-image", bootImageBuf, "-Ximage:")) {
  113.         ALOGI("Using dalvik.vm.boot-image: '%s'\n", bootImageBuf);
  114.     } else {
  115.         ALOGI("Using default boot image");
  116.     }
  117.     std::string disable_lock_profiling =
  118.         server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
  119.                                                              DISABLE_LOCK_PROFILING,
  120.                                                              /*default_value=*/ "");
  121.     if (disable_lock_profiling == "true") {
  122.         addOption(kLockProfThresholdRuntimeOption);
  123.         ALOGI("Disabling lock profiling: '%s'\n", kLockProfThresholdRuntimeOption);
  124.     } else {
  125.         ALOGI("Leaving lock profiling enabled");
  126.     }
  127.     const bool checkJni = GetBoolProperty("dalvik.vm.checkjni", false);
  128.     if (checkJni) {
  129.         ALOGD("CheckJNI is ON");
  130.         /* extended JNI checking */
  131.         addOption("-Xcheck:jni");
  132.         /* with -Xcheck:jni, this provides a JNI function call trace */
  133.         //addOption("-verbose:jni");
  134.     }
  135.     const bool odsignVerificationSuccess = GetBoolProperty("odsign.verification.success", false);
  136.     if (!odsignVerificationSuccess) {
  137.         addOption("-Xdeny-art-apex-data-files");
  138.     }
  139.     property_get("dalvik.vm.execution-mode", propBuf, "");
  140.     if (strcmp(propBuf, "int:portable") == 0) {
  141.         executionMode = kEMIntPortable;
  142.     } else if (strcmp(propBuf, "int:fast") == 0) {
  143.         executionMode = kEMIntFast;
  144.     } else if (strcmp(propBuf, "int:jit") == 0) {
  145.         executionMode = kEMJitCompiler;
  146.     }
  147.     strcpy(jniOptsBuf, "-Xjniopts:");
  148.     if (parseRuntimeOption("dalvik.vm.jniopts", jniOptsBuf, "-Xjniopts:")) {
  149.         ALOGI("JNI options: '%s'\n", jniOptsBuf);
  150.     }
  151.     /* route exit() to our handler */
  152.     addOption("exit", (void*) runtime_exit);
  153.     /* route fprintf() to our handler */
  154.     addOption("vfprintf", (void*) runtime_vfprintf);
  155.     /* register the framework-specific "is sensitive thread" hook */
  156.     addOption("sensitiveThread", (void*) runtime_isSensitiveThread);
  157.     /* enable verbose; standard options are { jni, gc, class } */
  158.     //addOption("-verbose:jni");
  159.     addOption("-verbose:gc");
  160.     //addOption("-verbose:class");
  161.     // On Android, we always want to allow loading the PerfettoHprof plugin.
  162.     // Even with this option set, we will still only actually load the plugin
  163.     // if we are on a userdebug build or the app is debuggable or profileable.
  164.     // This is enforced in art/runtime/runtime.cc.
  165.     //
  166.     // We want to be able to disable this, because this does not work on host,
  167.     // and we do not want to enable it in tests.
  168.     parseRuntimeOption("dalvik.vm.perfetto_hprof", perfettoHprofOptBuf, "-XX:PerfettoHprof=",
  169.                        "true");
  170.     // Enable PerfettoJavaHeapStackProf in the zygote
  171.     parseRuntimeOption("dalvik.vm.perfetto_javaheap", perfettoJavaHeapStackOptBuf,
  172.                        "-XX:PerfettoJavaHeapStackProf=", "true");
  173.     if (primary_zygote) {
  174.         addOption("-Xprimaryzygote");
  175.     }
  176.     /*
  177.      * The default starting and maximum size of the heap.  Larger
  178.      * values should be specified in a product property override.
  179.      */
  180.     parseRuntimeOption("dalvik.vm.heapstartsize", heapstartsizeOptsBuf, "-Xms", "4m");
  181.     parseRuntimeOption("dalvik.vm.heapsize", heapsizeOptsBuf, "-Xmx", "16m");
  182.     parseRuntimeOption("dalvik.vm.heapgrowthlimit", heapgrowthlimitOptsBuf, "-XX:HeapGrowthLimit=");
  183.     parseRuntimeOption("dalvik.vm.heapminfree", heapminfreeOptsBuf, "-XX:HeapMinFree=");
  184.     parseRuntimeOption("dalvik.vm.heapmaxfree", heapmaxfreeOptsBuf, "-XX:HeapMaxFree=");
  185.     parseRuntimeOption("dalvik.vm.heaptargetutilization",
  186.                        heaptargetutilizationOptsBuf,
  187.                        "-XX:HeapTargetUtilization=");
  188.     /* Foreground heap growth multiplier option */
  189.     parseRuntimeOption("dalvik.vm.foreground-heap-growth-multiplier",
  190.                        foregroundHeapGrowthMultiplierOptsBuf,
  191.                        "-XX:ForegroundHeapGrowthMultiplier=");
  192.     /*
  193.      * Finalizer and thread suspend timeouts.
  194.      */
  195.     parseRuntimeOption("dalvik.vm.finalizer-timeout-ms",
  196.                        finalizerTimeoutMsOptsBuf,
  197.                        "-XX:FinalizerTimeoutMs=");
  198.     parseRuntimeOption("dalvik.vm.thread-suspend-timeout-ms",
  199.                        threadSuspendTimeoutOptsBuf,
  200.                        "-XX:ThreadSuspendTimeout=");
  201.     /*
  202.      * JIT related options.
  203.      */
  204.     parseRuntimeOption("dalvik.vm.usejit", usejitOptsBuf, "-Xusejit:");
  205.     parseRuntimeOption("dalvik.vm.jitmaxsize", jitmaxsizeOptsBuf, "-Xjitmaxsize:");
  206.     parseRuntimeOption("dalvik.vm.jitinitialsize", jitinitialsizeOptsBuf, "-Xjitinitialsize:");
  207.     parseRuntimeOption("dalvik.vm.jitthreshold", jitthresholdOptsBuf, "-Xjitthreshold:");
  208.     parseRuntimeOption("dalvik.vm.jitpthreadpriority",
  209.                        jitpthreadpriorityOptsBuf,
  210.                        "-Xjitpthreadpriority:");
  211.     addOption("-Xjitsaveprofilinginfo");
  212.     parseRuntimeOption("dalvik.vm.jitprithreadweight",
  213.                        jitprithreadweightOptBuf,
  214.                        "-Xjitprithreadweight:");
  215.     parseRuntimeOption("dalvik.vm.jittransitionweight", jittransitionweightOptBuf,
  216.                        "-Xjittransitionweight:");
  217.     /*
  218.      * Use default platform configuration as limits for madvising,
  219.      * when no properties are specified.
  220.      */
  221.     parseRuntimeOption("dalvik.vm.madvise.vdexfile.size",
  222.                        madviseWillNeedFileSizeVdex,
  223.                        "-XMadviseWillNeedVdexFileSize:");
  224.     parseRuntimeOption("dalvik.vm.madvise.odexfile.size",
  225.                        madviseWillNeedFileSizeOdex,
  226.                        "-XMadviseWillNeedOdexFileSize:");
  227.     parseRuntimeOption("dalvik.vm.madvise.artfile.size",
  228.                        madviseWillNeedFileSizeArt,
  229.                        "-XMadviseWillNeedArtFileSize:");
  230.     /*
  231.      * Profile related options.
  232.      */
  233.     parseRuntimeOption("dalvik.vm.hot-startup-method-samples", hotstartupsamplesOptsBuf,
  234.             "-Xps-hot-startup-method-samples:");
  235.     parseRuntimeOption("dalvik.vm.ps-resolved-classes-delay-ms", saveResolvedClassesDelayMsOptsBuf,
  236.             "-Xps-save-resolved-classes-delay-ms:");
  237.     parseRuntimeOption("dalvik.vm.ps-min-save-period-ms", profileMinSavePeriodOptsBuf,
  238.             "-Xps-min-save-period-ms:");
  239.     parseRuntimeOption("dalvik.vm.ps-min-first-save-ms", profileMinFirstSaveOptsBuf,
  240.             "-Xps-min-first-save-ms:");
  241.     parseRuntimeOption("dalvik.vm.ps-inline-cache-threshold", profileInlineCacheThresholdOptsBuf,
  242.             "-Xps-inline-cache-threshold:");
  243.     property_get("ro.config.low_ram", propBuf, "");
  244.     if (strcmp(propBuf, "true") == 0) {
  245.       addOption("-XX:LowMemoryMode");
  246.     }
  247.     /*
  248.      * Garbage-collection related options.
  249.      */
  250.     parseRuntimeOption("dalvik.vm.gctype", gctypeOptsBuf, "-Xgc:");
  251.     // If it set, honor the "enable_generational_cc" device configuration;
  252.     // otherwise, let the runtime use its default behavior.
  253.     std::string enable_generational_cc =
  254.         server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
  255.                                                              ENABLE_GENERATIONAL_CC,
  256.                                                              /*default_value=*/ "");
  257.     if (enable_generational_cc == "true") {
  258.         addOption(kGenerationalCCRuntimeOption);
  259.     } else if (enable_generational_cc == "false") {
  260.         addOption(kNoGenerationalCCRuntimeOption);
  261.     }
  262.     parseRuntimeOption("dalvik.vm.backgroundgctype", backgroundgcOptsBuf, "-XX:BackgroundGC=");
  263.     /*
  264.      * Enable/disable zygote native fork loop.
  265.      */
  266.     parseRuntimeOption("dalvik.vm.force-java-zygote-fork-loop",
  267.                        javaZygoteForkLoopBuf,
  268.                        "-XX:ForceJavaZygoteForkLoop=");
  269.     /*
  270.      * Enable debugging only for apps forked from zygote.
  271.      */
  272.     if (zygote) {
  273.       // Set the JDWP provider and required arguments. By default let the runtime choose how JDWP is
  274.       // implemented. When this is not set the runtime defaults to not allowing JDWP.
  275.       addOption("-XjdwpOptions:suspend=n,server=y");
  276.       parseRuntimeOption("dalvik.vm.jdwp-provider",
  277.                          jdwpProviderBuf,
  278.                          "-XjdwpProvider:",
  279.                          "default");
  280.     }
  281.     // Only pass an explicit opaque-jni-ids to apps forked from zygote
  282.     if (zygote) {
  283.       parseRuntimeOption("dalvik.vm.opaque-jni-ids",
  284.                         opaqueJniIds,
  285.                         "-Xopaque-jni-ids:",
  286.                         "swapable");
  287.     }
  288.     parseRuntimeOption("dalvik.vm.lockprof.threshold",
  289.                        lockProfThresholdBuf,
  290.                        "-Xlockprofthreshold:");
  291.     if (executionMode == kEMIntPortable) {
  292.         addOption("-Xint:portable");
  293.     } else if (executionMode == kEMIntFast) {
  294.         addOption("-Xint:fast");
  295.     } else if (executionMode == kEMJitCompiler) {
  296.         addOption("-Xint:jit");
  297.     }
  298.     // Extra options for JIT.
  299.     parseCompilerOption("dalvik.vm.dex2oat-filter", dex2oatCompilerFilterBuf,
  300.                         "--compiler-filter=", "-Xcompiler-option");
  301.     parseCompilerOption("dalvik.vm.dex2oat-threads", dex2oatThreadsBuf, "-j", "-Xcompiler-option");
  302.     parseCompilerOption("dalvik.vm.dex2oat-cpu-set", dex2oatCpuSetBuf, "--cpu-set=",
  303.                         "-Xcompiler-option");
  304.     // Copy the variant.
  305.     sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", ABI_STRING);
  306.     parseCompilerOption(dex2oat_isa_variant_key, dex2oat_isa_variant,
  307.                         "--instruction-set-variant=", "-Xcompiler-option");
  308.     // Copy the features.
  309.     sprintf(dex2oat_isa_features_key, "dalvik.vm.isa.%s.features", ABI_STRING);
  310.     parseCompilerOption(dex2oat_isa_features_key, dex2oat_isa_features,
  311.                         "--instruction-set-features=", "-Xcompiler-option");
  312.     /*
  313.      * When running with debug.generate-debug-info, add --generate-debug-info to the compiler
  314.      * options so that both JITted code and the boot image, if it is compiled on device, will
  315.      * include native debugging information.
  316.      */
  317.     property_get("debug.generate-debug-info", propBuf, "");
  318.     bool generate_debug_info = (strcmp(propBuf, "true") == 0);
  319.     if (generate_debug_info) {
  320.         addOption("-Xcompiler-option");
  321.         addOption("--generate-debug-info");
  322.     }
  323.     // The mini-debug-info makes it possible to backtrace through compiled code.
  324.     bool generate_mini_debug_info = property_get_bool("dalvik.vm.minidebuginfo", 0);
  325.     if (generate_mini_debug_info) {
  326.         addOption("-Xcompiler-option");
  327.         addOption("--generate-mini-debug-info");
  328.     }
  329.     property_get("dalvik.vm.dex2oat-flags", dex2oatFlagsBuf, "");
  330.     parseExtraOpts(dex2oatFlagsBuf, "-Xcompiler-option");
  331.     /* extra options; parse this late so it overrides others */
  332.     property_get("dalvik.vm.extra-opts", extraOptsBuf, "");
  333.     parseExtraOpts(extraOptsBuf, NULL);
  334.     // Extra options for boot image generation.
  335.     parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xms", dex2oatXmsImageFlagsBuf,
  336.                                "-Xms", "-Ximage-compiler-option");
  337.     parseCompilerRuntimeOption("dalvik.vm.image-dex2oat-Xmx", dex2oatXmxImageFlagsBuf,
  338.                                "-Xmx", "-Ximage-compiler-option");
  339.     parseCompilerOption("dalvik.vm.image-dex2oat-filter", dex2oatImageCompilerFilterBuf,
  340.                         "--compiler-filter=", "-Ximage-compiler-option");
  341.     // If there is a dirty-image-objects file, push it.
  342.     if (hasFile("/system/etc/dirty-image-objects")) {
  343.         addOption("-Ximage-compiler-option");
  344.         addOption("--dirty-image-objects=/system/etc/dirty-image-objects");
  345.     }
  346.     parseCompilerOption("dalvik.vm.image-dex2oat-threads", dex2oatThreadsImageBuf, "-j",
  347.                         "-Ximage-compiler-option");
  348.     parseCompilerOption("dalvik.vm.image-dex2oat-cpu-set", dex2oatCpuSetImageBuf, "--cpu-set=",
  349.                         "-Ximage-compiler-option");
  350.     // The runtime may compile a boot image, when necessary, not using installd. Thus, we need
  351.     // to pass the instruction-set-features/variant as an image-compiler-option.
  352.     // Note: it is OK to reuse the buffer, as the values are exactly the same between
  353.     //       * compiler-option, used for runtime compilation (DexClassLoader)
  354.     //       * image-compiler-option, used for boot-image compilation on device
  355.     parseCompilerOption(dex2oat_isa_variant_key, dex2oat_isa_variant,
  356.                         "--instruction-set-variant=", "-Ximage-compiler-option");
  357.     parseCompilerOption(dex2oat_isa_features_key, dex2oat_isa_features,
  358.                         "--instruction-set-features=", "-Ximage-compiler-option");
  359.     if (generate_debug_info) {
  360.         addOption("-Ximage-compiler-option");
  361.         addOption("--generate-debug-info");
  362.     }
  363.     if (generate_mini_debug_info) {
  364.         addOption("-Ximage-compiler-option");
  365.         addOption("--generate-mini-debug-info");
  366.     }
  367.     property_get("dalvik.vm.image-dex2oat-flags", dex2oatImageFlagsBuf, "");
  368.     parseExtraOpts(dex2oatImageFlagsBuf, "-Ximage-compiler-option");
  369.     /* Set the properties for locale */
  370.     {
  371.         strcpy(localeOption, "-Duser.locale=");
  372.         const std::string locale = readLocale();
  373.         strncat(localeOption, locale.c_str(), PROPERTY_VALUE_MAX);
  374.         addOption(localeOption);
  375.     }
  376.     // Trace files are stored in /data/misc/trace which is writable only in debug mode.
  377.     property_get("ro.debuggable", propBuf, "0");
  378.     if (strcmp(propBuf, "1") == 0) {
  379.         property_get("dalvik.vm.method-trace", propBuf, "false");
  380.         if (strcmp(propBuf, "true") == 0) {
  381.             addOption("-Xmethod-trace");
  382.             parseRuntimeOption("dalvik.vm.method-trace-file",
  383.                                methodTraceFileBuf,
  384.                                "-Xmethod-trace-file:");
  385.             parseRuntimeOption("dalvik.vm.method-trace-file-siz",
  386.                                methodTraceFileSizeBuf,
  387.                                "-Xmethod-trace-file-size:");
  388.             property_get("dalvik.vm.method-trace-stream", propBuf, "false");
  389.             if (strcmp(propBuf, "true") == 0) {
  390.                 addOption("-Xmethod-trace-stream");
  391.             }
  392.         }
  393.     }
  394.     // Native bridge library. "0" means that native bridge is disabled.
  395.     //
  396.     // Note: bridging is only enabled for the zygote. Other runs of
  397.     //       app_process may not have the permissions to mount etc.
  398.     property_get("ro.dalvik.vm.native.bridge", propBuf, "");
  399.     if (propBuf[0] == '\0') {
  400.         ALOGW("ro.dalvik.vm.native.bridge is not expected to be empty");
  401.     } else if (zygote && strcmp(propBuf, "0") != 0) {
  402.         snprintf(nativeBridgeLibrary, sizeof("-XX:NativeBridge=") + PROPERTY_VALUE_MAX,
  403.                  "-XX:NativeBridge=%s", propBuf);
  404.         addOption(nativeBridgeLibrary);
  405.     }
  406. #if defined(__LP64__)
  407.     const char* cpu_abilist_property_name = "ro.product.cpu.abilist64";
  408. #else
  409.     const char* cpu_abilist_property_name = "ro.product.cpu.abilist32";
  410. #endif  // defined(__LP64__)
  411.     property_get(cpu_abilist_property_name, propBuf, "");
  412.     if (propBuf[0] == '\0') {
  413.         ALOGE("%s is not expected to be empty", cpu_abilist_property_name);
  414.         return -1;
  415.     }
  416.     snprintf(cpuAbiListBuf, sizeof(cpuAbiListBuf), "--cpu-abilist=%s", propBuf);
  417.     addOption(cpuAbiListBuf);
  418.     // Dalvik-cache pruning counter.
  419.     parseRuntimeOption("dalvik.vm.zygote.max-boot-retry", cachePruneBuf,
  420.                        "-Xzygote-max-boot-retry=");
  421.     // If set, the property below can be used to enable core platform API violation reporting.
  422.     property_get("persist.debug.dalvik.vm.core_platform_api_policy", propBuf, "");
  423.     if (propBuf[0] != '\0') {
  424.       snprintf(corePlatformApiPolicyBuf,
  425.                sizeof(corePlatformApiPolicyBuf),
  426.                "-Xcore-platform-api-policy:%s",
  427.                propBuf);
  428.       addOption(corePlatformApiPolicyBuf);
  429.     }
  430.     /*
  431.      * Retrieve the build fingerprint and provide it to the runtime. That way, ANR dumps will
  432.      * contain the fingerprint and can be parsed.
  433.      * Fingerprints are potentially longer than PROPERTY_VALUE_MAX, so parseRuntimeOption() cannot
  434.      * be used here.
  435.      * Do not ever re-assign fingerprintBuf as its c_str() value is stored in mOptions.
  436.      */
  437.     std::string fingerprint = GetProperty("ro.build.fingerprint", "");
  438.     if (!fingerprint.empty()) {
  439.         fingerprintBuf = "-Xfingerprint:" + fingerprint;
  440.         addOption(fingerprintBuf.c_str());
  441.     }
  442.     initArgs.version = JNI_VERSION_1_4;
  443.     initArgs.options = mOptions.editArray();
  444.     initArgs.nOptions = mOptions.size();
  445.     initArgs.ignoreUnrecognized = JNI_FALSE;
  446.     /*
  447.      * Initialize the VM.
  448.      *
  449.      * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
  450.      * If this call succeeds, the VM is ready, and we can start issuing
  451.      * JNI calls.
  452.      */
  453.     if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
  454.         ALOGE("JNI_CreateJavaVM failed\n");
  455.         return -1;
  456.     }
  457.     return 0;
  458. }
复制代码
注册JNI

将gRegJNI数组里的JNI方法进行注册。RegJNIRec 包含100+个JNI方法。
  1. /*static*/ int AndroidRuntime::startReg(JNIEnv* env)
  2. {
  3.     ATRACE_NAME("RegisterAndroidNatives");
  4.     /*
  5.      * This hook causes all future threads created in this process to be
  6.      * attached to the JavaVM.  (This needs to go away in favor of JNI
  7.      * Attach calls.)
  8.      */
  9.     androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
  10.     ALOGV("--- registering native functions ---\n");
  11.     /*
  12.      * Every "register" function calls one or more things that return
  13.      * a local reference (e.g. FindClass).  Because we haven't really
  14.      * started the VM yet, they're all getting stored in the base frame
  15.      * and never released.  Use Push/Pop to manage the storage.
  16.      */
  17.     env->PushLocalFrame(200);
  18. //核心步骤:将gRegJNI数组里的JNI方法进行注册。
  19.     if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
  20.         env->PopLocalFrame(NULL);
  21.         return -1;
  22.     }
  23.     env->PopLocalFrame(NULL);
  24.     //createJavaThread("fubar", quickTest, (void*) "hello");
  25.     return 0;
  26. }
复制代码
  1. static const RegJNIRec gRegJNI[] = {
  2.         REG_JNI(register_com_android_internal_os_RuntimeInit),
  3.         REG_JNI(register_com_android_internal_os_ZygoteInit_nativeZygoteInit),
  4.         REG_JNI(register_android_os_SystemClock),
  5.         REG_JNI(register_android_util_CharsetUtils),
  6.         REG_JNI(register_android_util_EventLog),
  7.         REG_JNI(register_android_util_Log),
  8.         REG_JNI(register_android_util_MemoryIntArray),
  9.         REG_JNI(register_android_app_admin_SecurityLog),
  10.         REG_JNI(register_android_content_AssetManager),
  11.         REG_JNI(register_android_content_StringBlock),
  12.         REG_JNI(register_android_content_XmlBlock),
  13.         REG_JNI(register_android_content_res_ApkAssets),
  14.         REG_JNI(register_android_content_res_ResourceTimer),
  15.         REG_JNI(register_android_text_AndroidCharacter),
  16.         REG_JNI(register_android_text_Hyphenator),
  17.         REG_JNI(register_android_view_InputDevice),
  18.         REG_JNI(register_android_view_KeyCharacterMap),
  19.         REG_JNI(register_android_os_Process),
  20.         REG_JNI(register_android_os_SystemProperties),
  21.         REG_JNI(register_android_os_Binder),
  22.         REG_JNI(register_android_os_Parcel),
  23.         REG_JNI(register_android_os_PerformanceHintManager),
  24.         REG_JNI(register_android_os_HidlMemory),
  25.         REG_JNI(register_android_os_HidlSupport),
  26.         REG_JNI(register_android_os_HwBinder),
  27.         REG_JNI(register_android_os_HwBlob),
  28.         REG_JNI(register_android_os_HwParcel),
  29.         REG_JNI(register_android_os_HwRemoteBinder),
  30.         REG_JNI(register_android_os_NativeHandle),
  31.         REG_JNI(register_android_os_ServiceManager),
  32.         REG_JNI(register_android_os_ServiceManagerNative),
  33.         REG_JNI(register_android_os_storage_StorageManager),
  34.         REG_JNI(register_android_service_DataLoaderService),
  35.         REG_JNI(register_android_view_DisplayEventReceiver),
  36.         REG_JNI(register_android_view_Surface),
  37.         REG_JNI(register_android_view_SurfaceControl),
  38.         REG_JNI(register_android_view_SurfaceControlHdrLayerInfoListener),
  39.         REG_JNI(register_android_view_SurfaceSession),
  40.         REG_JNI(register_android_view_InputApplicationHandle),
  41.         // This must be called after register_android_view_SurfaceControl since it has a dependency
  42.         // on the Java SurfaceControl object that references a native resource via static request.
  43.         REG_JNI(register_android_view_InputWindowHandle),
  44.         REG_JNI(register_android_view_CompositionSamplingListener),
  45.         REG_JNI(register_android_view_TextureView),
  46.         REG_JNI(register_android_view_TunnelModeEnabledListener),
  47.         REG_JNI(register_com_google_android_gles_jni_EGLImpl),
  48.         REG_JNI(register_com_google_android_gles_jni_GLImpl),
  49.         REG_JNI(register_android_opengl_jni_EGL14),
  50.         REG_JNI(register_android_opengl_jni_EGL15),
  51.         REG_JNI(register_android_opengl_jni_EGLExt),
  52.         REG_JNI(register_android_opengl_jni_GLES10),
  53.         REG_JNI(register_android_opengl_jni_GLES10Ext),
  54.         REG_JNI(register_android_opengl_jni_GLES11),
  55.         REG_JNI(register_android_opengl_jni_GLES11Ext),
  56.         REG_JNI(register_android_opengl_jni_GLES20),
  57.         REG_JNI(register_android_opengl_jni_GLES30),
  58.         REG_JNI(register_android_opengl_jni_GLES31),
  59.         REG_JNI(register_android_opengl_jni_GLES31Ext),
  60.         REG_JNI(register_android_opengl_jni_GLES32),
  61.         REG_JNI(register_android_graphics_classes),
  62.         REG_JNI(register_android_graphics_BLASTBufferQueue),
  63.         REG_JNI(register_android_graphics_GraphicBuffer),
  64.         REG_JNI(register_android_graphics_GraphicsStatsService),
  65.         REG_JNI(register_android_graphics_SurfaceTexture),
  66.         REG_JNI(register_android_database_CursorWindow),
  67.         REG_JNI(register_android_database_SQLiteConnection),
  68.         REG_JNI(register_android_database_SQLiteGlobal),
  69.         REG_JNI(register_android_database_SQLiteDebug),
  70.         REG_JNI(register_android_database_SQLiteRawStatement),
  71.         REG_JNI(register_android_os_Debug),
  72.         REG_JNI(register_android_os_FileObserver),
  73.         REG_JNI(register_android_os_GraphicsEnvironment),
  74.         REG_JNI(register_android_os_MessageQueue),
  75.         REG_JNI(register_android_os_SELinux),
  76.         REG_JNI(register_android_os_Trace),
  77.         REG_JNI(register_android_os_UEventObserver),
  78.         REG_JNI(register_android_net_LocalSocketImpl),
  79.         REG_JNI(register_android_os_MemoryFile),
  80.         REG_JNI(register_android_os_SharedMemory),
  81.         REG_JNI(register_android_os_incremental_IncrementalManager),
  82.         REG_JNI(register_com_android_internal_content_om_OverlayConfig),
  83.         REG_JNI(register_com_android_internal_content_om_OverlayManagerImpl),
  84.         REG_JNI(register_com_android_internal_net_NetworkUtilsInternal),
  85.         REG_JNI(register_com_android_internal_os_ClassLoaderFactory),
  86.         REG_JNI(register_com_android_internal_os_LongArrayMultiStateCounter),
  87.         REG_JNI(register_com_android_internal_os_LongMultiStateCounter),
  88.         REG_JNI(register_com_android_internal_os_Zygote),
  89.         REG_JNI(register_com_android_internal_os_ZygoteCommandBuffer),
  90.         REG_JNI(register_com_android_internal_os_ZygoteInit),
  91.         REG_JNI(register_com_android_internal_security_VerityUtils),
  92.         REG_JNI(register_com_android_internal_util_VirtualRefBasePtr),
  93.         REG_JNI(register_android_hardware_Camera),
  94.         REG_JNI(register_android_hardware_camera2_CameraMetadata),
  95.         REG_JNI(register_android_hardware_camera2_DngCreator),
  96.         REG_JNI(register_android_hardware_camera2_impl_CameraExtensionJpegProcessor),
  97.         REG_JNI(register_android_hardware_camera2_utils_SurfaceUtils),
  98.         REG_JNI(register_android_hardware_display_DisplayManagerGlobal),
  99.         REG_JNI(register_android_hardware_HardwareBuffer),
  100.         REG_JNI(register_android_hardware_OverlayProperties),
  101.         REG_JNI(register_android_hardware_SensorManager),
  102.         REG_JNI(register_android_hardware_SerialPort),
  103.         REG_JNI(register_android_hardware_SyncFence),
  104.         REG_JNI(register_android_hardware_UsbDevice),
  105.         REG_JNI(register_android_hardware_UsbDeviceConnection),
  106.         REG_JNI(register_android_hardware_UsbRequest),
  107.         REG_JNI(register_android_hardware_location_ActivityRecognitionHardware),
  108.         REG_JNI(register_android_media_AudioDeviceAttributes),
  109.         REG_JNI(register_android_media_AudioEffectDescriptor),
  110.         REG_JNI(register_android_media_AudioSystem),
  111.         REG_JNI(register_android_media_AudioRecord),
  112.         REG_JNI(register_android_media_AudioTrack),
  113.         REG_JNI(register_android_media_AudioAttributes),
  114.         REG_JNI(register_android_media_AudioProductStrategies),
  115.         REG_JNI(register_android_media_AudioVolumeGroups),
  116.         REG_JNI(register_android_media_AudioVolumeGroupChangeHandler),
  117.         REG_JNI(register_android_media_MediaMetrics),
  118.         REG_JNI(register_android_media_MicrophoneInfo),
  119.         REG_JNI(register_android_media_RemoteDisplay),
  120.         REG_JNI(register_android_media_ToneGenerator),
  121.         REG_JNI(register_android_media_audio_common_AidlConversion),
  122.         REG_JNI(register_android_media_midi),
  123.         REG_JNI(register_android_opengl_classes),
  124.         REG_JNI(register_android_ddm_DdmHandleNativeHeap),
  125.         REG_JNI(register_android_backup_BackupDataInput),
  126.         REG_JNI(register_android_backup_BackupDataOutput),
  127.         REG_JNI(register_android_backup_FileBackupHelperBase),
  128.         REG_JNI(register_android_backup_BackupHelperDispatcher),
  129.         REG_JNI(register_android_app_backup_FullBackup),
  130.         REG_JNI(register_android_app_Activity),
  131.         REG_JNI(register_android_app_ActivityThread),
  132.         REG_JNI(register_android_app_NativeActivity),
  133.         REG_JNI(register_android_util_jar_StrictJarFile),
  134.         REG_JNI(register_android_view_InputChannel),
  135.         REG_JNI(register_android_view_InputEventReceiver),
  136.         REG_JNI(register_android_view_InputEventSender),
  137.         REG_JNI(register_android_view_InputQueue),
  138.         REG_JNI(register_android_view_KeyEvent),
  139.         REG_JNI(register_android_view_MotionEvent),
  140.         REG_JNI(register_android_view_MotionPredictor),
  141.         REG_JNI(register_android_view_PointerIcon),
  142.         REG_JNI(register_android_view_VelocityTracker),
  143.         REG_JNI(register_android_view_VerifiedKeyEvent),
  144.         REG_JNI(register_android_view_VerifiedMotionEvent),
  145.         REG_JNI(register_android_content_res_ObbScanner),
  146.         REG_JNI(register_android_content_res_Configuration),
  147.         REG_JNI(register_android_animation_PropertyValuesHolder),
  148.         REG_JNI(register_android_security_Scrypt),
  149.         REG_JNI(register_com_android_internal_content_F2fsUtils),
  150.         REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
  151.         REG_JNI(register_com_android_internal_os_FuseAppLoop),
  152.         REG_JNI(register_com_android_internal_os_KernelAllocationStats),
  153.         REG_JNI(register_com_android_internal_os_KernelCpuBpfTracking),
  154.         REG_JNI(register_com_android_internal_os_KernelCpuTotalBpfMapReader),
  155.         REG_JNI(register_com_android_internal_os_KernelCpuUidBpfMapReader),
  156.         REG_JNI(register_com_android_internal_os_KernelSingleProcessCpuThreadReader),
  157.         REG_JNI(register_com_android_internal_os_KernelSingleUidTimeReader),
  158.         REG_JNI(register_android_window_WindowInfosListener),
  159.         REG_JNI(register_android_window_ScreenCapture),
  160.         REG_JNI(register_jni_common),
  161.         REG_JNI(register_android_tracing_PerfettoDataSource),
  162.         REG_JNI(register_android_tracing_PerfettoDataSourceInstance),
  163.         REG_JNI(register_android_tracing_PerfettoProducer),
  164. };
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

玛卡巴卡的卡巴卡玛

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表