Android启动流程

转:http://blog.csdn.net/qianjin0703/article/details/8468312

1. init进程

2. zygote进程

2.1 AndroidRuntime

2.2 ZygoteInit

3. system_server进程

3.1 init1阶段

3.2 init2阶段


接着Linux启动部分 http://blog.csdn.net/qianjin0703/article/details/6881107

1. init进程


系统在内核空间初始化进程,内存,文件系统,驱动模块之后,调用init_post()函数,开启第一个用户进程init,进入用户空间。

/kernel/init/main.c (仅截取部分重要代码)

  1. static noinline int init_post(void)
  2. {
  3. run_init_process("/sbin/init");
  4. run_init_process("/etc/init");
  5. run_init_process("/bin/init");
  6. run_init_process("/bin/sh");
  7. }
static noinline int init_post(void)
{

	run_init_process("/sbin/init");
	run_init_process("/etc/init");
	run_init_process("/bin/init");
	run_init_process("/bin/sh");
}

终端下查看1号进程,


可见,init是系统守护进程和zygote的父进程。

/system/core/init/init.c

  1. int main(int argc, char **argv)
  2. {
  3. mkdir("/dev", 0755);
  4. mkdir("/proc", 0755);
  5. mkdir("/sys", 0755);
  6. mount("devpts", "/dev/pts", "devpts", 0, NULL);
  7. mount("proc", "/proc", "proc", 0, NULL);
  8. mount("sysfs", "/sys", "sysfs", 0, NULL);
  9. open_devnull_stdio();
  10. klog_init();
  11. property_init();
  12. get_hardware_name(hardware, &revision);
  13. process_kernel_cmdline();
  14. init_parse_config_file("/init.rc");
  15. action_for_each_trigger("early-init", action_add_queue_tail);
  16. queue_builtin_action(wait_for_coldboot_done_action, "wait_for_coldboot_done");
  17. queue_builtin_action(keychord_init_action, "keychord_init");
  18. queue_builtin_action(console_init_action, "console_init");
  19. action_for_each_trigger("init", action_add_queue_tail);
  20. for(;;) {
  21. execute_one_command();
  22. restart_processes();
  23. nr = poll(ufds, fd_count, timeout);
  24. for (i = 0; i < fd_count; i++) {
  25. if (ufds[i].revents == POLLIN) {
  26. if (ufds[i].fd == get_property_set_fd())
  27. handle_property_set_fd();
  28. else if (ufds[i].fd == get_keychord_fd())
  29. handle_keychord();
  30. else if (ufds[i].fd == get_signal_fd())
  31. handle_signal();
  32. }
  33. }
  34. }
  35. return 0;
  36. }
int main(int argc, char **argv)
{

    mkdir("/dev", 0755);
    mkdir("/proc", 0755);
    mkdir("/sys", 0755);

    mount("devpts", "/dev/pts", "devpts", 0, NULL);
    mount("proc", "/proc", "proc", 0, NULL);
    mount("sysfs", "/sys", "sysfs", 0, NULL);

    open_devnull_stdio();
    klog_init();
    property_init();

    get_hardware_name(hardware, &revision);
    process_kernel_cmdline();

    init_parse_config_file("/init.rc");
    action_for_each_trigger("early-init", action_add_queue_tail);

    queue_builtin_action(wait_for_coldboot_done_action, "wait_for_coldboot_done");
    queue_builtin_action(keychord_init_action, "keychord_init");
    queue_builtin_action(console_init_action, "console_init");
    action_for_each_trigger("init", action_add_queue_tail);

    for(;;) {

        execute_one_command();
        restart_processes();

        nr = poll(ufds, fd_count, timeout);

        for (i = 0; i < fd_count; i++) {
            if (ufds[i].revents == POLLIN) {
                if (ufds[i].fd == get_property_set_fd())
                    handle_property_set_fd();
                else if (ufds[i].fd == get_keychord_fd())
                    handle_keychord();
                else if (ufds[i].fd == get_signal_fd())
                    handle_signal();
            }
        }
    }

    return 0;
}
init进程归纳如下
  • 解析init.rc和init.*.rc
  • 挂载文件系统,建立文件夹和文件,设置权限,为一些文件写入初值
  • 初始化property属性
  • 启动系统守护进程如adbd, vold, rild等
  • 启动zygote进程



2. zygote进程

zygote既是Android系统创建java世界的盘古,又是繁殖system_server和所有应用程序的女娲。

终端下查看zygote进程,


2.1 AndroidRuntime

