基于大佬的博客,在最新的android源码上记录自己的学习。 所参考博客,均贴出引用源,具体可参考原博主代码,可能更加详细。
因害怕忘记,故总结在此!
2024.7.14
源码基于Android 14
参考:袁辉辉大佬博客
涉及到相关类的路径
core/rootdir/init.zygote32.rc
base/core/java/com/android/internal/os/ZygoteInit.java
base/core/jni/com_android_internal_os_Zygote.cpp
base/core/jni/AndroidRuntime.cpp
base/cmds/app_process/app_main.cpp
native/libs/binder/ProcessState.cpp
base/core/java/com/android/internal/os/RuntimeInit.java
services/java/com/android/server/SystemServer.java
1.SystemServer进程是什么
SystemServer进程承载着Framework的核心服务,像AMS、WMS都在system_server进程。
2.SystemServer进程是谁创建的
SystemServer进程是Zygote fork出来的第一个进程。
3.SystemServer进程的创建过程和启动入口
从zygote进程的启动过程,我们可以知道zygote进程是init进程解析init.zygote32.rc(以32位系统为例)调用到ZygoteInit.main方法的。
路径:core/rootdir/init.zygote32.rc
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
class main
3.1 解析start-system-server参数 ZygoteInit.main
上面的rc文件中是argv参数 --zygote --start-system-server
public static void main(String[] argv) {
ZygoteServer zygoteServer = null;
Runnable caller;
try {
boolean startSystemServer = false;
String zygoteSocketName = "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)) {
zygoteSocketName = argv[i].substring(SOCKET_NAME_ARG.length());
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}
zygoteServer = new ZygoteServer(isPrimaryZygote);
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
if (r != null) {
r.run();
return;
}
}
caller = zygoteServer.runSelectLoop(abiList);
if (caller != null) {
caller.run();
}
}
3.2 forkSystemServer
上面字符串匹配到start-system-server,因此开始调用forkSystemServer创建systemserver。
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
/* 准备systemserver的参数,uid和pid都是1000,进程名是systemserver */
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,3005,3006,3007,3009,3010,3011,3012",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
"com.android.server.SystemServer",
};
ZygoteArguments parsedArgs;
int pid;
try {
ZygoteCommandBuffer commandBuffer = new ZygoteCommandBuffer(args);
try {
//用于解析参数,生成目标格式
parsedArgs = ZygoteArguments.getInstance(commandBuffer);
} catch (EOFException e) {
throw new AssertionError("Unexpected argument error for forking system server", e);
}
commandBuffer.close();
.....
/* 创建子进程,fork出system_server进程,0表示子进程 */
pid = Zygote.forkSystemServer(
parsedArgs.mUid, parsedArgs.mGid,
parsedArgs.mGids,
parsedArgs.mRuntimeFlags,
null,
parsedArgs.mPermittedCapabilities,
parsedArgs.mEffectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
//关闭父进程zygote复制而来的Socket
if (pid == 0) {
//如果还有另外一个zygote进程,则先等待启动第二个创建完成
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
//zygoteServer.closeServerSocket();
zygoteServer.closeServerSocket();
//执行systemserver进程
return handleSystemServerProcess(parsedArgs);
}
return null;
}
3.2.1 Zygote进程fork SystemServer进程 forkSystemServer
路径:base/core/java/com/android/internal/os/Zygote.java
static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
ZygoteHooks.preFork();
int pid = nativeForkSystemServer(
uid, gid, gids, runtimeFlags, rlimits,
permittedCapabilities, effectiveCapabilities);
// Set the Java Language thread priority to the default value for new apps.
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
ZygoteHooks.postForkCommon();
return pid;
}
3.2.1.1 JNI调用 nativeForkSystemServer
路径:base/core/jni/com_android_internal_os_Zygote.cpp
通过JNI调用,调用到com_android_internal_os_Zygote.cpp的com_android_internal_os_Zygote_nativeForkSystemServer方法,这里nativeForkSystemServer到com_android_internal_os_Zygote_nativeForkSystemServer的映射是在AndroidRuntime.start.startReg进行的。
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) {
pid_t pid = zygote::ForkCommon(env, true,
fds_to_close,
fds_to_ignore,
true);
if (pid == 0) {
// System server进程正常创建
SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, permitted_capabilities,
effective_capabilities, 0, MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
false, nullptr, nullptr, /* is_top_app= */ false,
/* pkg_data_info_list */ nullptr,
/* allowlisted_data_info_list */ nullptr, false, false, false);
} else if (pid > 0) {
// // zygote进程检测system_server进程是否创建
ALOGI("System server process %d has been created", pid);
gSystemServerPid = pid;
// There is a slight window that the system server process has crashed
// but it went unnoticed because we haven't published its pid yet. So
// we recheck here just to make sure that all is well.
int status;
if (waitpid(pid, &status, WNOHANG) == pid) {
////当system_server进程死亡后,重启zygote进程.因为systemserver进程是zygote创建的,因此这里需要在重启zygote
ALOGE("System server process %d has died. Restarting Zygote!", pid);
RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
}
if (UsePerAppMemcg()) {
// Assign system_server to the correct memory cgroup.
// Not all devices mount memcg so check if it is mounted first
// to avoid unnecessarily printing errors and denials in the logs.
if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
ALOGE("couldn't add process %d into system memcg group", pid);
}
}
}
return pid;
}
当systemserver进程创建失败时候,会重启zygote进程。
3.2.1.2 JNI层 ForkCommon
路径:base/core/jni/com_android_internal_os_Zygote.cpp
pid_t zygote::ForkCommon(JNIEnv* env, bool is_system_server,
const std::vector<int>& fds_to_close,
const std::vector<int>& fds_to_ignore,
bool is_priority_fork,
bool purge) {
//fork子进程
pid_t pid = fork();
if (pid == 0) {
//进入子进程
if (is_priority_fork) {
setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
} else {
setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MIN);
}
#if defined(__BIONIC__) && !defined(NO_RESET_STACK_PROTECTOR)
// Reset the stack guard for the new process.
android_reset_stack_guards();
#endif
// The child process.
PreApplicationInit();
//关闭并清除文件描述符
DetachDescriptors(env, fds_to_close, fail_fn);
// Invalidate the entries in the USAP table.
ClearUsapTable();
// Re-open all remaining open file descriptors so that they aren't shared
// with the zygote across a fork.
gOpenFdTable->ReopenOrDetach(fail_fn);
// Turn fdsan back on.
android_fdsan_set_error_level(fdsan_error_level);
// Reset the fd to the unsolicited zygote socket
gSystemServerSocketFd = -1;
} else if (pid == -1) {
ALOGE("Failed to fork child process: %s (%d)", strerror(errno), errno);
} else {
ALOGD("Forked child process %d", pid);
}
// We blocked SIGCHLD prior to a fork, we unblock it here.
UnblockSignal(SIGCHLD, fail_fn);
if (is_priority_fork && pid != 0) {
setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_DEFAULT);
}
return pid;
}
3.2.1.3 fork创建新进程
这里的fork采用了copy on write方式,这是linux创建进程的标准方法,会有两次return,pid==0是子进程的返回,pid > 0是父进程的返回。到这里只是完成了systemserver进程的创建工作,接下来就真正的去执行systemserver的真正工作。
3.2.2 handleSystemServerProcess 执行systemserver进程
路径:base/core/java/com/android/internal/os/ZygoteInit.java
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
// set umask to 0077 so new files and directories will default to owner-only permissions.
Os.umask(S_IRWXG | S_IRWXO);
//设置进程名字,就是上面我们设置的nicename
if (parsedArgs.mNiceName != null) {
Process.setArgV0(parsedArgs.mNiceName);
}
if (parsedArgs.mInvokeWith != null) {
String[] args = parsedArgs.mRemainingArgs;
// If we have a non-null system server class path, we'll have to duplicate the
// existing arguments and append the classpath to it. ART will handle the classpath
// correctly when we exec a new process.
if (systemServerClasspath != null) {
String[] amendedArgs = new String[args.length + 2];
amendedArgs[0] = "-cp";
amendedArgs[1] = systemServerClasspath;
System.arraycopy(args, 0, amendedArgs, 2, args.length);
args = amendedArgs;
}
WrapperInit.execApplication(parsedArgs.mInvokeWith,
parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
VMRuntime.getCurrentInstructionSet(), null, args);
throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
} else {
// 创建类加载器,并赋予当前线程
ClassLoader cl = getOrCreateSystemServerClassLoader();
if (cl != null) {
Thread.currentThread().setContextClassLoader(cl);
}
/*
* 传递参数到systemserver进程
*/
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl);
}
/* should never reach here */
}
3.2.2.1 ZygoteInit.zygoteInit
public static Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
//重定向log输出
RuntimeInit.redirectLogStreams();
//通用的一些初始化
RuntimeInit.commonInit();
//创建Binder,创建BInder线程池
ZygoteInit.nativeZygoteInit();
//应用的初始化
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}
3.3.2.2 commonInit
路径:core/java/com/android/internal/os/RuntimeInit.java
protected static final void commonInit() {
// 设置默认的未捕捉异常处理方法
LoggingHandler loggingHandler = new LoggingHandler();
RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));
// 设置时区,中国时区为"Asia/Shanghai"
RuntimeHooks.setTimeZoneIdSupplier(() -> SystemProperties.get("persist.sys.timezone"));
//重置log配置
LogManager.getLogManager().reset();
new AndroidConfig();
//设置默认的HTTP User-agent格式,用于 HttpURLConnection。
String userAgent = getDefaultUserAgent();
System.setProperty("http.agent", userAgent);
// 设置socket的tag,用于网络流量统计
TrafficStats.attachSocketTagger();
initialized = true;
}
3.2.2.3 JNI调用 nativeZygoteInit
路径:base/core/jni/AndroidRuntime.cpp
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
路径:base/cmds/app_process/app_main.cpp
virtual void onZygoteInit()
{
//ProcessState::self()是单例模式,主要是
//通过open打开/dev/binder驱动设备,再通过mmap映射内核的地址空间。
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
//创建线程池
proc->startThreadPool();
}
路径:native/libs/binder/ProcessState.cpp
sp<ProcessState> ProcessState::self()
{
return init(kDefaultDriver, false /*requireDefault*/);
}
3.2.2.4 applicationInit
路径:base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
//true代表应用程序退出时不调用AppRuntime.onExit(),否则会在退出前调用
nativeSetExitWithoutCleanup(true);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
//解析传入的argv参数
final Arguments args = new Arguments(argv);
// The end of of the RuntimeInit event (see #zygoteInit).
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
// 调用systemserver的main方法,这里的args.startClass是"com.android.server.SystemServer"
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
3.2.2.5 findStaticMain
这里的findStaticMain实质上就是反射的方式调用SystemServer进程的main方法,从此开始SystemServer进程启动系统服务的过程。
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
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);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
*/
return new MethodAndArgsCaller(m, argv);
}
/**
* Helper class which holds a method and arguments and can call them. This is used as part of
* a trampoline to get rid of the initial process setup stack frames.
*/
static class MethodAndArgsCaller implements Runnable {
public void run() {
try {
//根据传递过来的参数,可知此处通过反射机制
//调用的是SystemServer.main()方法
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
.....
}
}
}
4.SystemServer进程的启动过程
路径:services/java/com/android/server/SystemServer.java
4.1 main
路径:services/java/com/android/server/SystemServer.java
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
4.2 run
private void run() {
//初始化systemserver主线程的looper
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
// Initialize native services.
System.loadLibrary("android_servers");
//检测上次关机过程是否失败,该方法可能不会返回
performPendingShutdown();
//初始化系统上下文
createSystemContext();
//创建SystemServiceManager
mSystemServiceManager = new SystemServiceManager(mSystemContext);
//将mSystemServiceManager添加到本地服务的成员sLocalServiceObjects
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
......
// Start services.
try {
t.traceBegin("StartServices");
// 启动引导服务
startBootstrapServices(t);
// 启动核心服务
startCoreServices(t);
// 启动其他服务
startOtherServices(t);
startApexServices(t);
// Only update the timeout after starting all the services so that we use
// the default timeout to start system server.
updateWatchdogTimeout(t);
CriticalEventLog.getInstance().logSystemServerStarted();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
t.traceEnd(); // StartServices
}
......
// Looper进入循环模式,等待消息
Looper.loop();
}
这里的LocalServices.addService将服务添加到静态Map变量sLocalServiceObjects中,key对应的是服务的名字,value表示具体的服务。
4.2.1 performPendingShutdown
private void performPendingShutdown() {
final String shutdownAction = SystemProperties.get(
ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
if (shutdownAction != null && shutdownAction.length() > 0) {
boolean reboot = (shutdownAction.charAt(0) == '1');
final String reason;
if (shutdownAction.length() > 1) {
reason = shutdownAction.substring(1, shutdownAction.length());
} else {
reason = null;
}
......
Runnable runnable = new Runnable() {
@Override
public void run() {
// 当"sys.shutdown.requested"值不为空,则会重启或者关机
ShutdownThread.rebootOrShutdown(null, reboot, reason);
}
};
// ShutdownThread must run on a looper capable of displaying the UI.
//发送一个重启或者关机的message
Message msg = Message.obtain(UiThread.getHandler(), runnable);
msg.setAsynchronous(true);
UiThread.getHandler().sendMessage(msg);
}
4.2.2 createSystemContext
createSystemContext过程会创建ActivityThread、Instrumentation、ContextImpl,LoadedApk,Application。
private void createSystemContext() {
//设置systemserver进程上下文信息
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
路径:base/core/java/android/app/ActivityThread.java
public static ActivityThread systemMain() {
ThreadedRenderer.initForSystemProcess();
ActivityThread thread = new ActivityThread();
thread.attach(true, 0);
return thread;
}
4.2.3 startBootstrapServices
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
//启动watchdog
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
mDumper.addDumpable(watchdog);
t.traceEnd();
//阻塞等待与installd建立socket通道
Installer installer = mSystemServiceManager.startService(Installer.class);
//启动AMS
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
//启动PMS
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
//初始化PowerManagement
mActivityManagerService.initPowerManagement();
mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
//启动DMS
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
t.traceEnd();
// We need the default display before we can initialize the package manager.
t.traceBegin("WaitForDisplay");
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
t.traceEnd();
try {
Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
//启动PKMS
mPackageManagerService = PackageManagerService.main(
mSystemContext, installer, domainVerificationService,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
mActivityManagerService.setSystemProcess();
watchdog.init(mSystemContext, mActivityManagerService);
ResourcesManagerService resourcesService = new ResourcesManagerService(mSystemContext);
resourcesService.setActivityManagerService(mActivityManagerService);
mSystemServiceManager.startService(resourcesService);
该过程创建的服务有AMS,PMS,DMS,PMS,PKMS,RMS等。
4.2.4 startCoreServices
private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
t.traceBegin("startCoreServices");
// Service for system config
mSystemServiceManager.startService(SystemConfigService.class);
// Tracks the battery level. Requires LightService.
mSystemServiceManager.startService(BatteryService.class);
// Tracks application usage stats.
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
// Tracks whether the updatable WebView is in a ready state and watches for update installs.
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
// Tracks and caches the device state.
mSystemServiceManager.startService(CachedDeviceStateService.class);
// Tracks cpu time spent in binder calls
t.traceBegin("StartBinderCallsStatsService");
mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
t.traceEnd();
// Tracks time spent in handling messages in handlers.
t.traceBegin("StartLooperStatsService");
mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
t.traceEnd();
// Manages apk rollbacks.
t.traceBegin("StartRollbackManagerService");
mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);
t.traceEnd();
// Tracks native tombstones.
t.traceBegin("StartNativeTombstoneManagerService");
mSystemServiceManager.startService(NativeTombstoneManagerService.class);
t.traceEnd();
// Service to capture bugreports.
t.traceBegin("StartBugreportManagerService");
mSystemServiceManager.startService(BugreportManagerService.class);
t.traceEnd();
// Service for GPU and GPU driver.
t.traceBegin("GpuService");
mSystemServiceManager.startService(GpuService.class);
t.traceEnd();
// Handles system process requests for remotely provisioned keys & data.
t.traceBegin("StartRemoteProvisioningService");
mSystemServiceManager.startService(RemoteProvisioningService.class);
t.traceEnd();
// TODO(b/277600174): Start CpuMonitorService on all builds and not just on debuggable
// builds once the Android JobScheduler starts using this service.
if (Build.IS_DEBUGGABLE || Build.IS_ENG) {
// Service for CPU monitor.
t.traceBegin("CpuMonitorService");
mSystemServiceManager.startService(CpuMonitorService.class);
t.traceEnd();
}
t.traceEnd(); // startCoreServices
}
该过程启动了CpuMonitorService(CPU监控)、BugreportManagerService(bugreport管理)、UsageStatsManagerInternal(统计应用使用情况)等服务。
4.2.5 startOtherServices
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
//启动闹钟管理服务
mSystemServiceManager.startService(ALARM_MANAGER_SERVICE_CLASS);
//创建IMS
inputManager = new InputManagerService(context);
//创建WMS
wm = WindowManagerService.main(context, inputManager, !mFirstBoot,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
//添加WMS到ServiceManager中
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
//添加IMS到ServiceManager中
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
//设置AMS的WMS
mActivityManagerService.setWindowManager(wm);
//WMS 初始化
wm.onInitReady();
//启动SensorManagerService
SystemServerInitThreadPool.submit(() -> {
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
traceLog.traceBegin(START_SENSOR_MANAGER_SERVICE);
startISensorManagerService();
traceLog.traceEnd();
}, START_SENSOR_MANAGER_SERVICE);
//启动hidlservices
SystemServerInitThreadPool.submit(() -> {
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
traceLog.traceBegin(START_HIDL_SERVICES);
startHidlServices();
traceLog.traceEnd();
}, START_HIDL_SERVICES);
//start IMS
inputManager.start();
wm.displayReady();
wm.systemReady();
//创建StatusBarManagerService
try {
statusBar = new StatusBarManagerService(context);
statusBar.publishGlobalActionsProvider();
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar, false,
DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
} catch (Throwable e) {
reportWtf("starting StatusBarManagerService", e);
}
mSystemServiceManager.startService(NotificationManagerService.class);
//启动WallpaperManagerService
if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
t.traceBegin("StartWallpaperManagerService");
mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
t.traceEnd();
} else {
Slog.i(TAG, "Wallpaper service disabled by config");
}
mPackageManagerService.systemReady();
mDisplayManagerService.systemReady(safeMode);
mActivityManagerService.systemReady(() -> {
}
//启动systemUI
startSystemUi(context, windowManagerF);
}
该过程创建启动了一系列服务,例如创建了WMS,然后WMS、PMS、DMS和AMS进入systemReady状态。
之后执行Looper.loop,等待其他线程通过handler发送消息到主线程去处理消息。
4.2.6 startApexServices
*
* <p>Apex services must be the last category of services to start. No other service must be
* starting after this point. This is to prevent unnecessary stability issues when these apexes
* are updated outside of OTA; and to avoid breaking dependencies from system into apexes.
*/
private void startApexServices(@NonNull TimingsTraceAndSlog t) {
t.traceBegin("startApexServices");
// TODO(b/192880996): get the list from "android" package, once the manifest entries
// are migrated to system manifest.
List<ApexSystemServiceInfo> services = ApexManager.getInstance().getApexSystemServices();
for (ApexSystemServiceInfo info : services) {
String name = info.getName();
String jarPath = info.getJarPath();
t.traceBegin("starting " + name);
if (TextUtils.isEmpty(jarPath)) {
mSystemServiceManager.startService(name);
} else {
mSystemServiceManager.startServiceFromJar(name, jarPath);
}
t.traceEnd();
}
// make sure no other services are started after this point
mSystemServiceManager.sealStartedServices();
t.traceEnd(); // startApexServices
}
4.3 启动服务类别总结
systemserver进程启动了很多服务,从源码角度来说启动了引导服务、核心服务、其他服务和新加的apex服务四种服务。
1.引导服务:AMS、PMS、LightsServices等服务
2.核心服务:CpuMonitorService(CPU监控)、BugreportManagerService(bugreport管理)、UsageStatsManagerInternal(统计应用使用情况)等服务
3.其他服务:WMS、IMS等服务
4.Apex服务:好像不是很重要...
5.总结
systemserver进程是zygote进程出来的第一个进程,在zygote进程中通过forkSystemServer创建出systemserver进程后,然后通过handleSystemServerProcess 去启动systemserver进程,在systemserver进程启动时,要先通过ZygoteInit.zygoteInit为systemserver进程去创建Binder、创建Binder线程池,然后通过反射的方式,调用到SystemServer中的main方法,去启动引导服务、核心服务和其他服务。