Skip to content

Android系统启动流程

zhpanvip edited this page Mar 31, 2021 · 6 revisions

Android系统启动流程简述

Android系统的启动流程图如下:Loader->kernel->framework->Application

Loader层:

引导程序是在Android操作系统开始运行前的一个小程序。引导程序是运行的第一个程序,因此它是针 对特定的主板与芯片的。设备制造商要么使用很受欢迎的引导程序比如redboot、uboot、qi bootloader或者开发自己的引导程序,它不是Android操作系统的一部分。引导程序是OEM厂商或者运 营商加锁和限制的地方

Boot Rom:长按开机键,固件在Rom里边预设的代码开始执行,引导程序到Ram

Boot Loader:启动Android系统之前的引导程序,主要是检查Ram,初始化参数等

Kernel层

Kernel层指的是Android内核层,其启动流程如下:

1.启动swapper进程(pid=0)这是系统初始化过程内核创建的第一个进程,用户初始化进程管理、内存管理、加载display、Camera、Binder等驱动相关工作。

2.启动kthread进程,这是系统内核进程,会创建内核工作线程kworker、软中断线程ksoftrqd和thermal等守护进程。kthreadd是所有内核进程的鼻祖。

Native层

native层主要包括有init进程孵化的用户空间的守护进程,bootanim开机动画和hal层等。init是Linux西东的守护进程,是所有用户空间进程的鼻祖。

  • init进程会孵化出ueventdlogdhealthdinstalldadbd、lm这里写代码片kd等用户守护进程;
  • init会启动ServiceManager(Binder服务管家)、bootanim(开机动画)等重要服务
  • init进程孵化出Zygote进程,Zygote进程是Android系统的第一个Java进程,Zygote进程是所有Java进程的父进程。

Framework层

Framework层由native层和Java层共同构成,主要包括以下内容:

  • Media Server进程,有init进程fork出来,负责启动和管理整个C++ framework,包括AudioFinger,Camera Service等服务。
  • Zygote进程,由Init进程通过解析init.rc文件创建而成。Zygote是Android第一个Java进程。
  • SystemServer进程,由Zygote进程fork而来,是Zygote孵化的第一个子进程。负责启动和管理Java Framework、包括AMS、PMS等。

APP层

Zygote进程孵化的第一个APP进程是Launcher进程。同时Zygote进程也会创建Browser、Phone、Email等APP进程。Android系统中的所有APP进程都是由Zygote进程fork出来的。

Zygote进程启动分析

在ZygoteInit的main方法中fork SystemServer类,并将SystemServer类的main方法,封装到Runnable中,然后执行Runable.run方法,即调用SystemServer的main方法,代码如下:

// ZygoteInit    
public static void main(String argv[]) {
        ZygoteServer zygoteServer = new ZygoteServer();

           // ... 简化代码

            boolean startSystemServer = false;

            for (int i = 1; i < argv.length; i++) {
                // 1.加载首个Zygote进程的时候,加载参数有start-system-server,即startSystemServer=true
                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());
                } else {
                    throw new RuntimeException("Unknown command line argument: " + argv[i]);
                }
            }

            // 2. 注册zygote服务端localserversocket
            zygoteServer.registerServerSocketFromEnv(socketName);

            gcAndFinalize();

            Zygote.nativeSecurityInit();

            ZygoteHooks.stopZygoteNoThreadCreation();
      
            // 3.在这里通过forkSystemServer拿到封装了SystemServer.main方法的Runable对象,
            // 并执行main方法,在SystemServer的main方法中会初始化也就是Ams,Pms,Wms...等一系列系统服务
            if (startSystemServer) {
                Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
                if (r != null) {
                    r.run();
                    return;
                }
            }


            // 4.while(true) 死循环,除非抛出异常系统中断
            caller = zygoteServer.runSelectLoop(abiList);
        } catch (Throwable ex) {
            Log.e(TAG, "System zygote died with exception", ex);
            throw ex;
        } finally {
            zygoteServer.closeServerSocket();
        }
    }

