乐趣区

Android-10-系统启动-系列-SystemServer服务管家

前言

因为源码剖析的代码量比拟大,大部分博客网站的内容显示页面都比拟窄,显示进去的成果都异样俊俏,所以您也能够间接查看《Thinking in Android》来浏览这边文章,心愿这篇文章能帮你梳理分明 “SystemServer 过程的原理”

外围源码

要害类 门路
com_android_internal_os_Zygote.cpp frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
AndroidRuntime.cpp frameworks/base/core/jni/AndroidRuntime.cpp
ZygoteInit.java frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
Zygote.java frameworks/base/core/java/com/android/internal/os/Zygote.java
ActivityThread.java frameworks/base/core/java/android/app/ActivityThread.java
ContextImpl.java.java frameworks/base/core/java/android/app/ContextImpl.java
LoadedApk.java.java frameworks/base/core/java/android/app/LoadedApk.java
SystemServer.java frameworks/base/services/java/com/android/server/SystemServer.java
RuntimeInit.java frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
app_main.cpp frameworks/base/cmds/app_process/app_main.cpp
SystemServiceManager.java frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

概述

SystemServer 服务过程是 Android 零碎 Java 层框架的外围,它保护着 Android 零碎的 外围服务 ,比方:ActivityManagerServiceWindowManagerServicePackageManagerService 等,是 Android 零碎中一个十分重要的过程。

在 Android 零碎中,应用程序呈现问题,对系统影响不大,而 InitZygoteSystemServer 三大过程对系统的影响则十分大,因为其中任何一个 crash,都会造成零碎解体,呈现重启景象。

一、SystemServer 启动

SystemServer 是由 Zygote 孵化而来的一个过程,通过 ps 命令,咱们发现其过程名为:system_server

1.1 ZygoteInit.main()

在剖析 zygote 过程 时,咱们晓得当 zygote 过程进入到 java 世界后,在 ZygoteInit.java 中,将调用 forkSystemServer 办法启动 SystemServer 过程。

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

public class ZygoteInit {public static void main(String argv[]) {

        try {if (startSystemServer) {
                // fork 出 system_server
                Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);

                if (r != null) {r.run();
                    return;
                }
            }

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

        try {
            ... ...

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

}

1.2 Zygote.forkSystemServer()

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

public final class Zygote {public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {ZygoteHooks.preFork();
        // Resets nice priority for zygote process.
        resetNicePriority();
        
        // 调用 nativeForkSystemServer() 办法进一步解决,它是一个 native 办法
        int pid = nativeForkSystemServer(
                uid, gid, gids, runtimeFlags, rlimits,
                permittedCapabilities, effectiveCapabilities);
        // Enable tracing as soon as we enter the system_server.
        if (pid == 0) {Trace.setTracingEnabled(true, runtimeFlags);
        }
        ZygoteHooks.postForkCommon();
        return pid;
    }

}

1.3 com_android_internal_os_Zygote_nativeForkSystemServer

咱们来看看对应的 native 办法:

// frameworks/base/core/jni/com_android_internal_os_Zygote.cpp

static jint com_android_internal_os_Zygote_nativeForkSystemServer(
       JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
       jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
       jlong effective_capabilities) {
    ... ...

    // 传入一堆参数,进行理论的 "决裂" 工作,fork 出一个新的过程
    pid_t pid = ForkCommon(env, true,
                           fds_to_close,
                           fds_to_ignore);
    if (pid == 0) {
        SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
                         permitted_capabilities, effective_capabilities,
                         MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
                         false, nullptr, nullptr);
    } else if (pid > 0) {
        // The zygote process checks whether the child process has died or not.
        ALOGI("System server process %d has been created", pid);
      
        // 这里 SystemServer 过程曾经创立进去,pid > 0 阐明在父过程中
        // 将子过程 SystemServer 的 pid 存在 zygote 过程的全局变量中
        gSystemServerPid = pid;
      
        int status;
        if (waitpid(pid, &status, WNOHANG) == pid) {
            // 小概率,SystemServer 过程刚创立,就 crash;此时须要重启 zygote
            ALOGE("System server process %d has died. Restarting Zygote!", pid);
            RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
        }
        ... ...

    }
    return pid;
}

上述代码中,理论的“决裂”工作由函数 ForkCommon()SpecializeCommon() 实现。

1.4 ForkCommon()

// frameworks/base/core/jni/com_android_internal_os_Zygote.cpp

// Utility routine to fork a process from the zygote.
static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
                        const std::vector<int>& fds_to_close,
                        const std::vector<int>& fds_to_ignore) {SetSignalHandlers();
    ... ...
    
    pid_t pid = fork();    // 注册子过程信号监听器
    ... ...
    
    return pid;
}

