android开机启动流程说明
fmms
13年前
<p>第一步:启动<span style="font-family:Times New Roman;">linux</span></p> <p>1.Bootloader</p> <p>2.Kernel</p> <p>第二步 <span style="font-family:Times New Roman;">android</span><span style="font-family:宋体;">系统启动:入口为</span><span style="font-family:Times New Roman;">init.rc(system\core\rootdir)</span></p> <p>1./system/bin/service manager: Binder <span style="font-family:宋体;">守护进程;</span></p> <p>2.Runtime;</p> <p>3.Zygote :app-process/app-main;</p> <p>4.Start VM;</p> <p>5.Start server</p> <p>6.Start android service:Register to service Manager</p> <p>7.Start Launcher</p> <p>第三步:应用程序启动:运行<span style="font-family:Times New Roman;">package Manager</span></p> <p><span style="font-family:Times New Roman;"><br /> </span></p> <p><strong>l Init进程</strong></p> <p>Android系统在启动时首先会启动Linux系统,引导加载Linux Kernel并启动init进程。Init进程是一个由内核启动的用户级进程,是Android系统的第一个进程。该进程的相关代码在platform\system\core\init\init.c。在main函数中,有如下代码:</p> <p>open_devnull_stdio();<br /> log_init();<br /> <br /> INFO("reading config file\n");<br /> init_parse_config_file("/init.rc");<br /> <span style="color:#33cc00;"><br /> </span><span style="color:#33cc00;"> /* pull the kernel commandline and ramdisk properties file in */</span><br /> import_kernel_cmdline(0);<br /> <br /> get_hardware_name(hardware, &revision);<br /> snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);<br /> init_parse_config_file(tmp);</p> <p> 这里会加载解析init.rc和init.hardware.rc两个初始化脚本。*.rc文件定义了在init进程中需要启动哪些进程服务和执行哪些动作。其详细说明参见platform\system\core\init\reademe.txt。init.rc见如下定义:</p> <p>service servicemanager /system/bin/servicemanager<br /> user system<br /> critical<br /> onrestart restart zygote<br /> onrestart restart media<br /> <br /> service vold /system/bin/vold<br /> socket vold stream 0660 root mount<br /> ioprio be 2<br /> <br /> service netd /system/bin/netd<br /> socket netd stream 0660 root system<br /> socket dnsproxyd stream 0660 root inet<br /> <br /> service debuggerd /system/bin/debuggerd<br /> <br /> service ril-daemon /system/bin/rild<br /> socket rild stream 660 root radio<br /> socket rild-debug stream 660 radio system<br /> user root<br /> group radio cache inet misc audio sdcard_rw<br /> <br /> service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server<br /> socket zygote stream 666<br /> onrestart write /sys/android_power/request_state wake<br /> onrestart write /sys/power/state on<br /> onrestart restart media<br /> onrestart restart netd<br /> <br /> service drm /system/bin/drmserver<br /> user drm<br /> group system root inet</p> <p>具体解析过程见platform\system\core\init\Init_parser.c。解析所得服务添加到service_list中,动作添加到action_list中。</p> <p> </p> <p> </p> <p>接下来在main函数中执行动作和启动进程服务:</p> <p> execute_one_command();<br /> restart_processes()</p> <p>通常init过程需要创建一些系统文件夹并启动USB守护进程、Android Debug Bridge守护进程、Debug守护进程、ServiceManager进程、Zygote进程等。</p> <p> </p> <p><strong>l ServiceManager进程</strong></p> <p>ServiceManager进程是所有服务的管理器。由init.rc对ServiceManager的描述 service servicemanager /system/bin/servicemanager可知servicemanager进程从 platform\frameworks\base\cmd\servicemanager\Service_manager.cpp启动。在main函数中有如下代码:</p> <p>int main(int argc, char **argv)<br /> {<br /> struct binder_state *bs;<br /> void *svcmgr = BINDER_SERVICE_MANAGER;<br /> <br /> bs = binder_open(128*1024);<br /> <br /> if (binder_become_context_manager(bs)) {<br /> LOGE("cannot become context manager (%s)\n", strerror(errno));<br /> return -1;<br /> }<br /> <br /> svcmgr_handle = svcmgr;<br /> binder_loop(bs, svcmgr_handler);<br /> return 0;<br /> }</p> <p>首先调用binder_open()打开Binder设备(/dev/binder),调用binder_become_context_manager()把当前进程设置为ServiceManager。ServiceManager本身就是一个服务。</p> <p>int binder_become_context_manager(struct binder_state *bs)<br /> {<br /> return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0);<br /> }</p> <p> 最后binder_loop()进入循环状态,并设置svcmgr_handler回调函数等待添加、查询、获取服务等请求。</p> <p> </p> <p><strong>l Zygote进程</strong></p> <p> Zygote进程用于产生其他进程。由init.rc对zygote的描述service zygot /system/bin /app_process可知zygote进程从platfrom\frameworks\base\cmds\app_process \App_main.cpp启动。在main函数中有如下代码:</p> <p> if (0 == strcmp("--zygote", arg)) {<br /> bool startSystemServer = (i < argc) ? <br /> strcmp(argv[i], "--start-system-server") == 0 : false;<br /> setArgv0(argv0, "zygote");<br /> set_process_name("zygote");<br /> runtime.start("com.android.internal.os.ZygoteInit",<br /> startSystemServer);<br /> } else {<br /> set_process_name(argv0);<br /> <br /> runtime.mClassName = arg;<br /> <br /> <span style="color:#33cc00;"> </span><span style="color:#33cc00;"> // Remainder of args get passed to startup class main()</span><br /> runtime.mArgC = argc-i;<br /> runtime.mArgV = argv+i;<br /> <br /> LOGV("App process is starting with pid=%d, class=%s.\n",<br /> getpid(), runtime.getClassName());<br /> runtime.start();<br /> }</p> <p> 首先创建AppRuntime,即AndroidRuntime,建立了一个Dalvik虚拟机。通过这个runtime传递 com.android.internal.os.ZygoteInit参数,从而由Dalvik虚拟机运行ZygoteInit.java的 main(),开始创建Zygote进程。在其main()中,如下所示:</p> <p> registerZygoteSocket();<br /> EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,<br /> SystemClock.uptimeMillis());<br /> preloadClasses();<br /> <span style="color:#33cc00;"> //cacheRegisterMaps();</span><br /> preloadResources();<br /> EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,<br /> SystemClock.uptimeMillis());<br /> <span style="color:#009900;"><br /> </span><span style="color:#009900;"> <span style="color:#33cc00;"> // Finish profiling the zygote initialization.</span></span><br /> SamplingProfilerIntegration.writeZygoteSnapshot();<br /> <span style="color:#33cc00;"><br /> </span><span style="color:#33cc00;"> // Do an initial gc to clean up after startup</span><br /> gc();<br /> <br /> <span style="color:#33ff33;"> <span style="color:#33cc00;"> // If requested, start system server directly from Zygote</span></span><br /> if (argv.length != 2) {<br /> throw new RuntimeException(argv[0] + USAGE_STRING);<br /> }<br /> <br /> if (argv[1].equals("true")) {<br /> startSystemServer();<br /> } else if (!argv[1].equals("false")) {<br /> throw new RuntimeException(argv[0] + USAGE_STRING);<br /> }</p> <p> 首先通过registerZygoteSocket()登记端口,接着preloadClasses()装载相关类。这里大概要装载 1000多个类,具体装载类见platform\frameworks\base\preloaded-classes。这个文件有 WritePreloadedClassFile类自动生成。分析该类的main函数,有如下一段筛选类的代码:</p> <p> <span style="color:#33cc00;"> // Preload classes that were loaded by at least 2 processes. Hopefully,<br /> // the memory associated with these classes will be shared.</span><br /> for (LoadedClass loadedClass : root.loadedClasses.values()) {<br /> Set<String> names = loadedClass.processNames();<br /> if (!Policy.isPreloadable(loadedClass)) {<br /> continue;<br /> }<br /> <br /> if (names.size() >= MIN_PROCESSES ||<br /> (loadedClass.medianTimeMicros() > MIN_LOAD_TIME_MICROS && names.size() > 1)) {<br /> toPreload.add(loadedClass);<br /> }<br /> }<br /> <br /> int initialSize = toPreload.size();<br /> System.out.println(initialSize<br /> + " classses were loaded by more than one app.");<br /> <br /> // Preload eligable classes from applications (not long-running<br /> // services).<br /> for (Proc proc : root.processes.values()) {<br /> if (proc.fromZygote() && !Policy.isService(proc.name)) {<br /> for (Operation operation : proc.operations) {<br /> LoadedClass loadedClass = operation.loadedClass;<br /> if (shouldPreload(loadedClass)) {<br /> toPreload.add(loadedClass);<br /> }<br /> }<br /> }<br /> }</p> <p>其中MIN_LOAD_TIME_MICROS等于1250,当类的装载时间大于1.25ms,则需要预装载。</p> <p>Policy.isPreloadable()定于如下:</p> <p><span style="color:#33cc00;"> /**Reports if the given class should be preloaded. */</span><br /> public static boolean isPreloadable(LoadedClass clazz) {<br /> return clazz.systemClass && !EXCLUDED_CLASSES.contains(clazz.name);<br /> }</p> <p>其中EXCLUDED_CLASSES如下定义:</p> <p> <span style="color:#33cc00;"> /**<br /> * Classes which we shouldn't load from the Zygote.<br /> */</span><br /> private static final Set<String> EXCLUDED_CLASSES<br /> = new HashSet<String>(Arrays.asList(<br /> <span style="color:#33cc00;"> // Binders</span><br /> "android.app.AlarmManager",<br /> "android.app.SearchManager",<br /> "android.os.FileObserver",<br /> "com.android.server.PackageManagerService$AppDirObserver",<br /> <br /> <span style="color:#33cc00;"> // Threads</span><br /> "android.os.AsyncTask",<br /> "android.pim.ContactsAsyncHelper",<br /> "java.lang.ProcessManager"<br /> ));</p> <p>这几个Binders和Thread是不会被预加载的。</p> <p> 另外还有一些application需要装载,要求满足条件proc.fromZygote()且不是属于常驻内存的服务。SERVICES定义如下:</p> <p> <span style="color:#33cc00;"> /**<br /> * Long running services. These are restricted in their contribution to the <br /> * preloader because their launch time is less critical.<br /> */<br /> // TODO: Generate this automatically from package manager.</span><br /> private static final Set<String> SERVICES = new HashSet<String>(Arrays.asList(<br /> "system_server",<br /> "com.google.process.content",<br /> "android.process.media",<br /> "com.android.bluetooth",<br /> "com.android.calendar",<br /> "com.android.inputmethod.latin",<br /> "com.android.phone",<br /> "com.google.android.apps.maps.FriendService", // pre froyo<br /> "com.google.android.apps.maps:FriendService", // froyo<br /> "com.google.android.apps.maps.LocationFriendService",<br /> "com.google.android.deskclock",<br /> "com.google.process.gapps",<br /> "android.tts"<br /> ));</p> <p> preloaded-classes是在下载源码的时候生成,WritePreloadedClassFile类并没有被用到,但可以通过这个类了解Android系统对预加载类的默认要求,参考修改preloaded-classes文件,减少开机初始化时要预加载的类,提高开机速度。</p> <p>最后来通过startSystemServer()启动SystemServer进程。见如下代码:</p> <p><span style="color:#33cc00;"> /* Hardcoded command line to start the system server */</span><br /> String args[] = {<br /> "--setuid=1000",<br /> "--setgid=1000",<br /> "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003",<br /> "--capabilities=130104352,130104352",<br /> "--runtime-init",<br /> "--nice-name=system_server",<br /> "com.android.server.SystemServer",<br /> };<br /> ZygoteConnection.Arguments parsedArgs = null;<br /> <br /> int pid;<br /> <br /> try {<br /> parsedArgs = new ZygoteConnection.Arguments(args);<br /> <br /> <span style="color:#33cc00;"> /*<br /> * Enable debugging of the system process if *either* the command line flags<br /> * indicate it should be debuggable or the ro.debuggable system property<br /> * is set to "1"<br /> */</span><br /> int debugFlags = parsedArgs.debugFlags;<br /> if ("1".equals(SystemProperties.get("ro.debuggable")))<br /> debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;<br /> <br /> /* Request to fork the system server process */<br /> pid = Zygote.forkSystemServer(<br /> parsedArgs.uid, parsedArgs.gid,<br /> parsedArgs.gids, debugFlags, null,<br /> parsedArgs.permittedCapabilities,<br /> parsedArgs.effectiveCapabilities)</p> <p> Zygote包装了Linux的fork。forkSystemServer()调用forkAndSpecialize(),最终穿过虚拟机调用platform\dalvik\vm\native\dalvik_system_Zygote.c中 Dalvik_dalvik_system_Zygote_forkAndSpecialize()。由dalvik完成fork新的进程。</p> <p> main()最后会调用runSelectLoopMode(),进入while循环,由peers创建新的进程。</p> <p> </p> <p><strong>l SystemService进程</strong></p> <p> SystemService用于创建init.rc定义的服务之外的所有服务。在main()的最后有如下代码:</p> <p> // The system server has to run all of the time, so it needs to be<br /> // as efficient as possible with its memory usage.<br /> VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);<br /> <br /> System.loadLibrary("android_servers");<br /> init1(args);</p> <p>Init1()是在native空间实现的,用于启动native空间的服务,其实现在com_android_server_SystemServer.cpp中的android_server_SystemServer_init1():</p> <p>static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)<br /> {<br /> system_init();<br /> }</p> <p> 而system_init()服务初始化创建native层的各个服务:</p> <p><span style="color:#33cc00;"> // Start the sensor service</span><br /> SensorService::instantiate();<br /> <span style="color:#33cc00;"><br /> // On the simulator, audioflinger et al don't get started the<br /> // same way as on the device, and we need to start them here</span><br /> if (!proc->supportsProcesses()) {<br /> <span style="color:#33cc00;"><br /> // Start the AudioFlinger</span><br /> AudioFlinger::instantiate();<br /> <span style="color:#33cc00;"><br /> // Start the media playback service</span><br /> MediaPlayerService::instantiate();<br /> <br /> <span style="color:#33cc00;"> // Start the camera service</span><br /> CameraService::instantiate();<br /> <br /> <span style="color:#33cc00;"> // Start the audio policy service</span><br /> AudioPolicyService::instantiate();<br /> }</p> <p> 最后通过如下代码:</p> <p> LOGI("System server: starting Android services.\n");<br /> runtime->callStatic("com/android/server/SystemServer", "init2");</p> <p>回到SystemServer.java,调用init2():</p> <p> public static final void init2() {<br /> Slog.i(TAG, "Entered the Android system server!");<br /> Thread thr = new ServerThread();<br /> thr.setName("android.server.ServerThread");<br /> thr.start();<br /> }</p> <p> Init2启动一个线程,专门用来启动java空间的所有服务。如下代码所示启动部分服务:</p> <p> Slog.i(TAG, "Content Manager");<br /> ContentService.main(context,<br /> factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);<br /> <br /> Slog.i(TAG, "System Content Providers");<br /> ActivityManagerService.installSystemProviders();<br /> <br /> Slog.i(TAG, "Battery Service");<br /> battery = new BatteryService(context);<br /> ServiceManager.addService("battery", battery);<br /> <br /> Slog.i(TAG, "Lights Service");<br /> lights = new LightsService(context);<br /> <br /> Slog.i(TAG, "Vibrator Service");<br /> ServiceManager.addService("vibrator", new VibratorService(context));<br /> <br /> // only initialize the power service after we have started the<br /> // lights service, content providers and the battery service.<br /> power.init(context, lights, ActivityManagerService.getDefault(), battery);<br /> <br /> Slog.i(TAG, "Alarm Manager");<br /> AlarmManagerService alarm = new AlarmManagerService(context);<br /> ServiceManager.addService(Context.ALARM_SERVICE, alarm);</p> <p>并且把这些服务添加到ServiceManager中,以便管理和进程间通讯。</p> <p>在该线程后半部分,ActivityManagerService会等待AppWidget、WallPaper、IMM等systemReady后调用自身的systemReady()。</p> <p> ((ActivityManagerService)ServiceManager.getService("activity"))<br /> .setWindowManager(wm);<br /> <br /> <span style="color:#33cc00;"> // Skip Bluetooth if we have an emulator kernel<br /> // TODO: Use a more reliable check to see if this product should<br /> // support Bluetooth - see bug 988521</span><br /> if (SystemProperties.get("ro.kernel.qemu").equals("1")) {<br /> Slog.i(TAG, "Registering null Bluetooth Service (emulator)");<br /> ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);<br /> } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {<br /> Slog.i(TAG, "Registering null Bluetooth Service (factory test)");<br /> ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);<br /> } else {<br /> Slog.i(TAG, "Bluetooth Service");<br /> bluetooth = new BluetoothService(context);<br /> ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);<br /> bluetooth.initAfterRegistration();<br /> bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);<br /> ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,<br /> bluetoothA2dp);<br /> <br /> int bluetoothOn = Settings.Secure.getInt(mContentResolver,<br /> Settings.Secure.BLUETOOTH_ON, 0);<br /> if (bluetoothOn > 0) {<br /> bluetooth.enable();<br /> }<br /> }</p> <p> 而在ActivityManagerService的systemReady()最后会执行如下代码:</p> <p> mMainStack.resumeTopActivityLocked(null);</p> <p> 由于Activity管理栈为空,因此启动Launcher。</p> <p> <span style="color:#33cc00;"> // Find the first activity that is not finishing.</span><br /> ActivityRecord next = topRunningActivityLocked(null);<br /> <span style="color:#33cc00;"><br /> // Remember how we'll process this pause/resume situation, and ensure<br /> // that the state is reset however we wind up proceeding.</span><br /> final boolean userLeaving = mUserLeaving;<br /> mUserLeaving = false;<br /> <br /> if (next == null) {<br /> <span style="color:#33cc00;"> // There are no more activities! Let's just start up the<br /> // Launcher...</span><br /> if (mMainStack) {<br /> return mService.startHomeActivityLocked();<br /> }<br /> }</p> <p> 在startHomeActivityLocked()中创建一个带Category为CATEGORY_HOME的Intent,由此去启动相应Activity,即Launcher。</p> <p> Intent intent = new Intent(<br /> mTopAction,<br /> mTopData != null ? Uri.parse(mTopData) : null);<br /> intent.setComponent(mTopComponent);<br /> if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {<br /> intent.addCategory(Intent.CATEGORY_HOME);<br /> }</p> <p> 这样,Android系统便启动起来进入到待机界面。</p>