Android開機啓動流程初探 .

第一步:啓動linux
1.Bootloader
2.Kernel
第二步android系統啓動:入口爲init.rc(system\core\rootdir)
1./system/bin/service manager: Binder 守護進程;
2.Runtime;
3.Zygote :app-process/app-main;
4.Start VM;
5.Start server
6.Start android service:Register to service Manager
7.Start Launcher


第三步:應用程序啓動:運行package Manager
1.Init進程
       Android系統在啓動時首先會啓動Linux系統,引導加載Linux Kernel並啓動init進程。Init進程是一個由內核啓動的用戶級進程,是Android系統的第一個進程。該進程的相關代碼在platform\system\core\init\init.c。在main函數中,有如下代碼:


[cpp] view plaincopy
open_devnull_stdio();  
log_init();  
INFO("reading config file\n");  
init_parse_config_file("/init.rc");  
  
/* pull the kernel commandline and ramdisk properties file in */  
import_kernel_cmdline(0);  
get_hardware_name(hardware, &revision);  
snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);  
init_parse_config_file(tmp);  
       這裏會加載解析init.rc和init.hardware.rc兩個初始化腳本。*.rc文件定義了在init進程中需要啓動哪些進程服務和執行哪些動作。其詳細說明參見platform\system\core\init\reademe.txt。init.rc見如下定義:


[cpp] view plaincopy
service servicemanager /system/bin/servicemanager  
    user system  
    critical  
    onrestart restart zygote  
    onrestart restart media  
  
service vold /system/bin/vold  
    socket vold stream 0660 root mount  
    ioprio be 2  
  
service netd /system/bin/netd  
    socket netd stream 0660 root system  
    socket dnsproxyd stream 0660 root inet  
  
service debuggerd /system/bin/debuggerd  
  
service ril-daemon /system/bin/rild  
    socket rild stream 660 root radio  
    socket rild-debug stream 660 radio system  
    user root  
    group radio cache inet misc audio sdcard_rw  
  
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server  
    socket zygote stream 666  
    onrestart write /sys/android_power/request_state wake  
    onrestart write /sys/power/state on  
    onrestart restart media  
    onrestart restart netd  
  
service drm /system/bin/drmserver  
    user drm  
    group system root inet  
    具體解析過程見platform\system\core\init\Init_parser.c。解析所得服務添加到service_list中,動作添加到action_list中。
    接下來在main函數中執行動作和啓動進程服務:


[cpp] view plaincopy
execute_one_command();  
restart_processes();  
      通常init過程需要創建一些系統文件夾並啓動USB守護進程、Android Debug Bridge守護進程、Debug守護進程、ServiceManager進程、Zygote進程等。


2. ServiceManager進程
     ServiceManager進程是所有服務的管理器。由init.rc對ServiceManager的描述service servicemanager/system/bin/servicemanager可知servicemanager進程從platform\frameworks\base\cmd\servicemanager\Service_manager.cpp啓動。在main函數中有如下代碼:


[cpp] view plaincopy
int main(int argc, char **argv)  
{  
    struct binder_state *bs;  
    void *svcmgr = BINDER_SERVICE_MANAGER;  
  
    bs = binder_open(128*1024);  
  
    if (binder_become_context_manager(bs)) {  
        LOGE("cannot become context manager (%s)\n", strerror(errno));  
        return -1;  
    }  
  
    svcmgr_handle = svcmgr;  
    binder_loop(bs, svcmgr_handler);  
    return 0;  
}  
       首先調用binder_open()打開Binder設備(/dev/binder),調用binder_become_context_manager()把當前進程設置爲ServiceManager。ServiceManager本身就是一個服務。
[cpp] view plaincopy
int binder_become_context_manager(struct binder_state *bs)  
{  
    return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0);  
}  


     最後binder_loop()進入循環狀態,並設置svcmgr_handler回調函數等待添加、查詢、獲取服務等請求。


3. Zygote進程
      Zygote進程用於產生其他進程。由init.rc對zygote的描述service zygot /system/bin/app_process可知zygote進程從platfrom\frameworks\base\cmds\app_process\App_main.cpp啓動。在main函數中有如下代碼: 