从下面的代码能够看出,ForkCommon() 最终是通过 fork 的形式,决裂出子过程。

这里须要留神的是,在 zygote 过程 fork 之前,调用了 SetSignalHandlers() 函数注册了一个 子过程信号监听器

1.5 SetSignalHandlers()

// frameworks/base/core/jni/com_android_internal_os_Zygote.cpp

static void SetSignalHandlers() {struct sigaction sig_chld = {};
    sig_chld.sa_handler = SigChldHandler;

    // 该信号监听器关注子过程完结,对应的处理函数为 SigChldHandler
    if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
    }

    struct sigaction sig_hup = {};
    sig_hup.sa_handler = SIG_IGN;
    if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
    }
}

从下面的代码能够看出,SetSignalHandlers() 函数将注册一个信号处理器:SigChldHandler,来监听子过程的死亡。当子过程死亡后,就会产生一个信号,Zygote 过程收到该信号之后就会调用 SigChldHandler() 进行解决。须要留神的是,zygote 的信号监听器,关注的是 zygote 所有的子过程,而不只是 SystemServer 过程(每次创立一个新的过程时,zygote 都会注册对应的监听器)。

1.6 SigChldHandler()

// frameworks/base/core/jni/com_android_internal_os_Zygote.cpp

static void SigChldHandler(int /*signal_number*/) {
    pid_t pid;
    int status;
    int64_t usaps_removed = 0;
  
    while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
        // 通过 status 判断子过程完结的起因,并打印相应的 log
        ... ...

        if (pid == gSystemServerPid) {    // 上文曾经介绍过,gSystemServerPid 中记录了 SystemServer 的 pid
            kill(getpid(), SIGKILL);      // 如果完结的子过程为 SystemServer,Zygote 也将完结本人
        }
    }
    ... ...
}

发现没?所有 zygote 的子过程中,zygote 只关怀了 SystemServer 的死活,它们是 “ 生死共存亡的 ”,当其它子过程 crash 时,zygote 只打印了 log 信息。

咱们之前在剖析 init 的 main() 办法的最初,关注到如下代码:

