//减临时引用计数 if (target_thread) binder_thread_dec_tmpref(target_thread); binder_proc_dec_tmpref(target_proc); if (target_node) binder_dec_node_tmpref(target_node);
public SystemService startServiceFromJar(String className, String path){ PathClassLoader pathClassLoader = mLoadedPaths.get(path); if (pathClassLoader == null) { // NB: the parent class loader should always be the system server class loader. // Changing it has implications that require discussion with the mainline team. pathClassLoader = new PathClassLoader(path, this.getClass().getClassLoader()); mLoadedPaths.put(path, pathClassLoader); } final Class<SystemService> serviceClass = loadClassFromLoader(className, pathClassLoader); return startService(serviceClass); }
接着我们看看Class为参数的startService方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public <T extends SystemService> T startService(Class<T> serviceClass){ final String name = serviceClass.getName();
// Create the service. if (!SystemService.class.isAssignableFrom(serviceClass)) { thrownew RuntimeException("Failed to create " + name + ": service must extend " + SystemService.class.getName()); } final T service; try { Constructor<T> constructor = serviceClass.getConstructor(Context.class); service = constructor.newInstance(mContext); } catch (...) { ... }
publicvoidstartBootPhase(@NonNull TimingsTraceAndSlog t, int phase){ if (phase <= mCurrentPhase) { thrownew IllegalArgumentException("Next phase must be larger than previous"); } mCurrentPhase = phase;
finalint serviceLen = mServices.size(); for (int i = 0; i < serviceLen; i++) { final SystemService service = mServices.get(i); service.onBootPhase(mCurrentPhase); }
if (phase == SystemService.PHASE_BOOT_COMPLETED) { SystemServerInitThreadPool.shutdown(); } }
staticintforkSystemServer(int uid, int gid, int[] gids, int runtimeFlags, int[][] rlimits, long permittedCapabilities, long effectiveCapabilities){ //停止其他线程 ZygoteHooks.preFork();
static jint com_android_internal_os_Zygote_nativeForkSystemServer( JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities){ ... pid_t pid = ForkCommon(env, true, fds_to_close, fds_to_ignore, true); if (pid == 0) { // System server prcoess does not need data isolation so no need to // know pkg_data_info_list. SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, permitted_capabilities, effective_capabilities, MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true, false, nullptr, nullptr, /* is_top_app= */false, /* pkg_data_info_list */nullptr, /* whitelisted_data_info_list */nullptr, false, false); } elseif (pid > 0) { ... gSystemServerPid = pid; //检查SystemServer进程状态 int status; if (waitpid(pid, &status, WNOHANG) == pid) { //如果SystemServer进程死亡,重启整个Zygote ALOGE("System server process %d has died. Restarting Zygote!", pid); RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!"); }
//如果是低内存设备,限制SystemServer进程使用内存大小 if (UsePerAppMemcg()) { if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) { ALOGE("couldn't add process %d into system memcg group", pid); } } } return pid; }
//均为nullptr auto se_info = extract_fn(managed_se_info); auto nice_name = extract_fn(managed_nice_name); auto instruction_set = extract_fn(managed_instruction_set); auto app_data_dir = extract_fn(managed_app_data_dir);
static jint com_android_internal_os_Zygote_nativeForkSystemServer( JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities){ ... if (pid == 0) { ... } elseif (pid > 0) { ... gSystemServerPid = pid; //检查SystemServer进程状态 int status; if (waitpid(pid, &status, WNOHANG) == pid) { //如果SystemServer进程死亡,重启整个Zygote ALOGE("System server process %d has died. Restarting Zygote!", pid); RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!"); }
//如果是低内存设备,限制SystemServer进程使用内存大小 if (UsePerAppMemcg()) { if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) { ALOGE("couldn't add process %d into system memcg group", pid); } } } return pid; }
try { cl = Class.forName(className, true, classLoader); } catch (ClassNotFoundException ex) { thrownew RuntimeException( "Missing class when invoking static main " + className, ex); }
Method m; try { m = cl.getMethod("main", new Class[] { String[].class }); } catch (NoSuchMethodException ex) { thrownew RuntimeException( "Missing static main on " + className, ex); } catch (SecurityException ex) { thrownew RuntimeException( "Problem getting static main on " + className, ex); }
int modifiers = m.getModifiers(); if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) { thrownew RuntimeException( "Main method is not public and static on " + className); }
/* * This throw gets caught in ZygoteInit.main(), which responds * by invoking the exception's run() method. This arrangement * clears up all the stack frames that were required in setting * up the process. */ returnnew MethodAndArgsCaller(m, argv); }
Vector<String8> args; if (!className.isEmpty()) { //这个分支不会进入Zygote模式 ... } else { // We're in zygote mode. //新建Dalvik缓存目录 maybeCreateDalvikCache();
//添加启动参数 if (startSystemServer) { args.add(String8("start-system-server")); }
char prop[PROP_VALUE_MAX]; if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) { LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.", ABI_LIST_PROPERTY); return11; }
// In zygote mode, pass all remaining arguments to the zygote // main() method. //Zygote模式下没有其他参数了 for (; i < argc; ++i) { args.add(String8(argv[i])); } }
if (!niceName.isEmpty()) { //设置程序名以及进程名 runtime.setArgv0(niceName.string(), true/* setProcName */); }
if (zygote) { //执行AndroidRuntime::start方法 runtime.start("com.android.internal.os.ZygoteInit", args, zygote); } elseif (className) { runtime.start("com.android.internal.os.RuntimeInit", args, zygote); } else { fprintf(stderr, "Error: no class name or --zygote supplied.\n"); app_usage(); LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied."); } }
voidAndroidRuntime::start(constchar* className, const Vector<String8>& options, bool zygote) { ... staticconst String8 startSystemServer("start-system-server"); // Whether this is the primary zygote, meaning the zygote which will fork system server. //64_32位兼容设备上会启动两个Zygote,一个叫zygote,一个叫zygote_secondary bool primary_zygote = false;
//有start-system-server选项则代表是主Zygote for (size_t i = 0; i < options.size(); ++i) { if (options[i] == startSystemServer) { primary_zygote = true; /* track our progress through the boot sequence */ constint LOG_BOOT_PROGRESS_START = 3000; LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START, ns2ms(systemTime(SYSTEM_TIME_MONOTONIC))); } }
scoped_local_ref<jclass> c(env, findClass(env, className)); ALOG_ALWAYS_FATAL_IF(c.get() == NULL, "Native registration unable to find class '%s'; aborting...", className);
int result = e->RegisterNatives(c.get(), gMethods, numMethods); ALOG_ALWAYS_FATAL_IF(result < 0, "RegisterNatives failed for '%s'; aborting...", className);
publicstaticvoidmain(String argv[]){ ZygoteServer zygoteServer = null; // Mark zygote start. This ensures that thread creation will throw // an error. //标记着zygote开始启动,不允许创建线程(Zygote必须保证单线程) ZygoteHooks.startZygoteNoThreadCreation(); // Zygote goes into its own process group. //设置进程组id try { Os.setpgid(0, 0); } catch (ErrnoException ex) { thrownew RuntimeException("Failed to setpgid(0,0)", ex); }
//创建socket zygoteServer = new ZygoteServer(isPrimaryZygote);
//启动SystemServer if (startSystemServer) { Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the // child (system_server) process. if (r != null) { r.run(); return; } }
// The select loop returns early in the child process after a fork and // loops forever in the zygote. //执行死循环监听socket,负责接收事件,启动App caller = zygoteServer.runSelectLoop(abiList); } catch (Throwable ex) { Log.e(TAG, "System zygote died with exception", ex); throw ex; } finally { if (zygoteServer != null) { zygoteServer.closeServerSocket(); } }
// We're in the child process and have exited the select loop. Proceed to execute the // command. //接收到AMS的启动App请求后,fork出子进程,处理App启动 if (caller != null) { caller.run(); } }
/** * Direct access to syscalls. Code should strongly prefer using {@link #os} * unless it has a strong reason to bypass the helpful checks/guards that it * provides. */ publicstaticfinal Os rawOs = new Linux();
/** * Access to syscalls with helpful checks/guards. * For read access only; the only supported way to update this field is via * {@link #compareAndSetOs}. */ @UnsupportedAppUsage publicstaticvolatile Os os = new BlockGuardOs(rawOs);
try { cl = Class.forName(className, true, classLoader); } catch (ClassNotFoundException ex) { thrownew RuntimeException( "Missing class when invoking static main " + className, ex); }
Method m; try { m = cl.getMethod("main", new Class[] { String[].class }); } catch (NoSuchMethodException ex) { thrownew RuntimeException( "Missing static main on " + className, ex); } catch (SecurityException ex) { thrownew RuntimeException( "Problem getting static main on " + className, ex); }
int modifiers = m.getModifiers(); if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) { thrownew RuntimeException( "Main method is not public and static on " + className); }
/* * This throw gets caught in ZygoteInit.main(), which responds * by invoking the exception's run() method. This arrangement * clears up all the stack frames that were required in setting * up the process. */ returnnew MethodAndArgsCaller(m, argv); }