[cpp] view plaincopy
if (0 == strcmp("--zygote", arg)) {  
     bool startSystemServer = (i < argc) ?  
            strcmp(argv[i], "--start-system-server") == 0 : false;  
     setArgv0(argv0, "zygote");  
     set_process_name("zygote");  
     runtime.start("com.android.internal.os.ZygoteInit",  
         startSystemServer);  
 } else {  
     set_process_name(argv0);  
     runtime.mClassName = arg;  
  
     // Remainder of args get passed to startup class main()  
     runtime.mArgC = argc-i;  
     runtime.mArgV = argv+i;  
  
     LOGV("App process is starting with pid=%d, class=%s.\n",  
          getpid(), runtime.getClassName());  
     runtime.start();  
 }  
      首先創建AppRuntime,即AndroidRuntime,建立了一個Dalvik虛擬機。通過這個runtime傳遞com.android.internal.os.ZygoteInit參數,從而由Dalvik虛擬機運行ZygoteInit.java的main(),開始創建Zygote進程。在其main()中,如下所示:
[cpp] view plaincopy
registerZygoteSocket();  
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,  
SystemClock.uptimeMillis());  
preloadClasses();  
//cacheRegisterMaps();  
preloadResources();  
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,  
         SystemClock.uptimeMillis());  
  
// Finish profiling the zygote initialization.  
SamplingProfilerIntegration.writeZygoteSnapshot();  
  
// Do an initial gc to clean up after startup  
gc();  
  
// If requested, start system server directly from Zygote  
if (argv.length != 2) {  
   throw new RuntimeException(argv[0] + USAGE_STRING);  
}  
  
if (argv[1].equals("true")) {  
     startSystemServer();  
} else if (!argv[1].equals("false")) {  
    throw new RuntimeException(argv[0] + USAGE_STRING);  
}  


      首先通過registerZygoteSocket()登記端口,接着preloadClasses()裝載相關類。這裏大概要裝載1000多個類,具體裝載類見platform\frameworks\base\preloaded-classes。這個文件有WritePreloadedClassFile類自動生成。分析該類的main函數,有如下一段篩選類的代碼:


[cpp] view plaincopy
// Preload classes that were loaded by at least 2 processes. Hopefully,  
// the memory associated with these classes will be shared.  
 for (LoadedClass loadedClass : root.loadedClasses.values()) {  
     Set<String> names = loadedClass.processNames();  
     if (!Policy.isPreloadable(loadedClass)) {  
         continue;  
     }  
  
     if (names.size() >= MIN_PROCESSES ||  
             (loadedClass.medianTimeMicros() > MIN_LOAD_TIME_MICROS && names.size() > 1)) {  
         toPreload.add(loadedClass);  
     }  
 }  
 int initialSize = toPreload.size();  
 System.out.println(initialSize  
         + " classses were loaded by more than one app.");  
 // Preload eligable classes from applications (not long-running  
 // services).  
 for (Proc proc : root.processes.values()) {  
     if (proc.fromZygote() && !Policy.isService(proc.name)) {  
         for (Operation operation : proc.operations) {  
             LoadedClass loadedClass = operation.loadedClass;  
             if (shouldPreload(loadedClass)) {  
                 toPreload.add(loadedClass);  
             }  
         }  
     }  
 }  


      其中MIN_LOAD_TIME_MICROS等於1250,當類的裝載時間大於1.25ms,則需要預裝載。


      Policy.isPreloadable()定於如下:


[cpp] view plaincopy
/**Reports if the given class should be preloaded. */  
 public static boolean isPreloadable(LoadedClass clazz) {  
     return clazz.systemClass && !EXCLUDED_CLASSES.contains(clazz.name);  
 }  


      其中EXCLUDED_CLASSES如下定義:


