Android 应用程序的启动过程(一)

Zygote进程的介绍 基于8.0
Zygote进程称之为孵化进程

系统中所有的应用程序进程及系统SystemServer进程都是由Zygote进程通过Linux的fork()函数孵化出来的。

Zygote进程的启动

zygote进程对应的主入口文件为/frameworks/base/cmds/app_process/app_main.cpp的main()方法:

int main(int argc, char* const argv[])
{
  ......
    while (i < argc) {
        const char* arg = argv[i++];
        if (strcmp(arg, "--zygote") == 0) {
            //在init.rc中含有‘--zygote’参数,说明启动的是Zygote进程
            zygote = true;
            //设置昵称‘--zygote’
            niceName = ZYGOTE_NICE_NAME;
        } else if (strcmp(arg, "--start-system-server") == 0) {
            //启动SystemServer进程
            startSystemServer = true;
        }
    }
   ......

     if (zygote) {
        //zygote 为true 表示正在启动的进程为zygote进程
        //由此可知app_main.cpp在zygote启动其他进程的时候都会通过main()方法
        //这里启动的是zygote进程调用runtime start()方法 传入参数
        runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    } else if (className) {
        runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
    } else {
        fprintf(stderr, "Error: no class name or --zygote supplied.\n");
        app_usage();
        LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
    }
}

最后调用了AppRuntime的start()方法,AppRuntime是app_main.cpp的内部类

class AppRuntime : public AndroidRuntime
{
}

AppRuntime继承了AndroidRuntime实际调用的是AndroidRuntime的start()方法,源码位置/frameworks/base/core/jni/AndroidRuntime

void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{
    ......
    //启动虚拟机
    JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    if (startVm(&mJavaVM, &env, zygote) != 0) {
        return;
    }
    onVmCreated(env);
    //注册JNI函数
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }
    ......
    //className由start()方法传入启动zygote为‘com.android.internal.os.ZygoteInit’
    //转换为斜线格式com/android/internal/os/ZygoteInit
    char* slashClassName = toSlashClassName(className);
    //找出该Class
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        //未找到ZygoteInit.Class
    } else {
        //找到该ZygoteInit.Class 的main方法ID
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
        if (startMeth == NULL) {
            //未找到main方法
        } else {
            //调用 ZygoteInit.Class 的main方法
            env->CallStaticVoidMethod(startClass, startMeth, strArray);
#if 0
            if (env->ExceptionCheck())
                threadExitUncaughtException(env);
#endif
        }
    }
}

AndroidRuntime中做了3件事

  1. 启动虚拟机
  2. 注册JNI函数
  3. 调用ZygoteInit的main()方法
    这里我们主要探究应用程序的启动,主要看ZygoteInit的main()方法,
    /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static void main(String argv[]) {
    //实例化服务端 zygote进程
    ZygoteServer zygoteServer = new ZygoteServer();
    ......

    try {
        ......
        boolean startSystemServer = false;
        String socketName = "zygote";
        String abiList = null;
            boolean enableLazyPreload = false;
            for (int i = 1; i < argv.length; i++) {
                if ("start-system-server".equals(argv[i])) {
                    startSystemServer = true;
                } else if ("--enable-lazy-preload".equals(argv[i])) {
                    enableLazyPreload = 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)) {
                    socketName = argv[i].substring(SOCKET_NAME_ARG.length());
                }
            }
            ......
            //注册一个zygote 的Socket
            zygoteServer.registerServerSocket(socketName);
            //是否需要懒加载准备
            if (!enableLazyPreload) {
                //加载
                preload(bootTimingsTraceLog);
            } else {
                Zygote.resetNicePriority();
            }
            //启动SystemServer
            if (startSystemServer) {
                startSystemServer(abiList, socketName, zygoteServer);
            }
            //循环等待socket连接等待AMS请求
            zygoteServer.runSelectLoop(abiList);
            
            zygoteServer.closeServerSocket();
        } catch (Zygote.MethodAndArgsCaller caller) {
            //捕捉异常后进行操作 启动自进程进入子进程的main()方法
            caller.run();
        } catch (Throwable ex) {
            zygoteServer.closeServerSocket();
        }
    }

ZygoteInit的main方法中一共主要做了5件事:
1.zygoteServer.registerServerSocket注册了一个zygote的Socket接口,用来和AMS通信
2. preload()预加载资源
3.启动SystemServer进程
4.zygote的Socket开启循环等待AMS的连接,与AMS通信
5.caller.run(),启动子进程的main()方法

SystemServer的启动

