Android漫游记(6)---APP启动之旅(I)
Android基于Linux2.6+内核,我们看一张图,以对Android系统的架构有个感性的认识。
我们从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,查看当前进程列表:
我们看看红圈标注的进程。当中10002为PID,137为父进程ID。
能够看到进程号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这个初始化脚本。能够找到例如以下的行:
其作用就是初始化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启动的全部准备工作,注意。这仅仅是准备工作。真正的启动步骤例如以下图:
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片段:
/system/lib以下的这些C库被全部APP进程共享,尽管在不同的APP进程中可能位于不同的虚拟地址,但“共享”一份物理存储!其它的APP启动后的内存映像都是从这个zygote完整“拷贝”过来的。
转载请注明出处:生活秀  
              Enjoy IT!
posted on 2017-06-30 09:40 cynchanpin 阅读(329) 评论(0) 收藏 举报
                    
                
                
            
        
浙公网安备 33010602011771号