[cpp] view plaincopy
/** 
  * Classes which we shouldn't load from the Zygote. 
  */  
 private static final Set<String> EXCLUDED_CLASSES  
         = new HashSet<String>(Arrays.asList(  
     // Binders  
     "android.app.AlarmManager",  
     "android.app.SearchManager",  
     "android.os.FileObserver",  
     "com.android.server.PackageManagerService$AppDirObserver",  
     // Threads  
     "android.os.AsyncTask",  
     "android.pim.ContactsAsyncHelper",  
     "java.lang.ProcessManager"  
 ));  


      這幾個Binders和Thread是不會被預加載的。
      另外還有一些application需要裝載,要求滿足條件proc.fromZygote()且不是屬於常駐內存的服務。SERVICES定義如下:
 


[cpp] view plaincopy
/** 
  * Long running services. These are restricted in their contribution to the 
  * preloader because their launch time is less critical. 
  */  
 // TODO: Generate this automatically from package manager.  
 private static final Set<String> SERVICES = new HashSet<String>(Arrays.asList(  
     "system_server",  
     "com.google.process.content",  
     "android.process.media",  
     "com.android.bluetooth",  
     "com.android.calendar",  
     "com.android.inputmethod.latin",  
     "com.android.phone",  
     "com.google.android.apps.maps.FriendService", // pre froyo  
     "com.google.android.apps.maps:FriendService", // froyo  
     "com.google.android.apps.maps.LocationFriendService",  
     "com.google.android.deskclock",  
     "com.google.process.gapps",  
     "android.tts"  
 ));  


        preloaded-classes是在下載源碼的時候生成,WritePreloadedClassFile類並沒有被用到,但可以通過這個類瞭解Android系統對預加載類的默認要求,參考修改preloaded-classes文件,減少開機初始化時要預加載的類,提高開機速度。 


       最後來通過startSystemServer()啓動SystemServer進程。見如下代碼:


 


[cpp] view plaincopy
/* Hardcoded command line to start the system server */  
 String args[] = {  
     "--setuid=1000",  
     "--setgid=1000",  
     "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003",  
     "--capabilities=130104352,130104352",  
     "--runtime-init",  
     "--nice-name=system_server",  
     "com.android.server.SystemServer",  
 };  
  
 ZygoteConnection.Arguments parsedArgs = null;  
 int pid;  
 try {  
     parsedArgs = new ZygoteConnection.Arguments(args);  
     /* 
      * Enable debugging of the system process if *either* the command line flags 
      * indicate it should be debuggable or the ro.debuggable system property 
      * is set to "1" 
      */  
     int debugFlags = parsedArgs.debugFlags;  
     if ("1".equals(SystemProperties.get("ro.debuggable")))  
         debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;  
  
     /* Request to fork the system server process */  
     pid = Zygote.forkSystemServer(  
             parsedArgs.uid, parsedArgs.gid,  
             parsedArgs.gids, debugFlags, null,  
             parsedArgs.permittedCapabilities,  
             parsedArgs.effectiveCapabilities)  


      Zygote包裝了Linux的fork。forkSystemServer()調用forkAndSpecialize(),最終穿過虛擬機調用platform\dalvik\vm\native\dalvik_system_Zygote.c中Dalvik_dalvik_system_Zygote_forkAndSpecialize()。由dalvik完成fork新的進程。
  main()最後會調用runSelectLoopMode(),進入while循環,由peers創建新的進程。


4. SystemService進程
     SystemService用於創建init.rc定義的服務之外的所有服務。在main()的最後有如下代碼:


[cpp] view plaincopy
// The system server has to run all of the time, so it needs to be  
// as efficient as possible with its memory usage.  
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);  
  
System.loadLibrary("android_servers");  
init1(args);  
       Init1()是在native空間實現的,用於啓動native空間的服務,其實現在com_android_server_SystemServer.cpp中的android_server_SystemServer_init1():
[cpp] view plaincopy
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)  
{  
    system_init();  
}  
       而system_init()服務初始化創建native層的各個服務:


[cpp] view plaincopy
// Start the sensor service  
SensorService::instantiate();  
  