forkSystemServer方法用来准备SystemServer进程的参数和fork SystemServer进程。用SystemServer的全限定名“com.android.server.SystemServer”通过Zygote.forkSystemSeerver()初始化SystemServer。返回pid若为0则创建成功,代码如下:

// ZygoteInit  
private static Runnable forkSystemServer(String abiList, String socketName,
        ZygoteServer zygoteServer) {

    /* 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,1021,1023,"
                    + "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010,3011",
            "--capabilities=" + capabilities + "," + capabilities,
            "--nice-name=system_server",
            "--runtime-args",
            "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
            "com.android.server.SystemServer",
      			// 注意这里的参数com.android.server.SystemServer
    };
    ZygoteArguments parsedArgs = null;

    int pid;

    try {
        //传入准备参数,注意上面参数最后的"com.android.server.SystemServer"
        parsedArgs = new ZygoteArguments(args);
        Zygote.applyDebuggerSystemProperty(parsedArgs);
        Zygote.applyInvokeWithSystemProperty(parsedArgs);


        /* Request to fork the system server process */
        pid = Zygote.forkSystemServer(
                parsedArgs.mUid, parsedArgs.mGid,
                parsedArgs.mGids,
                parsedArgs.mRuntimeFlags,
                null,
                parsedArgs.mPermittedCapabilities,
                parsedArgs.mEffectiveCapabilities);
    } catch (IllegalArgumentException ex) {
        throw new RuntimeException(ex);
    }

    /* For child process */
    // pid = 0 说明创建子进程成功,SystemServer此时拥有独立进程,可以独立在自己的进程内操作了
    if (pid == 0) {
        if (hasSecondZygote(abiList)) {
            waitForSecondaryZygote(socketName);
        }

        zygoteServer.closeServerSocket();
        // 处理SystemServer进程
        return handleSystemServerProcess(parsedArgs);
    }

    return null;
}

handleSystemServerProcess方法中初始化类加载器,并执行ZygoteInit.zygoteInit方法。

// ZygoteInit
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {

     // 默认为null,走Zygote.init()流程
    if (parsedArgs.mInvokeWith != null) {
				// ...
    } else {
        ClassLoader cl = null;
        if (systemServerClasspath != null) {
            // 创建类加载器,并赋予当前线程
            cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion);
            Thread.currentThread().setContextClassLoader(cl);
        }

        /*
         * Pass the remaining arguments to SystemServer.
         */
        return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                parsedArgs.mDisabledCompatChanges,
                parsedArgs.mRemainingArgs, cl);
    }

    /* should never reach here */
}

上述方法中parsedArgs.invokeWith默认是为null的,也就是走else流程,可以看到先创建了一个类加载器并赋予了当前线程,然后进入了ZygoteInit.zygoteInit()

ZygoteInit.zygoteInit()方法中主要进行zygote的初始化跟Runtime的初始化。Zygote 的初始化调用了native方法,里面的大致工作是打开/dev/binder驱动设备,创建一个新的binder线程,调用talkWithDriver()不断地跟驱动交互。

public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
        String[] argv, ClassLoader classLoader) {
    if (RuntimeInit.DEBUG) {
        Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
    }

    RuntimeInit.redirectLogStreams();

    RuntimeInit.commonInit();
    ZygoteInit.nativeZygoteInit();
    return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
            classLoader);
}

进入RuntimeInit.applicationInit()查看具体应用初始化流程:

protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
        String[] argv, ClassLoader classLoader) {

    nativeSetExitWithoutCleanup(true);
    VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
    VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
    // 解析参数
    final Arguments args = new Arguments(argv);

    // 反射查找SystemServer的main方法
    return findStaticMain(args.startClass, args.startArgs, classLoader);
}

上述代码将上文中传来的参数封装成了Arguments,然后通过findStaticMain方法反射查找SystemServer的main方法。并将其封装到Runnable中。

