标签:
android启动流程文章已经概述了android的启动流程,而andoird 5.0的流程其实也差不多,少数不同而已。
如下图:
整个启动流程与之前的一样,唯一不同的是android L支持64位的app,所以又起一个Zygote64来专门负责64位APK的孵化。
而且创建Zygote进程脚本在init.zygoteXX.rc里。
如下:
system/core/rootdir/init.zygote64_32.rc system/core/rootdir/init.zygote64.rc system/core/rootdir/init.zygote32.rc system/core/rootdir/init.zygote32_64.rc
64位芯片通常会选择
system/core/rootdir/init.zygote64_32.rc
咱们来看下内容,分析创建了两个zygote。
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote class main socket zygote stream 660 root system onrestart write /sys/android_power/request_state wake onrestart write /sys/power/state on onrestart restart media onrestart restart netd service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary class main socket zygote_secondary stream 660 root system onrestart restart zygote
kernel/init/main.c asmlinkage void __init start_kernel(void)//这是kernel的入口,汇编head-common.S会链过来。 { ... /* Do the rest non-__init'ed, we're now alive */ rest_init(); }
static noinline void __init_refok rest_init(void) { ... kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND); ... }
static int __ref kernel_init(void *unused) { kernel_init_freeable();//指定init文件位置,新增的函数,与之前的系统不同。 <span style="white-space:pre"> </span>... if (ramdisk_execute_command) { if (!run_init_process(ramdisk_execute_command))//调用run_init_process,init进程跑进来 return 0; pr_err("Failed to execute %s\n", ramdisk_execute_command); } <span style="white-space:pre"> </span>.... }kernel_init_freeable()实现
static noinline void __init kernel_init_freeable(void) { ... if (!ramdisk_execute_command) ramdisk_execute_command = "/init";//指定init文件位置 if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) { ramdisk_execute_command = NULL; prepare_namespace(); } ... }
init.rc service servicemanager /system/bin/servicemanager//看到吧 class core user system group system critical onrestart restart healthd onrestart restart zygote onrestart restart media onrestart restart surfaceflinger onrestart restart drm下面是servicemanager部分代码,它负责管理本地系统服务和Java系统服务,为下面的本地系统系服,java系统服务的注册提供服务
frameworks/native/cmds/servicemanager/service_manager.c uint32_t do_find_service(struct binder_state *bs, const uint16_t *s, size_t len, uid_t uid, pid_t spid) { } int do_add_service(struct binder_state *bs, const uint16_t *s, size_t len, uint32_t handle, uid_t uid, int allow_isolated, pid_t spid) { } int main(int argc, char **argv) { struct binder_state *bs; bs = binder_open(128*1024); ... selinux_enabled = is_selinux_enabled(); sehandle = selinux_android_service_context_handle();//增加了selinux方面的内容 if (selinux_enabled > 0) { if (sehandle == NULL) { ALOGE("SELinux: Failed to acquire sehandle. Aborting.\n"); abort(); } if (getcon(&service_manager_context) != 0) { ALOGE("SELinux: Failed to acquire service_manager context. Aborting.\n"); abort(); } } union selinux_callback cb; cb.func_audit = audit_callback; selinux_set_callback(SELINUX_CB_AUDIT, cb);//很多地方都用到 cb.func_log = selinux_log_callback; selinux_set_callback(SELINUX_CB_LOG, cb); svcmgr_handle = BINDER_SERVICE_MANAGER; binder_loop(bs, svcmgr_handler); return 0; }从是上面知道servicemanager除了什么的service的注册服务外,还在SELinux安全领域做了工作,因为android L已经完全打开SELinux的功能。
init.rc service media /system/bin/mediaserver//这样启动 class main user media group audio camera inet net_bt net_bt_admin net_bw_acct drmrpc mediadrm qcom_diag ioprio rt 4
frameworks/av/media/mediaserver/main_mediaserver.cpp int main(int argc __unused, char** argv) { ... ALOGI("ServiceManager: %p", sm.get()); AudioFlinger::instantiate();//启动AudioFlinger服务 MediaPlayerService::instantiate();//启动MediaPlayerService服务 CameraService::instantiate();//启动CameraService服务 #ifdef AUDIO_LISTEN_ENABLED ALOGI("ListenService instantiated"); ListenService::instantiate(); #endif AudioPolicyService::instantiate(); SoundTriggerHwService::instantiate(); registerExtensions(); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); } }
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote//zygote64通过app_process64进程启动 class main socket zygote stream 660 root system onrestart write /sys/android_power/request_state wake onrestart write /sys/power/state on onrestart restart media onrestart restart netd service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary//zygote通过app_process32进程启动 class main socket zygote_secondary stream 660 root system onrestart restart zygote分别通过app_process64,app_process32两个app_process进程来启动zygote64,zygote。
frameworks/base/cmds/app_process/app_main.cpp #if defined(__LP64__) static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist64"; static const char ZYGOTE_NICE_NAME[] = "zygote64";//64位zygote进程的名字 #else static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist32"; static const char ZYGOTE_NICE_NAME[] = "zygote"; #endif int main(int argc, char* const argv[]) { ... while (i < argc) { const char* arg = argv[i++]; if (strcmp(arg, "--zygote") == 0) { zygote = true; niceName = ZYGOTE_NICE_NAME;//根据64还是32,指定zygote进程的名字 } ... } ... if (!niceName.isEmpty()) { runtime.setArgv0(niceName.string()); set_process_name(niceName.string());//设置进程名字 } if (zygote) { runtime.start("com.android.internal.os.ZygoteInit", args);//启动zygote进程 } ... }
frameworks/base/core/jni/AndroidRuntime.cpp void AndroidRuntime::start(const char* className, const Vector<String8>& options) { ALOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n", className != NULL ? className : "(unknown)"); ... //下面就是启动java进程,调用了java中的main函数入口 /* * Start VM. This thread becomes the main thread of the VM, and will * not return until the VM exits. */ char* slashClassName = toSlashClassName(className); jclass startClass = env->FindClass(slashClassName); if (startClass == NULL) { ALOGE("JavaVM unable to locate class '%s'\n", slashClassName); /* keep going */ } else { jmethodID startMeth = env->GetStaticMethodID(startClass, "main", "([Ljava/lang/String;)V"); if (startMeth == NULL) { ALOGE("JavaVM unable to find main() in '%s'\n", className); /* keep going */ } else { env->CallStaticVoidMethod(startClass, startMeth, strArray); #if 0 if (env->ExceptionCheck()) threadExitUncaughtException(env); #endif } } free(slashClassName); ALOGD("Shutting down VM\n"); if (mJavaVM->DetachCurrentThread() != JNI_OK) ALOGW("Warning: unable to detach main thread\n"); if (mJavaVM->DestroyJavaVM() != 0) ALOGW("Warning: VM did not shut down cleanly\n"); }
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java public static void main(String argv[]) { try { ... registerZygoteSocket(socketName);//注册listener接口 ... if (startSystemServer) { startSystemServer(abiList, socketName);//启动system server } Log.i(TAG, "Accepting command socket connections"); runSelectLoop(abiList); closeServerSocket(); } catch (MethodAndArgsCaller caller) { caller.run(); } catch (RuntimeException ex) { Log.e(TAG, "Zygote died with exception", ex); closeServerSocket(); throw ex; } }
frameworks/base/services/java/com/android/server/SystemServer.java public static void main(String[] args) { new SystemServer().run();//调用run() }SystemServer的main函数直接调用run()
private void run() { ... // Start services. try { startBootstrapServices();//启动一系列Java系统服务 startCoreServices(); startOtherServices(); } catch (Throwable ex) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting system services", ex); throw ex; } ... }
private void startOtherServices() { ... Slog.i(TAG, "Content Manager"); contentService = ContentService.main(context, mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL); Slog.i(TAG, "System Content Providers"); mActivityManagerService.installSystemProviders(); Slog.i(TAG, "Vibrator Service"); vibrator = new VibratorService(context); ServiceManager.addService("vibrator", vibrator); Slog.i(TAG, "Consumer IR Service"); consumerIr = new ConsumerIrService(context); ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr); mAlarmManagerService = mSystemServiceManager.startService(AlarmManagerService.class); alarm = IAlarmManager.Stub.asInterface( ServiceManager.getService(Context.ALARM_SERVICE)); Slog.i(TAG, "Init Watchdog"); final Watchdog watchdog = Watchdog.getInstance(); watchdog.init(context, mActivityManagerService); ... }
private void startOtherServices() { ... mActivityManagerService.systemReady(new Runnable() { @Override public void run() { ... } }); ... }
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java public void systemReady(final Runnable goingCallback) { synchronized(this) { if (mSystemReady) { // If we're done calling all the receivers, run the next "boot phase" passed in // by the SystemServer if (goingCallback != null) { goingCallback.run(); } return; } ... mStackSupervisor.resumeTopActivitiesLocked();//启动HomeActivity sendUserSwitchBroadcastsLocked(-1, mCurrentUserId); } }
frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java boolean resumeTopActivitiesLocked() { return resumeTopActivitiesLocked(null, null, null); } boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target, Bundle targetOptions) { if (targetStack == null) { targetStack = getFocusedStack(); } // Do targetStack first. boolean result = false; if (isFrontStack(targetStack)) { result = targetStack.resumeTopActivityLocked(target, targetOptions); } for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) { final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks; for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) { final ActivityStack stack = stacks.get(stackNdx); if (stack == targetStack) { // Already started above. continue; } if (isFrontStack(stack)) { stack.resumeTopActivityLocked(null);//调用stack.resumeTopActivityLocked() } } } return result; }
frameworks/base/services/java/com/android/server/SystemServer.java private void startOtherServices() { ... mActivityManagerService.setWindowManager(wm); ... }
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java public void setWindowManager(WindowManagerService wm) { mWindowManager = wm; mStackSupervisor.setWindowManager(wm);//调用这里 }
frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java void setWindowManager(WindowManagerService wm) { synchronized (mService) { ... createStackOnDisplay(HOME_STACK_ID, Display.DEFAULT_DISPLAY);//创建HOME_STACK,与之前系统有所不同 mHomeStack = mFocusedStack = mLastFocusedStack = getStack(HOME_STACK_ID); ... } }
private int createStackOnDisplay(int stackId, int displayId) { ActivityDisplay activityDisplay = mActivityDisplays.get(displayId); if (activityDisplay == null) { return -1; } ActivityContainer activityContainer = new ActivityContainer(stackId); mActivityContainers.put(stackId, activityContainer);//将HOME_STACK放入Activitycontainer中 activityContainer.attachToDisplayLocked(activityDisplay); return stackId; }
ActivityStack getStack(int stackId) { ActivityContainer activityContainer = mActivityContainers.get(stackId); if (activityContainer != null) { return activityContainer.mStack; } return null; }
frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target, Bundle targetOptions) { ..... if (stack == targetStack) { // Already started above. continue; } if (isFrontStack(stack)) { stack.resumeTopActivityLocked(null);//调用stack.resumeTopActivityLocked() } .... }
frameworks/base/services/core/java/com/android/server/am/ActivityStack.java final boolean resumeTopActivityLocked(ActivityRecord prev) { return resumeTopActivityLocked(prev, null); } final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) { ... result = resumeTopActivityInnerLocked(prev, options); ... } final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) { ... final TaskRecord prevTask = prev != null ? prev.task : null; if (next == null) { // There are no more activities! Let's just start up the // Launcher... ActivityOptions.abort(options); if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: No more activities go home"); if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); // Only resume home if on home display final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ? HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo(); return isOnHomeDisplay() && mStackSupervisor.resumeHomeStackTask(returnTaskType, prev);//调用 } ... }
frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java boolean resumeHomeStackTask(int homeStackTaskType, ActivityRecord prev) { if (!mService.mBooting && !mService.mBooted) { // Not ready yet! return false; } if (homeStackTaskType == RECENTS_ACTIVITY_TYPE) { mWindowManager.showRecentApps(); return false; } moveHomeStackTaskToTop(homeStackTaskType); if (prev != null) { prev.task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE); } ActivityRecord r = mHomeStack.topRunningActivityLocked(null); // if (r != null && (r.isHomeActivity() || r.isRecentsActivity())) { if (r != null && r.isHomeActivity()) { mService.setFocusedActivityLocked(r); return resumeTopActivitiesLocked(mHomeStack, prev, null); } return mService.startHomeActivityLocked(mCurrentUser);//调用 }
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java boolean startHomeActivityLocked(int userId) { if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL && mTopAction == null) { // We are running in factory test mode, but unable to find // the factory test app, so just sit around displaying the // error message and don't try to start anything. return false; } Intent intent = getHomeIntent(); ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId); if (aInfo != null) { intent.setComponent(new ComponentName( aInfo.applicationInfo.packageName, aInfo.name)); // Don't do this if the home app is currently being // instrumented. aInfo = new ActivityInfo(aInfo); aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId); ProcessRecord app = getProcessRecordLocked(aInfo.processName, aInfo.applicationInfo.uid, true); if (app == null || app.instrumentationClass == null) { intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); mStackSupervisor.startHomeActivity(intent, aInfo); } } return true; }
标签:
原文地址:http://blog.csdn.net/hovan/article/details/42737955