// On the simulator, audioflinger et al don't get started the  
// same way as on the device, and we need to start them here  
if (!proc->supportsProcesses()) {  
  // Start the AudioFlinger  
  AudioFlinger::instantiate();  
  
  // Start the media playback service  
  MediaPlayerService::instantiate();  
  
  // Start the camera service  
  CameraService::instantiate();  
  
  // Start the audio policy service  
  AudioPolicyService::instantiate();  
}  
      最後通過如下代碼:


[cpp] view plaincopy
LOGI("System server: starting Android services.\n");  
runtime->callStatic("com/android/server/SystemServer", "init2");  
      回到SystemServer.java,調用init2():


[cpp] view plaincopy
public static final void init2() {  
     Slog.i(TAG, "Entered the Android system server!");  
     Thread thr = new ServerThread();  
     thr.setName("android.server.ServerThread");  
     thr.start();  
 }  
      Init2啓動一個線程,專門用來啓動java空間的所有服務。如下代碼所示啓動部分服務:


[cpp] view plaincopy
// Critical services...  
try {  
    Slog.i(TAG, "Entropy Service");  
    ServiceManager.addService("entropy", new EntropyService());  
  
    Slog.i(TAG, "Power Manager");  
    power = new PowerManagerService();  
    ServiceManager.addService(Context.POWER_SERVICE, power);  
  
    Slog.i(TAG, "Activity Manager");  
    context = ActivityManagerService.main(factoryTest);  
  
    Slog.i(TAG, "Telephony Registry");  
    ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));  
  
    AttributeCache.init(context);  
  
    Slog.i(TAG, "Package Manager");  
    // Only run "core" apps if we're encrypting the device.  
    String cryptState = SystemProperties.get("vold.decrypt");  
    boolean onlyCore = false;  
    if (ENCRYPTING_STATE.equals(cryptState)) {  
        Slog.w(TAG, "Detected encryption in progress - only parsing core apps");  
        onlyCore = true;  
    } else if (ENCRYPTED_STATE.equals(cryptState)) {  
        Slog.w(TAG, "Device encrypted - only parsing core apps");  
        onlyCore = true;  
    }  
  
    pm = PackageManagerService.main(context,  
            factoryTest != SystemServer.FACTORY_TEST_OFF,  
            onlyCore);  
    boolean firstBoot = false;  
    try {  
        firstBoot = pm.isFirstBoot();  
    } catch (RemoteException e) {  
    }  
  
    ActivityManagerService.setSystemProcess();  
  
    mContentResolver = context.getContentResolver();  
  
    // The AccountManager must come before the ContentService  
    try {  
        Slog.i(TAG, "Account Manager");  
        ServiceManager.addService(Context.ACCOUNT_SERVICE,  
                new AccountManagerService(context));  
    } catch (Throwable e) {  
        Slog.e(TAG, "Failure starting Account Manager", e);  
    }  
  
    Slog.i(TAG, "Content Manager");  
    ContentService.main(context,  
            factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);  
  
    Slog.i(TAG, "System Content Providers");  
    ActivityManagerService.installSystemProviders();  
  
    Slog.i(TAG, "Lights Service");  
    lights = new LightsService(context);  
  
    Slog.i(TAG, "Battery Service");  
    battery = new BatteryService(context, lights);  
    ServiceManager.addService("battery", battery);  
  
    Slog.i(TAG, "Vibrator Service");  
    ServiceManager.addService("vibrator", new VibratorService(context));  
  
    // only initialize the power service after we have started the  
    // lights service, content providers and the battery service.  
    power.init(context, lights, ActivityManagerService.self(), battery);  
  
    Slog.i(TAG, "Alarm Manager");  
    alarm = new AlarmManagerService(context);  
    ServiceManager.addService(Context.ALARM_SERVICE, alarm);  
  
    Slog.i(TAG, "Init Watchdog");  
    Watchdog.getInstance().init(context, battery, power, alarm,  
            ActivityManagerService.self());  
  
    Slog.i(TAG, "Window Manager");  
    wm = WindowManagerService.main(context, power,  
            factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,  
            !firstBoot);  
    ServiceManager.addService(Context.WINDOW_SERVICE, wm);  
  
    ActivityManagerService.self().setWindowManager(wm);  
  
    // Skip Bluetooth if we have an emulator kernel  
    // TODO: Use a more reliable check to see if this product should  
    // support Bluetooth - see bug 988521  
    if (SystemProperties.get("ro.kernel.qemu").equals("1")) {  
        Slog.i(TAG, "No Bluetooh Service (emulator)");  
    } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {  
        Slog.i(TAG, "No Bluetooth Service (factory test)");  
    } else {  
        Slog.i(TAG, "Bluetooth Service");  
        bluetooth = new BluetoothService(context);  
        ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);  
        bluetooth.initAfterRegistration();  
        bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);  
        ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,  
                                  bluetoothA2dp);  
        bluetooth.initAfterA2dpRegistration();  
  
        int airplaneModeOn = Settings.System.getInt(mContentResolver,  
                Settings.System.AIRPLANE_MODE_ON, 0);  
        int bluetoothOn = Settings.Secure.getInt(mContentResolver,  
            Settings.Secure.BLUETOOTH_ON, 0);  
        if (airplaneModeOn == 0 && bluetoothOn != 0) {  
            bluetooth.enable();  
        }  
    }  
  
} catch (RuntimeException e) {  
    Slog.e("System", "******************************************");  
    Slog.e("System", "************ Failure starting core service", e);  
}  


       並且把這些服務添加到ServiceManager中,以便管理和進程間通訊。
       在該線程後半部分,ActivityManagerService會等待AppWidget、WallPaper、IMM等systemReady後調用自身的systemReady()。   


 