int main(int argc, char** argv) {
    ... ...

    while (true) {
        // By default, sleep until something happens.
        int epoll_timeout_ms = -1;

        if (do_shutdown && !shutting_down) {
            do_shutdown = false;
            if (HandlePowerctlMessage(shutdown_command)) {shutting_down = true;}
        }

        if (!(waiting_for_prop || Service::is_exec_service_running())) {am.ExecuteOneCommand();
        }
        if (!(waiting_for_prop || Service::is_exec_service_running())) {if (!shutting_down) {
                // 重启死掉的 service,如果是 Zygote 死掉了,就重启 Zygote
                auto next_process_restart_time = RestartProcesses();
        ... ...

    }
}

在 init 的 main() 函数中,如果 Zygote 进行工作,Init 过程就调用 RestartProcesses() 函数来重启 Zygote。

所以,init 过程 Zygote 过程 SystemServer 过程 严密相连,任何一个都不能出问题!

通过 fork 创立出 SystemServer 过程后,SystemServer 过程会调用 handleSystemServerProcess 函数,开始执行本人的工作。

1.7 ZygoteInit.forkSystemServer()

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

public class ZygoteInit {

    private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
        ... ...
    
        /* For child process */
        if (pid == 0) {if (hasSecondZygote(abiList)) {waitForSecondaryZygote(socketName);
            }

            zygoteServer.closeServerSocket();
            return handleSystemServerProcess(parsedArgs);    // SystemServer 过程解决本人的工作
        }

        return null;
    }
}

1.8 ZygoteInit.handleSystemServerProcess()

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

public class ZygoteInit {

    /**
     * Finish remaining work for the newly forked system server process.
     */
    private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {if (parsedArgs.mNiceName != null) {Process.setArgV0(parsedArgs.mNiceName);
        }

        // 加载 SystemServer 对应的文件
        final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
        if (systemServerClasspath != null) {if (performSystemServerDexOpt(systemServerClasspath)) {sCachedSystemServerClassLoader = null;}
            boolean profileSystemServer = SystemProperties.getBoolean("dalvik.vm.profilesystemserver", false);
            if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
                try {prepareSystemServerProfile(systemServerClasspath);
                } catch (Exception e) {Log.wtf(TAG, "Failed to set up system server profile", e);
                }
            }
        }

        if (parsedArgs.mInvokeWith != null) {... ...} else {createSystemServerClassLoader();    // 构建对应的 ClassLoader
            ClassLoader cl = sCachedSystemServerClassLoader;
            if (cl != null) {Thread.currentThread().setContextClassLoader(cl);
            }

            // 将残余参数及 classLoader 递交给 ZygoteInit 的 zygoteInit() 函数
            return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                    parsedArgs.mRemainingArgs, cl);
        }
    }

    /* should never reach here */
}

从下面的代码能够看出,接下来的流程进入到 ZygoteInit 的 zygoteInit() 函数。zygoteInit 函数将依据 classLoader 和参数,实现不同过程所须要的初始化工作(SystemServer 过程与 Zygote 的其它子过程均将应用 zygoteInit 函数)。

1.9 ZygoteInit.zygoteInit()

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

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

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();

        RuntimeInit.commonInit();         // 惯例初始化操作,临时不做深刻
        ZygoteInit.nativeZygoteInit();    // native 办法,为 Binder 通信做好筹备
        return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);    // 见 1.12
    }

}

1.10 ZygoteInit.nativeZygoteInit()

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

static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{gCurRuntime->onZygoteInit();      // gCurRuntime 指的是什么?}

咱们晓得,在 app_main.cppmain 函数中,创立了 AppRuntime

int main(int argc, char* const argv[])
{AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
}

AppRuntime 定义如下:

class AppRuntime : public AndroidRuntime
{
public:
    AppRuntime(char* argBlockStart, const size_t argBlockLength)
        : AndroidRuntime(argBlockStart, argBlockLength)
        , mClass(NULL)
    { }
    ... ...
}

看看 AppRuntime 的父类 AndroidRuntime:

AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) :
        mExitWithoutCleanup(false),
        mArgBlockStart(argBlockStart),
        mArgBlockLength(argBlockLength)
{SkGraphics::Init();

    // Pre-allocate enough space to hold a fair number of options.
    mOptions.setCapacity(20);

    assert(gCurRuntime == NULL);        // one per process
    gCurRuntime = this;
}

从代码能够看出,AndroidRuntime 初始化时定义了 gCurRuntimegCurRuntime 指向对象本身,也就是说 gCurRuntime 指向的是 AppRuntime 对象

因为 SystemServer 过程由 zygote 过程 fork 进去,所以 SystemServer 过程中也存在 gCurRuntime 对象,类型为 AppRuntime

至此咱们晓得,Native 函数中 gCurRuntime->onZygoteInit 将调用 AppRuntime 中的 onZygoteInit()

1.11 app_main.onZygoteInit()

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

    virtual void onZygoteInit()
    {sp<ProcessState> proc = ProcessState::self();
        ALOGV("App process: starting thread pool.\n");
        proc->startThreadPool();    // 启动一个线程,用于 binder 通信}

1.12 RuntimeInit.applicationInit()

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

public class RuntimeInit {protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
            ClassLoader classLoader) {
        // 设置一些过程退出的解决策略,可用堆栈下限等
        ... ...

        // Remaining arguments are passed to the start class's static main
        return findStaticMain(args.startClass, args.startArgs, classLoader);
    }
    
}

