本节是本系列文章的第三篇,将分析System_Server进程的启动过程和Launcher的启动过程。

第一篇文章:Android系统启动分析(一)


第二篇文章:Android系统启动分析(二)

本节涉及到的文件有:

文件 路径
ZygoteInit.java frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
ZygoteServer.java frameworks/base/core/java/com/android/internal/os/ZygoteServer.java
AndroidRuntime.cpp frameworks/base/core/jni/AndroidRuntime.cpp
app_main.cpp frameworks/base/cmds/app_process/app_main.cpp
RuntimeInit.cpp frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
SystemServer.java frameworks/base/core/java/com/android/server/SystemServer.java
SystemServiceManager.java frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

三、SystemServer进程启动

在上节讲到了从Zygote进程启动SystemServer进程,本节将分析SystemServer进程的启动过程。

3.1 ZygoteInit.forkSystemServer

我们再来回顾下创建SystemServer的过程。

frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
//准备一些启动参数
……
try {
……
//注释1:调用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);
}

//如果pid == 0,当前代码逻辑运行在子进程中
if (pid == 0) {
//如果有第二个Zygote,则等待第二个Zygote连接
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
//注释2:关闭Zygote进程创建的Socket
zygoteServer.closeServerSocket();
//注释3:处理SystemServer进程
return handleSystemServerProcess(parsedArgs);
}
return null;
}

该部分涉及到SystemServer进程创建的主要是注释1、3两处。首先Zygote会通过forkSystemServer方法来创建一个新的进程启动SystemServer,同时返回进程pid,若pid==0,会调用handleSystemServerProcess处理SystemServer进程。在上节提到,forkSystemServer最终会调用nativeForkSystemServer()来处理,这里不会细说。
注释2处:由Zygote创建的子进程默认拥有Zygote进程的Socket对象,而子进程用不上,所以这里调用了closeServerSocket来关闭Socket。

3.1.1 handleSystemServerProcess

我们重点关注handleSystemServerProcess方法。

frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
……
if (parsedArgs.niceName != null) {
//设置进程名字为niceName:system_server
Process.setArgV0(parsedArgs.niceName);
}
//注释1
//system/framework/{services.jar,ethernet-service.jar,wifi-service.jar}
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
//注释2:执行dex优化
performSystemServerDexOpt(systemServerClasspath);
……
}

if (parsedArgs.invokeWith != null) {
……
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
//注释3:创建类加载器并赋予当前线程
cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
//注释4
return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
}

注释1处:systemServerClasspath路径为:/system/framework/services.jar:/system/framework/ethernet-service.jar:/system/framework/wifi-service.jar:/system/framework/com.android.location.provider.jar
注释2处:调用performSystemServerDexOpt对注释1处几个jar包执行dex优化
注释3处:创建类加载器并赋予当前线程
注释4处:将启动SystemServer的参数解析后的剩余参数”com.android.server.SystemServer”保存到parsedArgs.remainingArgs,并传入ZygoteInit.zygoteInit()中

3.1.2 ZygoteInit.zygoteInit

frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
1
2
3
4
5
6
7
8
9
10
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
//初始化Android Log输出流,重定向System.out和System.err到Android Log
RuntimeInit.redirectLogStreams();
//注释1:初始化通用的运行环境
RuntimeInit.commonInit();
//注释2:通过JNI初始化Zygote
ZygoteInit.nativeZygoteInit();
//注释3:应用初始化
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}

注释1处:初始化通用运行环境,如设置默认的未捕捉异常的Handler,设置时区,重置Log配置等
重点看看注释2处:ZygoteInit.nativeZygoteInit()和注释3处:RuntimeInit.applicationInit()

3.1.3 启动Binder线程池

frameworks/base/core/jni/AndroidRuntime.cpp
1
2
3
4
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
frameworks/base/cmds/app_process/app_main.cpp
1
2
3
4
void onZygoteInit(){
sp<ProcessState> proc = ProcessState::self();
proc->startThreadPool(); //启动新的binder线程
}

该处代码主要工作是打开”/dev/binder”设备节点,并启动一个新的binder线程,这样SystemServer进程就可以使用Binder进行进程间通信。

3.1.4 RuntimeInit.applicationInit

frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
1
2
3
4
5
6
7
8
9
10
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,ClassLoader classLoader) {
//设置关闭应用程序是否调用AppRuntime.onExit()
nativeSetExitWithoutCleanup(true);
//设置虚拟机堆内存利用率为0.75
VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
final Arguments args = new Arguments(argv);
//注释1
return findStaticMain(args.startClass, args.startArgs, classLoader);
}

注释1处:调用findStaticMain()反射获取到SystemServer的main()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;

try {
//反射得到SystemServer类
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
}

Method m;
try {
//反射获取SystemServer.main()方法
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) {
}

int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
}

return new MethodAndArgsCaller(m, argv);
}

该处主要作用是先反射得到SystemServer类并获取其main方法,将其传给MethodAndArgsCaller,并返回。MethodAndArgsCaller是一个Runnale实现类,其run()方法里反射调用传进去的Method,在这里就是SystemServer.main()方法,最后run()在ZygoteInit.main()中调用。