ActivityManagerService是由SystemServer进程启动的,我们先看下SystemServer进程的启动,ZygoteInit的main方法调用了startSystemServer方法

private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
            throws Zygote.MethodAndArgsCaller, RuntimeException {
        ......
        ZygoteConnection.Arguments parsedArgs = null;
        int pid;
        try {
            parsedArgs = new ZygoteConnection.Arguments(args);
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

            //调用Zygote.forksystemServer
            pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }
         ......
       
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            //pid = 0标识在当前子进程
            //创建成功SystemServer后关闭‘zygote’socket 
            //后执行handleSystemServerProcess
            zygoteServer.closeServerSocket();
            handleSystemServerProcess(parsedArgs);
        }
        return true;
    }

调用了Zygote.forksystemServer方法

   public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
......
        int pid = nativeForkSystemServer(
                uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
......
        return pid;
    }

最后调用了native层的nativeForkSystemServer方法创建了SystemServer进程。
在SystemServer进程创建完后继续调用了ZygoteInit的handleSystemServerProcess,

private static void handleSystemServerProcess(        
   ZygoteConnection.Arguments parsedArgs)
            throws Zygote.MethodAndArgsCaller {
......
   ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
......
}

主要调用了ZygoteInit.zygoteInit方法

public static final void zygoteInit(int targetSdkVersion, String[] argv,
            ClassLoader classLoader) throws Zygote.MethodAndArgsCaller {
......
        //初始化Binder进程
        ZygoteInit.nativeZygoteInit();
        RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
    }

ZygoteInit.zygoteInit主要初始化了Binder相关应用程序,使进程间可以通信, RuntimeInit.applicationInit最后通过反射调用了SystemServer的main方法。源码/frameworks/base/services/java/com/android/server/SystemServer.java main()方法中 new SystemServer().run();直接调用了run方法

private void run() {
......
        //设置虚拟机
        VMRuntime.getRuntime().clearGrowthLimit();
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
        Build.ensureFingerprintProperty();                  
        Environment.setUserRequired(true);
        BaseBundle.setShouldDefuse(true);
        BinderInternal.disableBackgroundScheduling(true);
        BinderInternal.setMaxThreads(sMaxBinderThreads);
        //准备主线程的消息处理
        android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);
            android.os.Process.setCanSelfBackground(false);
        Looper.prepareMainLooper();
        //加载android_servers cpp文件
        System.loadLibrary("android_servers");
        performPendingShutdown();
        //初始化System Context 并创建SystemServiceManager实例
        createSystemContext();
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // Prepare the thread pool for init tasks that can be parallelized
        SystemServerInitThreadPool.get();
    } finally {
        traceEnd();  // InitBeforeStartServices
    }

        // Start services.
    try {
        traceBeginAndSlog("StartServices");
        //开启引导服务
        startBootstrapServices();
        //开启核心服务
        startCoreServices();
        //开启其他服务
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    } catch (Throwable ex) {
    } finally {
        traceEnd();
    }
......

    //开启Looper
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
    }

在SystemServer run方法中
1.设置了虚拟机
2.创建了SystemServiceManager对象
3.开启了其他的服务进程

ActivityManagerService是由引导服务开启的,我们主要跟着AMS走。省略无用代码
private void startBootstrapServices() {
......
    //安装服务
    Installer installer = mSystemServiceManager.startService(Installer.class);
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
     //启动AMS
     mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
          mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    //启动PowerManagerService 服务
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    //让AMS初始化PowerManagerService
    mActivityManagerService.initPowerManagement();
    if (!SystemProperties.getBoolean("config.disable_noncore", false)) {
    //启动 RecoverySystemService服务
mSystemServiceManager.startService(RecoverySystemService.class);
    }
    //启动LightsService 服务
    mSystemServiceManager.startService(LightsService.class);
    //启动DisplayManagerService
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    //启动 PackageManagerService 并实例化PackManager
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
    mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();
    //启动 UserManagerService.LifeCycle
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
     //属性缓存初始化
     AttributeCache.init(mSystemContext);
     mActivityManagerService.setSystemProcess();
     mDisplayManagerService.setupSchedulerPolicies();
     //启动OverlayManagerService
     mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
......
}

可以看到在startBootstrapServices()中我们启动了AMS,PMS等被定义为引导服务的服务。
接着看mSystemServiceManager.startService()方法

    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
......
            final T service;
            try {
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            }
 .......
            startService(service);
            return service;
        } 
    }

通过反射获取SystemService对象后调用本类的startService(service),将service加入管理,最后调用service.onStart();启动了ActivityManagerService.onStart();方法启动了AMS。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值