1.13 RuntimeInit.findStaticMain()

跟踪 findStaticMain()

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

public class RuntimeInit {protected static Runnable findStaticMain(String className, String[] argv,
            ClassLoader classLoader) {
        // className 为进行初始化工作的过程类名
        // 在 SystemServer 初始化时,为 com.android.server.SystemServer
        Class<?> cl;

        try {
            // 上面就是通过反射失去对应类的 main 办法
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Missing class when invoking static main" + className,
                    ex);
        }
        ... ...

        return new MethodAndArgsCaller(m, argv);    // 捕捉 MethodAndArgsCaller 异样
    }
    
}

二、SystemServer 工作流程

2.1 SystemServer.main()

接下来就进入了 SystemServer.javamain() 函数解决流程:

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

public final class SystemServer {

    /**
     * The main entry point from zygote.
     */
    public static void main(String[] args) {new SystemServer().run();        // 创立并运行,简略粗犷!}
    
}

这里比较简单,只是 new 出一个 SystemServer 对象 并执行其 run() 办法。

2.2 SystemServer.run()

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

public final class SystemServer {private void run() {
        try {traceBeginAndSlog("InitBeforeStartServices");
            ... ...

            // 如何零碎时钟早于 1970 年,则设置零碎始终从 1970 年开始
            if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {Slog.w(TAG, "System clock is before 1970; setting to 1970.");
                SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
            }

            ... ...    

            if (!SystemProperties.get("persist.sys.language").isEmpty()) {
                // 设置区域,语言等选项    
                final String languageTag = Locale.getDefault().toLanguageTag();

                SystemProperties.set("persist.sys.locale", languageTag);
                SystemProperties.set("persist.sys.language", "");
                SystemProperties.set("persist.sys.country", "");
                SystemProperties.set("persist.sys.localevar", "");
            }
            ... ...

           // 革除 vm 内存增长下限,因为启动过程须要较多的虚拟机内存空间
            VMRuntime.getRuntime().clearGrowthLimit();                                     

            // 设置堆栈利用率,GC 后会从新计算堆栈空间大小
            VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);                         
            
            // 针对局部设施依赖于运行时就产生指纹信息,因而须要在开机实现前曾经定义
            Build.ensureFingerprintProperty();                                             
            
            // 拜访环境变量前,须要明确地指定用户
            Environment.setUserRequired(true);                                             
            ... ...

            // 加载动静库 libandroid_services.so
            System.loadLibrary("android_servers");                                         
            
            // 检测上次关机过程是否失败,该办法可能不会返回
            performPendingShutdown();                                                        
            
           // 在 SystemServer 过程中也须要创立 Context 对象,初始化零碎上下文
            createSystemContext();                                                         
            
            // 创立 SystemServiceManager 对象
            mSystemServiceManager = new SystemServiceManager(mSystemContext);  
            // SystemServer 过程次要是用来构建零碎各种 service 服务,// 而 SystemServiceManager 就是这些服务的治理对象            
            mSystemServiceManager.setStartInfo(mRuntimeRestart,
                    mRuntimeStartElapsedTime, mRuntimeStartUptime);        
            
            // 将 SystemServiceManager 对象保留到 SystemServer 过程中的一个数据结构中            
            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();    // 次要用于启动零碎 Boot 级服务        
            startCoreServices();         // 次要用于启动系统核心的服务       
            startOtherServices();        // 次要用于启动一些非紧要或者非须要及时启动的服务    
            SystemServerInitThreadPool.shutdown();} catch (Throwable ex) {Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {traceEnd();
        }
        ... ...

        // 启动 looper,以解决到来的音讯,始终循环执行
        Looper.loop();                                                                       
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

}

以上就是 SystemServer.run() 办法的整个流程,简化如下:

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

public final class SystemServer {private void run() {
        try {
            // Initialize the system context.
            createSystemContext();    // 01. 初始化零碎上下文
            
            // 02. 创立零碎服务治理                                       
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);                  
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);   
        } finally {traceEnd();  // InitBeforeStartServices
        }