3.2 解析SystemServer

frameworks/base/core/java/com/android/server/SystemServer.java
1
2
3
public static void main(String[] args) {
new SystemServer().run();
}

SystemServer的main方法做的事很简单,只是调用了SystemServer().run()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
private void run() {
try {
//初始化时区
//变更虚拟机的库文件
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
……
//创建消息Looper
Looper.prepareMainLooper();
//加载android_servers.so库
System.loadLibrary("android_servers");
……
//初始化系统Context
createSystemContext();

//创建SystemServiceManager
mSystemServiceManager = new SystemServiceManager(mSystemContext);
……
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
//准备线程池
SystemServerInitThreadPool.get();
} finally {
}
// Start services.
try {
//启动引导服务
startBootstrapServices();
//启动核心服务
startCoreServices();
//启动其他服务
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
throw ex;
} finally {
}
……
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

SystemServer.run方法创建了一个SystemServiceManager对象,并将其加到LocalServices中,其内部有一个ArrayMap用来保存添加的服务。
startBootstrapServices()、startCoreServices()和startOtherServices()分别用来启动引导服务、核心服务和其他服务。

3.2.1 startBootstrapServices

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private void startBootstrapServices() {
Installer installer = mSystemServiceManager.startService(Installer.class);
……
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);

mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
mActivityManagerService.initPowerManagement();

mSystemServiceManager.startService(LightsService.class);

mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
……
}

从上面可以看出,在startBootstrapServices里面启动了很多服务,如ActivityManagerService、PowerManagerService、LightsService、DisplayManagerService、PackageManagerService、UserManagerService等

3.2.2 startCoreServices

1
2
3
4
5
6
7
8
9
10
11
private void startCoreServices() {
mSystemServiceManager.startService(DropBoxManagerService.class);
mSystemServiceManager.startService(BatteryService.class);
……
mSystemServiceManager.startService(UsageStatsService.class);
……
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
……
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}

startCoreServices中启动了DropBoxManagerService、BatteryService、UsageStatsService、WebViewUpdateService等服务

3.2.3 startOtherServices

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private void startOtherServices() {
final Context context = mSystemContext;
VibratorService vibrator = null;
IStorageManager storageManager = null;
NetworkManagementService networkManagement = null;
NetworkStatsService networkStats = null;
NetworkPolicyManagerService networkPolicy = null;
ConnectivityService connectivity = null;
NetworkScoreService networkScore = null;
NsdService serviceDiscovery= null;
WindowManagerService wm = null;
SerialService serial = null;
NetworkTimeUpdateService networkTimeUpdater = null;
CommonTimeManagementService commonTimeMgmtService = null;
InputManagerService inputManager = null;
TelephonyRegistry telephonyRegistry = null;
ConsumerIrService consumerIr = null;
MmsServiceBroker mmsService = null;
HardwarePropertiesManagerService hardwarePropertiesService = null;
FaceIdManagerService faceIdService = null;
……
}

startOtherServices启动的服务较多,且逻辑与上述两个方法相似,便不再分析。

3.2.4 系统服务的启动

从3.2节可以看到,系统服务的启动一般都是通过SystemServiceManager.startService来完成。这里以ActivityManagerService的启动来分析。

1
2
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();

ActivityManagerService通过SystemServiceManager.startService来启动,startService方法如下所示:

frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
if (!SystemService.class.isAssignableFrom(serviceClass)) {
……
}
final T service;
try {
//获取类的构造器
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
……
} catch (IllegalAccessException ex) {
……
} catch (NoSuchMethodException ex) {
……
} catch (InvocationTargetException ex) {
……
}
//将service传给startService
startService(service);
return service;
} finally {
……
}
}

该方法先获取到ActivityManagerService.LiftCycle的构造,再构造出一个LiftCycle的对象,最后将LiftCycle的对象传给重载方法startService(final SystemService service)

1
2
3
4
5
6
7
8
9
10
11
12
13
public void startService(@NonNull final SystemService service) {
//注释1
mServices.add(service);
long time = SystemClock.elapsedRealtime();
try {
//注释2
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");
}

注释1处:将service对象添加到mServices中,mServices是一个存储SystemService的ArrayList,其定义如下:

private final ArrayList mServices = new ArrayList();

注释2处:回调ActivityManagerService.LiftCycle对象的onStart方法完成启动ActivityManagerService

3.3 SystemServer进程总结

SystemService进程是Android中一个很重要的进程,由Zygote进启动,其启动过程中主要做了如下工作:

  1. 初始化一些系统变量和运行环境
  2. 启动Binder线程池
  3. 创建消息Looper、加载类库、初始化系统Context、创建SystemServiceManager等
  4. 启动各种系统服务

参考

https://blog.csdn.net/hongbochen1223/article/details/56331690
https://juejin.im/post/5aaf125d6fb9a028db587c50
https://blog.csdn.net/itachi85/article/details/54783506
https://blog.csdn.net/zhonglunshun/article/details/78615980
https://juejin.im/post/59f4592e51882529405991cb#heading-6
https://blog.csdn.net/qq_30993595/article/details/82747738
SystemServer进程启动流程