protected static Runnable findStaticMain(String className, String[] argv,
        ClassLoader classLoader) {
    Class<?> cl;

    try {
      	// 反射找到SystemServer对应的Class类
        cl = Class.forName(className, true, classLoader);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(
                "Missing class when invoking static main " + className,
                ex);
    }

    Method m;
    try {
        // 获取SystemServer的main方法
        m = cl.getMethod("main", new Class[] { String[].class });
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException(
                "Missing static main on " + className, ex);
    } catch (SecurityException ex) {
        throw new RuntimeException(
                "Problem getting static main on " + className, ex);
    }

		// 将SystemServer的main方法封装到MethodAndArgsCaller中,这个类实现了Runnable
    return new MethodAndArgsCaller(m, argv);
}

MethodAndArgsCaller代码如下,在run方法中调用了invoke,即通过反射执行SystemServer的main方法。

static class MethodAndArgsCaller implements Runnable {
    /** method to call */
    private final Method mMethod;

    /** argument array */
    private final String[] mArgs;

    public MethodAndArgsCaller(Method method, String[] args) {
        mMethod = method;
        mArgs = args;
    }

    public void run() {
        try {
            mMethod.invoke(null, new Object[] { mArgs });
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            Throwable cause = ex.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else if (cause instanceof Error) {
                throw (Error) cause;
            }
            throw new RuntimeException(ex);
        }
    }
}

SystemServer的启动

上一节中通过ZygoteInit最终执行了SystemServer的main方法。而SystemServer的main方法如下:

// SystemServer
public static void main(String[] args) {
    new SystemServer().run();
}

在main方法中初始化了SystemServer并调用了其run方法,run方法如下:

// SystemServer
private void run() {
    TimingsTraceAndSlog t = new TimingsTraceAndSlog();
    try {
				 // ...

        Environment.setUserRequired(true);

        BaseBundle.setShouldDefuse(true);

        Parcel.setStackTraceParceling(true);

        BinderInternal.disableBackgroundScheduling(true);

        BinderInternal.setMaxThreads(sMaxBinderThreads);

        android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(false);
      	// 初始化Looper
        Looper.prepareMainLooper();
        Looper.getMainLooper().setSlowLogThresholdMs(
                SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

        SystemServiceRegistry.sEnableServiceNotFoundWtf = true;

        System.loadLibrary("android_servers");

        initZygoteChildHeapProfiling();

        performPendingShutdown();

        // 创建系统Context
        createSystemContext();

        // Call per-process mainline module initialization.
        ActivityThread.initializeMainlineModules();

        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setStartInfo(mRuntimeRestart,
                mRuntimeStartElapsedTime, mRuntimeStartUptime);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // Prepare the thread pool for init tasks that can be parallelized
        SystemServerInitThreadPool.start();
        // Attach JVMTI agent if this is a debuggable build and the system property is set.
        if (Build.IS_DEBUGGABLE) {
            // Property is of the form "library_path=parameters".
            String jvmtiAgent = SystemProperties.get("persist.sys.dalvik.jvmtiagent");
            if (!jvmtiAgent.isEmpty()) {
                int equalIndex = jvmtiAgent.indexOf('=');
                String libraryPath = jvmtiAgent.substring(0, equalIndex);
                String parameterList =
                        jvmtiAgent.substring(equalIndex + 1, jvmtiAgent.length());
                // Attach the agent.
                try {
                    Debug.attachJvmtiAgent(libraryPath, parameterList, null);
                } catch (Exception e) {
                    Slog.e("System", "*************************************************");
                    Slog.e("System", "********** Failed to load jvmti plugin: " + jvmtiAgent);
                }
            }
        }
    } finally {
        t.traceEnd();  // InitBeforeStartServices
    }

    // Setup the default WTF handler
    RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);

    // Start services.
    try {
        // 开启重要的系统服务
        startBootstrapServices(t);
        startCoreServices(t);
        startOtherServices(t);
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
    }

    StrictMode.initVmDefaults(null);

    if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
        final long uptimeMillis = SystemClock.elapsedRealtime();
        FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
                FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_READY,
                uptimeMillis);
        final long maxUptimeMillis = 60 * 1000;
        if (uptimeMillis > maxUptimeMillis) {
            Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
                    "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
        }
    }

    // Loop forever.开启Loop,让SystemServer永远处于run状态
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