        // 03. 启动零碎各种服务
        try {startBootstrapServices();    // 启动疏导服务
            startCoreServices();         // 启动外围服务
            startOtherServices();        // 启动其余服务
            SystemServerInitThreadPool.shutdown();}

        // Loop forever.
        Looper.loop();    // 始终循环执行  
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

}

接下来咱们针对 SystemServer 所做的 三局部工作 独自剖析!

2.3 初始化零碎上下文

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

public final class SystemServer {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);
    }

}

跟踪 systemMain() 办法:

// frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread extends ClientTransactionHandler {public static ActivityThread systemMain() {
        // The system process on low-memory devices do not get to use hardware
        // accelerated drawing, since this can add too much overhead to the
        // process.
        if (!ActivityManager.isHighEndGfx()) {ThreadedRenderer.disable(true);    // 对于低内存的设施,禁用硬件加速
        } else {ThreadedRenderer.enableForegroundTrimming();
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(true, 0);    // 调用 attach() 办法
        return thread;
    }

}

跟踪 attach() 办法:

// frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread extends ClientTransactionHandler {private void attach(boolean system, long startSeq) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {... ...} else {
            // Don't set application object here -- if the system crashes,
            // we can't display an alert, we just want to die die die.
            // 设置 SystemServer 过程在 DDMS 中显示的名字为 "system_process"
            android.ddm.DdmHandleAppName.setAppName("system_process",
                    UserHandle.myUserId());    // 如不设置,则显示 "?",无奈调试该过程
            try {mInstrumentation = new Instrumentation();
                mInstrumentation.basicInit(this);
                // 首先通过 getSystemContext() 创立零碎上下文,而后创立利用上下文
                ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
                // 创立 Application
                mInitialApplication = context.mPackageInfo.makeApplication(true, null);
                // 调用 Application 的 onCreate()
                mInitialApplication.onCreate();} catch (Exception e) {
                throw new RuntimeException("Unable to instantiate Application():" + e.toString(), e);
            }        
        }
        ... ...

        ViewRootImpl.ConfigChangedCallback configChangedCallback
                = (Configuration globalConfig) -> {synchronized (mResourcesManager) {
                // We need to apply this change to the resources immediately, because upon returning
                // the view hierarchy will be informed about it.
                if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
                        null /* compat */)) {updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
                            mResourcesManager.getConfiguration().getLocales());

                    // This actually changed the resources! Tell everyone about it.
                    if (mPendingConfiguration == null
                            || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
                        mPendingConfiguration = globalConfig;
                        sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
                    }
                }
            }
        };
        // 增加回调
        ViewRootImpl.addConfigCallback(configChangedCallback);                             
    }

}

咱们发现 attach() 办法次要做了四件事:
(1)创立零碎上下文:getSystemContext()
(2)创立利用上下文:createAppContext()
(3)创立 Application:makeApplication()
(4)增加回调 configChangedCallbackViewRootImpl

(1)创立零碎上下文

// frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread extends ClientTransactionHandler {public ContextImpl getSystemContext() {synchronized (this) {if (mSystemContext == null) {mSystemContext = ContextImpl.createSystemContext(this);
            }
            return mSystemContext;
        }
    }

}
// frameworks/base/core/java/android/app/ContextImpl.java

class ContextImpl extends Context {static ContextImpl createSystemContext(ActivityThread mainThread) {
        // 这边 new 进去的 LoadedApk 将作为创立利用上下文的参数 packageInfo
        LoadedApk packageInfo = new LoadedApk(mainThread);
        // ContextImpl() 创立零碎上下文 
        ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
                null, null);
        context.setResources(packageInfo.getResources());
        context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
                context.mResourcesManager.getDisplayMetrics());
        return context;
    }

}

(2)创立利用上下文

// frameworks/base/core/java/android/app/ContextImpl.java

