码迷,mamicode.com
首页 > 移动开发 > 详细

Android漫游记(6)---APP启动之旅(I)

时间:2014-07-16 10:13:02      阅读:367      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   java   color   

    Android基于Linux2.6+内核,我们看一张图,以对Android系统的架构有个感性的认识。

bubuko.com,布布扣


    我们从Kernel层简单说明:

    1、Kernel层:基于Linux2.6+内核,同时做了一些嵌入式环境做了一些针对性的优化调整。

    2、Libraries层:包括Bionic C库,以及HAL(硬件驱动接口抽象)等API。

    3、Android Runtime(ART)层:包含核心应用库和Dalvik虚拟机。

    4、Application Framework层:纯JAVA的API框架,包括Activity Manager和Windows Manager等。

    5、Application层:顾名思义,应用层,如预装的电话、短信,游戏APP等。

    

    下面,我们首先看下一个典型的Android系统APP进程映像:

命令行输入PS,查看当前进程列表:

bubuko.com,布布扣

我们看看红圈标注的进程,其中10002为PID,137为父进程ID。

bubuko.com,布布扣

可以看到进程号137的进程即为神秘的“zygote”进程,而zygote的父进程为init进程。init进程为Android一切进程的祖先进程,而zygote则为APP应用的祖先进程。


    至此,我们对Android的应用启动的初始过程有了一个大致的认识,下面,我们结合AOSP(Android Open Source Project)来做更深入的分析。

Android开源代码库:点击打开链接

    首先我们从app_main.cpp开始(点击打开链接),这个就是/system/bin/app_process的C++源码,也就是所有APP的父进程。我们直接对照源码进程阅读,我添加了注释:

int main(int argc, char* const argv[])
{
    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
        // Older kernels don't understand PR_SET_NO_NEW_PRIVS and return
        // EINVAL. Don't die on such kernels.
        if (errno != EINVAL) {
            LOG_ALWAYS_FATAL("PR_SET_NO_NEW_PRIVS failed: %s", strerror(errno));
            return 12;
        }
    }

    AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
    // Process command line arguments
    // ignore argv[0]
    argc--;
    argv++;

    // Everything up to '--' or first non '-' arg goes to the vm.
    //
    // The first argument after the VM args is the "parent dir", which
    // is currently unused.
    //
    // After the parent dir, we expect one or more the following internal
    // arguments :
    //
    // --zygote : Start in zygote mode
    // --start-system-server : Start the system server.
    // --application : Start in application (stand alone, non zygote) mode.
    // --nice-name : The nice name for this process.
    //
    // For non zygote starts, these arguments will be followed by
    // the main class name. All remaining arguments are passed to
    // the main method of this class.
    //
    // For zygote starts, all remaining arguments are passed to the zygote.
    // main function.


    int i = runtime.addVmArguments(argc, argv);

    // Parse runtime arguments.  Stop at first unrecognized option.
    bool zygote = false;
    bool startSystemServer = false;
    bool application = false;
    const char* niceName = NULL;
    String8 className;

    ++i;  // Skip unused "parent dir" argument.
    while (i < argc) {
        const char* arg = argv[i++];
		/*******************
		启动参数包含--zygote
		niceName即进程名,在ARM32下,ZYGOTE_NICE_NAME = zygote(ARM64则为zygote64)
		*******************/
        if (strcmp(arg, "--zygote") == 0) {
            zygote = true;
            niceName = ZYGOTE_NICE_NAME;
        }
        /*******************
		启动参数包含--start-system-server
		置startSystemServer为true,以同时启动system-server
		*******************/		
		else if (strcmp(arg, "--start-system-server") == 0) {
            startSystemServer = true;
        }
        /*******************
		启动参数包含--application
		置application为true,传递参数给dalvik
		*******************/		
		else if (strcmp(arg, "--application") == 0) {
            application = true;
        } else if (strncmp(arg, "--nice-name=", 12) == 0) {
            niceName = arg + 12;
        } else if (strncmp(arg, "--", 2) != 0) {
            className.setTo(arg);
            break;
        } else {
            --i;
            break;
        }
    }

    Vector<String8> args;
    if (!className.isEmpty()) {
        // We're not in zygote mode, the only argument we need to pass
        // to RuntimeInit is the application argument.
        //
        // The Remainder of args get passed to startup class main(). Make
        // copies of them before we overwrite them with the process name.
		/*******************
		非Zygote模式处理
		*******************/	
        args.add(application ? String8("application") : String8("tool"));
        runtime.setClassNameAndArgs(className, argc - i, argv + i);
    } else {
        // We're in zygote mode.
		/*******************
		Zygote模式启动处理
		*******************/	
        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);
            return 11;
        }

        String8 abiFlag("--abi-list=");
        abiFlag.append(prop);
        args.add(abiFlag);

        // In zygote mode, pass all remaining arguments to the zygote
        // main() method.
        for (; i < argc; ++i) {
            args.add(String8(argv[i]));
        }
    }

    if (niceName && *niceName) {
        runtime.setArgv0(niceName);
        set_process_name(niceName);
    }

    if (zygote) {
	    /*******************
		Zygote Init,Dalvik启动
	    *******************/	
        runtime.start("com.android.internal.os.ZygoteInit", args);
    } else if (className) {
        runtime.start("com.android.internal.os.RuntimeInit", args);
    } else {
        fprintf(stderr, "Error: no class name or --zygote supplied.\n");
        app_usage();
        LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
        return 10;
    }
}