// SystemServer 
// 创建系统Context
private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

    final Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

可以看到,上边代码主要的工作,创建主线程Looper循环器,初始化系统上下文,最关键的还是后面的开启一系列的服务,这些服务就包括了系统服务。接着跟进sartBootstrapService()看看是如何初始化系统服务的:

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
    t.traceBegin("startBootstrapServices");

    final Watchdog watchdog = Watchdog.getInstance();
    watchdog.start();

    SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);

 
    PlatformCompat platformCompat = new PlatformCompat(mSystemContext);
    ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
    ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE,
            new PlatformCompatNative(platformCompat));
    AppCompatCallbacks.install(new long[0]);

    mSystemServiceManager.startService(FileIntegrityService.class);
  
    Installer installer = mSystemServiceManager.startService(Installer.class);

    mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);

    mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);

    ActivityTaskManagerService atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();
    // 开启AMS
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
            mSystemServiceManager, atm);
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    mWindowManagerGlobalLock = atm.getGlobalLock();

    mDataLoaderManagerService = mSystemServiceManager.startService(
            DataLoaderManagerService.class);
  
    mIncrementalServiceHandle = startIncrementalService();

    // 开启PowerManagerService
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

    mSystemServiceManager.startService(ThermalManagerService.class);

    mActivityManagerService.initPowerManagement();

    mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);

    RescueParty.registerHealthObserver(mSystemContext);
    PackageWatchdog.getInstance(mSystemContext).noteBoot();

    mSystemServiceManager.startService(LightsService.class);

    if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
        mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
    }

    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

    String cryptState = VoldProperties.decrypt().orElse("");
    if (ENCRYPTING_STATE.equals(cryptState)) {
        mOnlyCore = true;
    } else if (ENCRYPTED_STATE.equals(cryptState)) {
        mOnlyCore = true;
    }

    // Start the package manager.
    if (!mRuntimeRestart) {
        FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
                FrameworkStatsLog
                        .BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_START,
                SystemClock.elapsedRealtime());
    }

    try {
        Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
        // 初始化PMS
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    } finally {
        Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
    }

    SystemServerDexLoadReporter.configureSystemServerDexReporter(mPackageManagerService);

    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();
    if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
        FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
                FrameworkStatsLog
                        .BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_READY,
                SystemClock.elapsedRealtime());
    }
    if (!mOnlyCore) {
        boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
                false);
        if (!disableOtaDexopt) {
            try {
                Watchdog.getInstance().pauseWatchingCurrentThread("moveab");
                OtaDexoptService.main(mSystemContext, mPackageManagerService);
            } catch (Throwable e) {
                reportWtf("starting OtaDexOptService", e);
            } finally {
                Watchdog.getInstance().resumeWatchingCurrentThread("moveab");
            }
        }
    }

    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);

    AttributeCache.init(mSystemContext);

    mActivityManagerService.setSystemProcess();

    watchdog.init(mSystemContext, mActivityManagerService);

    mDisplayManagerService.setupSchedulerPolicies();

    mSystemServiceManager.startService(new OverlayManagerService(mSystemContext));

    mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));

    if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
        // DisplayManager needs the overlay immediately.
        mActivityManagerService.updateSystemUiContext();
        LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
    }

    mSensorServiceStart = SystemServerInitThreadPool.submit(() -> {
        TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
        traceLog.traceBegin(START_SENSOR_SERVICE);
        startSensorService();
        traceLog.traceEnd();
    }, START_SENSOR_SERVICE);
}

可以看到startBootstrapServices中开启了一些列的系统服务,其中我们比较熟悉的ActivityMangerService、PackageManagerService以及PowerManagerService等都在这里启动。

参考链接:https://juejin.cn/post/6844903663971155982

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

项目相关问题

Android基础知识

Android消息机制

Android Binder

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

Framework

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

Clone this wiki locally