class ContextImpl extends Context {static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {return createAppContext(mainThread, packageInfo, null);
    }

    static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo,
            String opPackageName) {if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
        // ContextImpl() 创立利用上下文
        ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
                null, opPackageName);
        context.setResources(packageInfo.getResources());
        return context;
    }

}

咱们能够看出:new ContextImpl() 时,零碎上下文和利用上下文的参数是一样的,createAppContext() 中的参数 packageInfo,就是 createSystemContext() 中 new 的 LoadedApk

创立实现之后,零碎上下文赋值给了 ActivityThread 的成员变量 mSystemContext,而利用上下文只是作为函数中的局部变量长期应用。

(3)创立 Application

// frameworks/base/core/java/android/app/LoadedApk.java

public final class LoadedApk {

    public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {if (mApplication != null) {return mApplication;}

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");

        Application app = null;

        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {    // forceDefaultAppClass 为 true                               
            appClass = "android.app.Application";
        }

        try {java.lang.ClassLoader cl = getClassLoader();
            // 此 LoadedApk 对象是 createSystemContext 时 new 的,mPackageName = "android"
            if (!mPackageName.equals("android")) {initializeJavaContextClassLoader();
            }
            // 又创立了一个部分利用上下文
            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);  
            // 创立 Application 
            app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {if (!mActivityThread.mInstrumentation.onException(app, e)) {Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                throw new RuntimeException(
                    "Unable to instantiate application" + appClass
                    + ":" + e.toString(), e);
            }
        }

        // 将后面创立的 app 增加到利用列表
        mActivityThread.mAllApplications.add(app);
        mApplication = app;
        ... ...

        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

        return app;
    }

}

2.4 创立零碎服务治理

咱们回顾下 创立零碎服务治理 相干代码:

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

public final class SystemServer {private void run() {
        try {
            // Initialize the system context.
            createSystemContext();    // 01. 初始化零碎上下文
            
            // 02. 创立零碎服务治理                                       
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);                  
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);   
        } finally {traceEnd();  // InitBeforeStartServices
        }
    ... ...
    
}

这一步比较简单,只是 new 了一个 SystemServiceManager,并将其增加到本地服务列表中。mSystemContext 为第一步中创立的零碎上下文。本地服务列表是以类为 key 保留的一个列表,即列表中某种类型的对象最多只能有一个。

new SystemServiceManager()

// frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

public class SystemServiceManager {
    ... ...

    // 零碎服务列表,零碎服务必须继承 SystemService
    private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

    // 以后处于开机过程的哪个阶段
    private int mCurrentPhase = -1;

    SystemServiceManager(Context context) {mContext = context;}

    @SuppressWarnings("unchecked")
    // 通过类名启动零碎服务,可能会找不到类而抛异样
    public SystemService startService(String className) {
        final Class<SystemService> serviceClass;
        try {serviceClass = (Class<SystemService>)Class.forName(className);
        } catch (ClassNotFoundException ex) {Slog.i(TAG, "Starting" + className);
            throw new RuntimeException("Failed to create service" + className
                    + ": service class not found, usually indicates that the caller should"
                    + "have called PackageManager.hasSystemFeature() to check whether the"
                    + "feature is available on this device before trying to start the"
                    + "services that implement it", ex);
        }
        return startService(serviceClass);
    }

    @SuppressWarnings("unchecked")
    // 创立并启动零碎服务,零碎服务类必须继承 SystemService
    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {final String name = serviceClass.getName();
            Slog.i(TAG, "Starting" + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService" + name);

            // Create the service.
            if (!SystemService.class.isAssignableFrom(serviceClass)) {
                throw new RuntimeException("Failed to create" + name
                        + ": service must extend" + SystemService.class.getName());
            }
            final T service;
            try {Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            } catch (InstantiationException ex) {... ...}

            startService(service);
            return service;
        } finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }

    public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {service.onStart();
        } catch (RuntimeException ex) {throw new RuntimeException("Failed to start service" + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
    }

    // 告诉零碎服务到了开机的哪个阶段,会遍历调用所有零碎服务的 onBootPhase() 函数
    public void startBootPhase(final int phase) {
        ... ...

        try {Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "OnBootPhase" + phase);
            final int serviceLen = mServices.size();
            for (int i = 0; i < serviceLen; i++) {final SystemService service = mServices.get(i);
                long time = SystemClock.elapsedRealtime();
                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, service.getClass().getName());
                try {service.onBootPhase(mCurrentPhase);
                } catch (Exception ex) {
                    throw new RuntimeException("Failed to boot service"
                            + service.getClass().getName()
                            + ": onBootPhase threw an exception during phase"
                            + mCurrentPhase, ex);
                }
                warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
            }
        } finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }
    
}

2.5 启动零碎各种服务

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

public final class SystemServer {private void run() {
        // 01. 初始化零碎上下文
        // 02. 创立零碎服务治理                                       
        // 03. 启动零碎各种服务
        try {startBootstrapServices();    // 启动疏导服务
            startCoreServices();         // 启动外围服务
            startOtherServices();        // 启动其余服务
            SystemServerInitThreadPool.shutdown();}

        // Loop forever.
        Looper.loop();    // 始终循环执行  
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

}

(1)启动疏导服务

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

public final class SystemServer {

    /**
     * Starts the small tangle of critical services that are needed to get the system off the
     * ground.  These services have complex mutual dependencies which is why we initialize them all
     * in one place here.  Unless your service is also entwined in these dependencies, it should be
     * initialized in one of the other functions.
     */
    private void startBootstrapServices() {
        ... ...

        // 启动 Installer 服务,阻塞期待与 installd 建设 socket 通道
        Installer installer = mSystemServiceManager.startService(Installer.class);

        mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);

        mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);

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

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

        mSystemServiceManager.startService(ThermalManagerService.class);

        // PowerManagerService 就绪,AMS 初始化电源治理
        mActivityManagerService.initPowerManagement();

        mActivityManagerService.initPowerManagement();

        mSystemServiceManager.startService(RecoverySystemService.class);

        RescueParty.noteBoot(mSystemContext);

        // 启动 LightsService
        mSystemServiceManager.startService(LightsService.class);

        // 启动 DisplayManagerService
        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

        // We need the default display before we can initialize the package manager.
        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

        // 当设施正在加密时,仅运行外围利用
        String cryptState = SystemProperties.get("vold.decrypt");
        if (ENCRYPTING_STATE.equals(cryptState)) {Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
            mOnlyCore = true;
        } else if (ENCRYPTED_STATE.equals(cryptState)) {Slog.w(TAG, "Device encrypted - only parsing core apps");
            mOnlyCore = true;
        }

        // Start the package manager.
        if (!mRuntimeRestart) {
            MetricsLogger.histogram(null, "boot_package_manager_init_start",
                    (int) SystemClock.elapsedRealtime());
        }

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

        mFirstBoot = mPackageManagerService.isFirstBoot();
        mPackageManager = mSystemContext.getPackageManager();
        ... ...

        // 将 UserManagerService 增加到服务列表,该服务是在 PackageManagerService 中初始化的        
        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);

        // 初始化用来缓存包资源的属性缓存
        AttributeCache.init(mSystemContext);

        // Set up the Application instance for the system process and get started.
        mActivityManagerService.setSystemProcess();
        ... ...

        mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
            TimingsTraceLog traceLog = new TimingsTraceLog(SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
            traceLog.traceBegin(START_SENSOR_SERVICE);
            startSensorService();    // 启动传感器服务
            traceLog.traceEnd();}, START_SENSOR_SERVICE);
    }

}

首先期待 installd 启动实现,而后启动一些相互依赖的要害服务。

(2)启动外围服务

接下来持续看下外围服务的启动:

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

public final class SystemServer {

    /**
     * Starts some essential services that are not tangled up in the bootstrap process.
     */
    private void startCoreServices() {
        // 启动 BatteryService,用于统计电池电量,须要 LightService
        mSystemServiceManager.startService(BatteryService.class);

        // 启动 UsageStatsService,用于统计利用应用状况
        mSystemServiceManager.startService(UsageStatsService.class);
        mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));

        // 启动 WebViewUpdateService
        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
        }
        .... ...

    }

}