上面代码的几个关键地方,我都做了注释,我们看下Android根目录下的init.rc这个初始化脚本,可以找到如下的行:

bubuko.com,布布扣

其作用就是初始化zygote进程。

    zygote启动过程可以大致描述如下:执行app_process,并修改进程名为zygote,同时根据传入的start-system-server参数,启动system-server服务,同时初始化dalvik虚拟机。我们看看AndroidRuntime这个类的源码(点击打开链接),其中start函数的作用有两个,一是启动dalvik VM,一是执行com.android.internal.os.ZygoteInit的main函数,并传递相关参数,实现zygote初始化工作。


    我们再看看com.android.internal.os.ZygoteInit这个JAVA类的源码(点击打开链接),看看究竟都做了什么。

</pre></p><p style="text-align: left;"><pre name="code" class="java">public static void main(String argv[]) {
        try {
            // Start profiling the zygote initialization.
            SamplingProfilerIntegration.start();

            boolean startSystemServer = false;
            String socketName = "zygote";
            String abiList = null;
            for (int i = 1; i < argv.length; i++) {
                if ("start-system-server".equals(argv[i])) {
				/*准备启动system_server*/
                    startSystemServer = true;
                } else if (argv[i].startsWith(ABI_LIST_ARG)) {
                    abiList = argv[i].substring(ABI_LIST_ARG.length());
                } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
				/*Zygote监听的socketname,默认为/dev/socket/zygote   */
                    socketName = argv[i].substring(SOCKET_NAME_ARG.length());
                } else {
                    throw new RuntimeException("Unknown command line argument: " + argv[i]);
                }
            }

            if (abiList == null) {
                throw new RuntimeException("No ABI list supplied.");
            }

			/**注册socket*/
            registerZygoteSocket(socketName);
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                SystemClock.uptimeMillis());
            preload();
            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();

            // Disable tracing so that forked processes do not inherit stale tracing tags from
            // Zygote.
            Trace.setTracingEnabled(false);

            if (startSystemServer) {
                startSystemServer(abiList, socketName);
            }

            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;
        }
    }

ZygoteInit完成实际的system_server启动,同时初始化Zygote的socket监听(/dev/socket/zygote这个伪设备文件),至此终于完成了APP启动的所有准备工作,注意,这只是准备工作,真正的启动过程如下图:

bubuko.com,布布扣

    1、Launcher(Android的“发射进程”,你能看到的桌面,应用列表等都是Launcher的内容)进程监听到应用启动事件,如你点击了APP图标;

    2、通过Binder(Android跨进程通信框架IPC),跨进程通知Activity Manager服务来启动Activity。ActivityManager调用Zygote.forkAndSpecialize来fork一个新的APP子进程并返回PID,然后调用APP的启动Activity的OnStart和OnCreate方法,完成启动!

我们看看Fork这个函数(点击打开链接):Fork的作用是“克隆”一个和当前进程结构一致的全新子进程(当然,并不是完整的照搬)!这是Android的一个聪明的做法,依据Linux的COW(Copy On Write)理论,新生成的进程会“共享”父进程的所有库链接信息,同时会加载自己应有特定的一些LIB,例如Bionic libc库是所有APP共享的,由于它是只读的,因此所有的APP共享一份“物理存储”的LIBC库,而不是每个APP一份拷贝。

我们看看Zygote进程的内存maps片段:

bubuko.com,布布扣

/system/lib下面的这些C库被所有APP进程共享,虽然在不同的APP进程中可能位于不同的虚拟地址,但“共享”一份物理存储!其他的APP启动后的内存映像都是从这个zygote完整“拷贝”过来的!


转载请注明出处:生活秀                Enjoy IT!bubuko.com,布布扣

Android漫游记(6)---APP启动之旅(I),布布扣,bubuko.com

Android漫游记(6)---APP启动之旅(I)

标签:android   style   blog   http   java   color   

原文地址:http://blog.csdn.net/lifeshow/article/details/37812947

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!