/frameworks/base/cmds/app_process/app_main.cpp

  1. int main(int argc, const char* const argv[])
  2. {
  3. AppRuntime runtime;
  4. if (zygote) {
  5. runtime.start("com.android.internal.os.ZygoteInit",
  6. startSystemServer ? "start-system-server" : "");
  7. }
int main(int argc, const char* const argv[])
{

    AppRuntime runtime;

    if (zygote) {
        runtime.start("com.android.internal.os.ZygoteInit",
                startSystemServer ? "start-system-server" : "");
}
AppRuntime是从AndroidRuntime类派生的,最后由runtime.start()进入Java世界。

/frameworks/base/core/jni/AndroidRuntime.cpp

  1. void AndroidRuntime::start(const char* className, const char* options)
  2. {
  3. /* start the virtual machine */
  4. JNIEnv* env;
  5. if (startVm(&mJavaVM, &env) != 0) {
  6. return;
  7. }
  8. onVmCreated(env);
  9. /*
  10. * Register android functions.
  11. */
  12. if (startReg(env) < 0) {
  13. ALOGE("Unable to register all android natives\n");
  14. return;
  15. }
  16. /*
  17. * Start VM. This thread becomes the main thread of the VM, and will
  18. * not return until the VM exits.
  19. */
  20. char* slashClassName = toSlashClassName(className);
  21. jclass startClass = env->FindClass(slashClassName);
  22. jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
  23. "([Ljava/lang/String;)V");
  24. env->CallStaticVoidMethod(startClass, startMeth, strArray);
  25. }
void AndroidRuntime::start(const char* className, const char* options)
{

    /* start the virtual machine */
    JNIEnv* env;
    if (startVm(&mJavaVM, &env) != 0) {
        return;
    }
    onVmCreated(env);

    /*
     * Register android functions.
     */
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }

    /*
     * 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);

    jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
            "([Ljava/lang/String;)V");

    env->CallStaticVoidMethod(startClass, startMeth, strArray);

}

-> 创建虚拟机

注意这里会设置虚拟机的heapsize,默认16M,一般32M,不能太小,否则在操作大尺寸图片时无法分配所需内存。

-> 注册jni函数

这里注册了本地方法,这些方法最终被编译进动态链接库libandroid_runtime.so,供上层Java调用。

  1. static const RegJNIRec gRegJNI[] = {
  2. REG_JNI(register_android_debug_JNITest),
  3. REG_JNI(register_com_android_internal_os_RuntimeInit),
  4. REG_JNI(register_android_os_SystemClock),
  5. REG_JNI(register_android_util_Log),
  6. REG_JNI(register_android_os_Process),
  7. REG_JNI(register_android_os_SystemProperties),
  8. REG_JNI(register_android_os_Binder),
  9. REG_JNI(register_android_view_Display),
  10. REG_JNI(register_android_graphics_Bitmap),
  11. REG_JNI(register_android_graphics_Camera),
  12. REG_JNI(register_android_database_SQLiteDatabase),
  13. REG_JNI(register_android_os_Power),
  14. REG_JNI(register_android_os_StatFs),
  15. REG_JNI(register_android_net_NetworkUtils),
  16. REG_JNI(register_android_nfc_NdefMessage),
  17. REG_JNI(register_com_android_internal_os_ZygoteInit),
  18. REG_JNI(register_android_hardware_Camera),
  19. REG_JNI(register_android_hardware_SensorManager),
  20. REG_JNI(register_android_hardware_UsbDevice),
  21. REG_JNI(register_android_media_AudioRecord),
  22. REG_JNI(register_android_media_AudioSystem),
  23. REG_JNI(register_android_media_AudioTrack),
  24. REG_JNI(register_android_opengl_classes),
  25. REG_JNI(register_android_bluetooth_BluetoothSocket),
  26. REG_JNI(register_android_server_BluetoothService),
  27. REG_JNI(register_android_app_ActivityThread),
  28. REG_JNI(register_android_app_NativeActivity),
  29. REG_JNI(register_android_view_InputChannel),
  30. REG_JNI(register_android_view_InputQueue),
  31. REG_JNI(register_android_view_KeyEvent),
  32. REG_JNI(register_android_view_MotionEvent),
  33. REG_JNI(register_android_view_PointerIcon),
  34. };
static const RegJNIRec gRegJNI[] = {
    REG_JNI(register_android_debug_JNITest),
    REG_JNI(register_com_android_internal_os_RuntimeInit),
    REG_JNI(register_android_os_SystemClock),
    REG_JNI(register_android_util_Log),
    REG_JNI(register_android_os_Process),
    REG_JNI(register_android_os_SystemProperties),
    REG_JNI(register_android_os_Binder),
    REG_JNI(register_android_view_Display),
    REG_JNI(register_android_graphics_Bitmap),
    REG_JNI(register_android_graphics_Camera),
    REG_JNI(register_android_database_SQLiteDatabase),
    REG_JNI(register_android_os_Power),
    REG_JNI(register_android_os_StatFs),
    REG_JNI(register_android_net_NetworkUtils),
    REG_JNI(register_android_nfc_NdefMessage),
    REG_JNI(register_com_android_internal_os_ZygoteInit),
    REG_JNI(register_android_hardware_Camera),
    REG_JNI(register_android_hardware_SensorManager),
    REG_JNI(register_android_hardware_UsbDevice),
    REG_JNI(register_android_media_AudioRecord),
    REG_JNI(register_android_media_AudioSystem),
    REG_JNI(register_android_media_AudioTrack),
    REG_JNI(register_android_opengl_classes),
    REG_JNI(register_android_bluetooth_BluetoothSocket),
    REG_JNI(register_android_server_BluetoothService),

    REG_JNI(register_android_app_ActivityThread),
    REG_JNI(register_android_app_NativeActivity),
    REG_JNI(register_android_view_InputChannel),
    REG_JNI(register_android_view_InputQueue),
    REG_JNI(register_android_view_KeyEvent),
    REG_JNI(register_android_view_MotionEvent),
    REG_JNI(register_android_view_PointerIcon),

};


2.2 ZygoteInit

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

  1. public static void main(String argv[]) {
  2. try {
  3. SamplingProfilerIntegration.start();
  4. registerZygoteSocket();
  5. preload();
  6. SamplingProfilerIntegration.writeZygoteSnapshot();
  7. if (argv[1].equals("start-system-server")) {
  8. startSystemServer();
  9. }
  10. runSelectLoopMode();
  11. closeServerSocket();
  12. }
  13. }
    public static void main(String argv[]) {
        try {
            SamplingProfilerIntegration.start();

            registerZygoteSocket();

            preload();

            SamplingProfilerIntegration.writeZygoteSnapshot();

            if (argv[1].equals("start-system-server")) {
                startSystemServer();
            } 

                runSelectLoopMode();

            closeServerSocket();
        } 
    }

-> 建立服务端Socket

zygote及系统中其他程序的通信没有使用Binder,而是采用了基于AF_UNIX类型的Socket.

-> 预加载类和资源

预加载的类可以在 /frameworks/base/preloaded-classes 查看。预加载的资源生成framewrok-res.apk,主要是一些图标,刷机达人经常修改它。

-> 启动system_server进程

zygote进程fork出system_server子进程,把任务繁重的系统服务全部托管出去,自己负责循环监听所有应用程序的请求。

-> 等待应用程序的请求

zygote通过runSelectLoopMode()处理应用程序客户端的请求,由ZygoteConnection的runOnce()孵化出新的应用程序。


综上所述,zygote进程归纳如下

  • 创建虚拟机
  • 注册jni函数
  • 预加载类和资源
  • 启动system_server进程
  • 监听应用程序请求


3. system_server进程

/frameworks/base/services/java/com/android/SystemServer.java

  1. public static void main(String[] args) {
  2. System.loadLibrary("android_servers");
  3. init1(args);
  4. }
    public static void main(String[] args) {

        System.loadLibrary("android_servers");
        init1(args);
    }
3.1 init1阶段
加载libandriod_server.so库,实现init1

/frameworks/base/cmds/system_server/library/system_init.cpp

  1. extern "C" status_t system_init()
  2. {
  3. sp<GrimReaper> grim = new GrimReaper();
  4. sm->asBinder()->linkToDeath(grim, grim.get(), 0);
  5. char propBuf[PROPERTY_VALUE_MAX];
  6. property_get("system_init.startsurfaceflinger", propBuf, "1");
  7. if (strcmp(propBuf, "1") == 0) {
  8. // Start the SurfaceFlinger
  9. SurfaceFlinger::instantiate();
  10. }
  11. property_get("system_init.startsensorservice", propBuf, "1");
  12. if (strcmp(propBuf, "1") == 0) {
  13. // Start the sensor service
  14. SensorService::instantiate();
  15. }
  16. AndroidRuntime* runtime = AndroidRuntime::getRuntime();
  17. jclass clazz = env->FindClass("com/android/server/SystemServer");
  18. jmethodID methodId = env->GetStaticMethodID(clazz, "init2", "()V");
  19. env->CallStaticVoidMethod(clazz, methodId);
  20. return NO_ERROR;
  21. }
extern "C" status_t system_init()
{

    sp<GrimReaper> grim = new GrimReaper();
    sm->asBinder()->linkToDeath(grim, grim.get(), 0);

    char propBuf[PROPERTY_VALUE_MAX];
    property_get("system_init.startsurfaceflinger", propBuf, "1");
    if (strcmp(propBuf, "1") == 0) {
        // Start the SurfaceFlinger
        SurfaceFlinger::instantiate();
    }

    property_get("system_init.startsensorservice", propBuf, "1");
    if (strcmp(propBuf, "1") == 0) {
        // Start the sensor service
        SensorService::instantiate();
    }

    AndroidRuntime* runtime = AndroidRuntime::getRuntime();

    jclass clazz = env->FindClass("com/android/server/SystemServer");
    jmethodID methodId = env->GetStaticMethodID(clazz, "init2", "()V");
    env->CallStaticVoidMethod(clazz, methodId);

    return NO_ERROR;
}


3.2 init2阶段

init2回到Java层,启动一个ServerThread线程,启动系统的各项服务。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值