(3)启动其余服务

代码很长(1200 多行 …),然而逻辑简略,次要是启动各种服务。

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

public final class SystemServer {

    /**
     * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
     */
    private void startOtherServices() {
        ... ...

        try {
            ... ...

            // 调度策略
            ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());

            mSystemServiceManager.startService(TelecomLoaderService.class);

            // 提供电话注册、治理服务,能够获取电话的链接状态、信号强度等
            telephonyRegistry = new TelephonyRegistry(context);
            ServiceManager.addService("telephony.registry", telephonyRegistry);

            mEntropyMixer = new EntropyMixer(context);
            
            mContentResolver = context.getContentResolver();

            // 提供所有账号、明码、认证治理等等的服务
            mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
            ... ...

            // 振动器服务
            vibrator = new VibratorService(context);
            ServiceManager.addService("vibrator", vibrator);
            ... ...

            inputManager = new InputManagerService(context);

            // WMS needs sensor service ready
            ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
            mSensorServiceStart = null;
            wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
                    new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
            ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
                    DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
            ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
                    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
            ... ...

        } catch (RuntimeException e) {Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting core service", e);
        }
        ... ...

        LockSettingsService               // 屏幕锁定服务,治理每个用户的相干锁屏信息
        DeviceIdleController              // Doze 模式的次要驱动
        DevicePolicyManagerService        // 提供一些零碎级别的设置及属性
        StatusBarManagerService           // 状态栏治理服务
        ClipboardService                  // 零碎剪切板服务
        NetworkManagementService          // 网络管理服务
        TextServicesManagerService        // 文本服务,例如文本查看等
        NetworkScoreService               // 网络评分服务
        NetworkStatsService               // 网络状态服务
        NetworkPolicyManagerService       // 网络策略服务
        WifiP2pService                    // Wifi Direct 服务
        WifiService                       // Wifi 服务
        WifiScanningService               // Wifi 扫描服务
        RttService                        // Wifi 相干
        EthernetService                   // 以太网服务
        ConnectivityService               // 网络连接治理服务
        NsdService                        // 网络发现服务
        NotificationManagerService        // 告诉栏治理服务
        DeviceStorageMonitorService       // 磁盘空间状态检测服务
        LocationManagerService            // 位置服务,GPS、定位等
        CountryDetectorService            // 检测用户国家
        SearchManagerService              // 搜寻治理服务
        DropBoxManagerService             // 用于零碎运行时日志的存储于治理
        WallpaperManagerService           // 壁纸治理服务
        AudioService                      // AudioFlinger 的下层治理封装,次要是音量、音效、声道及铃声等的治理
        DockObserver                      // 如果零碎有个座子,当手机装上或插入这个座子的话,就得靠他来治理了
        WiredAccessoryManager             // 监督手机和底座上的耳机
        UsbService                        // USB 服务
        SerialService                     // 串口服务
        TwilightService                   // 指出用户以后所在位置是否为早晨,被 UiModeManager 等用来调整夜间模式
        BackupManagerService              // 备份服务
        AppWidgetService                  // 提供 Widget 的治理和相干服务
        VoiceInteractionManagerService    // 语音交互治理服务
        DiskStatsService                  // 磁盘统计服务,供 dumpsys 应用
        SamplingProfilerService           // 用于耗时统计等
        NetworkTimeUpdateService          // 监督网络工夫,当网络工夫变动时更新本地工夫。CertBlacklister                   // 提供一种机制更新 SSL certificate blacklist
        DreamManagerService               // 屏幕爱护
        PrintManagerService               // 打印服务
        HdmiControlService                // HDMI 管制服务
        FingerprintService                // 指纹服务
        ... ...

    }

}

以上代码仅按程序列出启动的服务,有些服务依据条件,如是否是工厂模式或零碎属性配置,选择性启动,这里不思考条件判断和异样解决。

自此,SystemServer 相干源码剖析结束。

退出移动版