[cpp] view plaincopy
Slog.i(TAG, "Content Manager");  
ContentService.main(context,  
         factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);  
  
((ActivityManagerService)ServiceManager.getService("activity"))  
         .setWindowManager(wm);  
  
  
 // Skip Bluetooth if we have an emulator kernel  
 // TODO: Use a more reliable check to see if this product should  
 // support Bluetooth - see bug 988521  
 if (SystemProperties.get("ro.kernel.qemu").equals("1")) {  
     Slog.i(TAG, "Registering null Bluetooth Service (emulator)");  
     ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);  
 } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {  
     Slog.i(TAG, "Registering null Bluetooth Service (factory test)");  
     ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);  
 } else {  
     Slog.i(TAG, "Bluetooth Service");  
     bluetooth = new BluetoothService(context);  
     ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);  
     bluetooth.initAfterRegistration();  
     bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);  
     ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,  
                               bluetoothA2dp);  
  
     int bluetoothOn = Settings.Secure.getInt(mContentResolver,  
         Settings.Secure.BLUETOOTH_ON, 0);  
  
     if (bluetoothOn > 0) {  
         bluetooth.enable();  
     }  
 }  
       而在ActivityManagerService的systemReady()最後會執行如下代碼:


[cpp] view plaincopy
mMainStack.resumeTopActivityLocked(null);  
       由於Activity管理棧爲空,因此啓動Launcher。


[cpp] view plaincopy
// Find the first activity that is not finishing.  
ActivityRecord next = topRunningActivityLocked(null);  
  
// Remember how we'll process this pause/resume situation, and ensure  
// that the state is reset however we wind up proceeding.  
final boolean userLeaving = mUserLeaving;  
mUserLeaving = false;  
  
if (next == null) {  
    // There are no more activities!  Let's just start up the  
    // Launcher...  
    if (mMainStack) {  
        return mService.startHomeActivityLocked();  
    }  
}  


        在startHomeActivityLocked()中創建一個帶Category爲CATEGORY_HOME的Intent,由此去啓動相應Activity,即Launcher。


[cpp] view plaincopy
Intent intent = new Intent(  
    mTopAction,  
    mTopData != null ? Uri.parse(mTopData) : null);  
intent.setComponent(mTopComponent);  
  
if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {  
    intent.addCategory(Intent.CATEGORY_HOME);  
}  
       這樣,Android系統便啓動起來進入到待機界面。


摘自 亨利摩根的專欄
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章