前言
上一篇流程分析了zygote进程的启动,在zygote进程启动中会调用forkSystemServer()方法去启动systemserver进程,接下来就具体分析一下源码的逻辑
forkSystemServer
//#ZygoteInit.java
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
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",
};
ZygoteArguments parsedArgs = null;
int pid;
try {
//将上面准备的参数,按照 ZygoteArguments 的风格进行封装
parsedArgs = new ZygoteArguments(args);
Zygote.applyDebuggerSystemProperty(parsedArgs);
Zygote.applyInvokeWithSystemProperty(parsedArgs);
if (shouldProfileSystemServer()) {
parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
}
/* Request to fork the system server process */
pid = Zygote.forkSystemServer( //通过fork 分裂 出system_server
parsedArgs.mUid, parsedArgs.mGid,
parsedArgs.mGids,
parsedArgs.mRuntimeFlags,
null,
parsedArgs.mPermittedCapabilities,
parsedArgs.mEffectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) { //处理 32_64这种兼容模式的情况
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket(); // fork 时会 copy socket,system server 需要主动关闭
return handleSystemServerProcess(parsedArgs);
}
return null;
}
//#Zygote.java
static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
//调用native的forkSystemServer方法
int pid = nativeForkSystemServer(
uid, gid, gids, runtimeFlags, rlimits,
permittedCapabilities, effectiveCapabilities);
return pid;
}
private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
解析完参数过后,通过Zygote.forkSystemServer孵化出system_server进程,fork的机制就是拷贝,为了区别是zygote进程还是systemserver进程,会在fork后返回一个pid值,如果是system_server进程,pid就是0,而zygote进程的pid就是system_server分配的一个pid值
通过代码流程发现调到了jni的nativeForkSystemServer方法,有前文可以知道,在Zygote启动的时候会初始化ART的运行环境,里面会有JNI的注册,但是没有找到对应的方法,最后发现,Zygote会有一个对应的c++的JNI类,然后对应到了对应的方法中
Zygote对应的c++文件路径.png
#com_android_internal_os_Zygote.c++
int register_com_android_internal_os_Zygote(JNIEnv* env) {
//这个JNI方法的里面会传入一个gMethods参数,这里面就有我们需要的nativeForkSystemServer的对应Native方法的注册
return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
}
static const JNINativeMethod gMethods[] = {
{"nativeForkSystemServer", "(II[II[[IJJ)I",
(void*)com_android_internal_os_Zygote_nativeForkSystemServer},
};
//具体的执行的nativeForkSystemServer方法
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) {
//进一步调用了ForkCommon
pid_t pid = ForkCommon(env, true,
fds_to_close,
fds_to_ignore,
true);
//这部分也有根据pid区分进程执行不同代码的逻辑的判断
if (pid == 0) {
} else if (pid > 0) {
}
return pid;
}
static pid_t 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) {
//最终调用到fork()方法,而fork的就会根据孵化的复制关系返回不同的pid值
pid_t pid = fork();
if (pid == 0) {
} else {
}
return pid;
}
fork()这个机制就是完全的复制,所以不同的进程都有执行相同的代码,执行fork()后就会产生新的进程,就有对应的pid生成,为了区分不同的进程,所以fork()后会有不同的pid返回值,可以看到这套流程都是通过pid==0进行判断是否是新孵化的进程去做差异化处理,在ZygoteInit.java中
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) { //处理 32_64这种兼容模式的情况
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket(); // fork 时会 copy socket,system server 需要主动关闭
return handleSystemServerProcess(parsedArgs);
}
在pid==0条件下,进入system_server进程的处理逻辑,zygote进程会通过socket方式等待其他进程的消息通知去孵化新的进程,但是SystemServer没必要保持这样的socket,就会主动去关闭socket连接,释放资源,接下来就进入了SystemServer的专属启动逻辑handleSystemServerProcess()方法
handleSystemServerProcess
/**
* Finish remaining work for the newly forked system server process.
* 完成新分叉的系统服务器进程的剩余工作。
*/
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
if (parsedArgs.mNiceName != null) {
Process.setArgV0(parsedArgs.mNiceName);
}
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (parsedArgs.mInvokeWith != null) {
//上面的forksystemserver方法可以看出,没有给mInvokeWith赋值,所以这部分逻辑不会进
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
/*
* Pass the remaining arguments to SystemServer.
* 将剩余的参数传递给 SystemServer。
*/
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl);
}
}
ZygoteInit.zygoteInit
//除开上面的初始化逻辑,这个方法主要执行了两个部分
public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
...
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit();
//step 1 开启Binder线程池
//systemserver里面会和很多系统服务进程通信,Android中跨进程通信使用binder机制,所以开启binder线程池管理
ZygoteInit.nativeZygoteInit();
//step 2 运行systemserver.main
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}
<!--step 1-->
//调用JNI的方法
private static final native void nativeZygoteInit();
#AndroidRuntime.cpp中注册的位置,对应的方法
int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
{
const JNINativeMethod methods[] = {
{ "nativeZygoteInit", "()V",
(void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
};
return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
methods, NELEM(methods));
}
//c++中的方法
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
//当前运行环境中,开启Binder线程池
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
proc->startThreadPool();
}
<!--step 2-->
#RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
final Arguments args = new Arguments(argv);
// Remaining arguments are passed to the start class's static main
// 执行这一步
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
#RuntimeInit.java
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
//一看这样的写法就是需要反射去调用
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
}
Method m;
try {
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))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
//接下来执行这一步
return new MethodAndArgsCaller(m, argv);
}
//将上面反射拿到的方法和参数进行了封装,最终返回一个Runnable对象
static class MethodAndArgsCaller implements Runnable {
private final Method mMethod;
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
public void run() {
try {
//通过反射执行SystemServer.main()方法
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
} catch (InvocationTargetException ex) {
}
}
}
小结
通过上面的逻辑,zygote执行forkSystemServer()方法会找到一个Runnable对象,并在后面执行对应的run()方法,这一部分涉及到pid的判断,当pid==0进入SystemServer进程的逻辑,开启binder线程池,然后通过反射找到SystemServer.java对象的main()方法,并调用
接下来就进入到了SystemServer.main方法,执行systemserver进程的具体逻辑
#SystemServer.java
public static void main(String[] args) {
new SystemServer().run();
}
//主要流程
private void run() {
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
final long uptimeMillis = SystemClock.elapsedRealtime();
...
Looper.prepareMainLooper(); //初始化主线程的looper
// Initialize the system context.
createSystemContext(); //创建系统上下文
// 初始化SystemServiceManager
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();
// Start services.
try {
t.traceBegin("StartServices");
startBootstrapServices(t); //启动引导服务 AMS PKMS PMS
startCoreServices(t); //启动核心服务
startOtherServices(t);//启动其他服务
} catch (Throwable ex) {
} finally {
t.traceEnd(); // StartServices
}
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.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
小结
system_server启动的主要流程有
-
createSystemContext() 创建系统的上下文
-
mSystemServiceManager = new SystemServiceManager(mSystemContext) 系统服务管理进程
-
startBootstrapServices(t) 启动引导服务 AMS/PKMS/PMS等
-
startCoreServices 启动核心服务
-
startOtherServices 启动其他服务 WMS等
针对上面的几步流程,进一步在源码中梳理一下
1 createSystemContext
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
#ActivityThread
public static ActivityThread systemMain() {
//实例化ActivityThread,并且调用attach方法
ActivityThread thread = new ActivityThread();
thread.attach(true, 0);
return thread;
}
//attach方法内容比较多,先关注跟初始化相关的东西
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
//非系统进程的处理逻辑,app进程进入这一块,现在是Systemserver进程,进入else
} else {
// Don't set application object here -- if the system crashes,
// we can't display an alert, we just want to die die die.
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
//创建appcontext
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
//初始化一个application,第二个参数 Instrumentation传参为null
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
}
}
//获取系统的context上下文,是个单例
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
mSystemContext = ContextImpl.createSystemContext(this);
}
return mSystemContext;
}
}
//SystemServer进程也会有一个application类,第二个参数为null
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
try {
//有ClassLoader一般就是通过反射的方式去实例化对象
final java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
initializeJavaContextClassLoader();
}
// Rewrite the R 'constants' for all library apks.
SparseArray<String> packageIdentifiers = getAssets().getAssignedPackageIdentifiers(
false, false);
for (int i = 0, n = packageIdentifiers.size(); i < n; i++) {
final int id = packageIdentifiers.keyAt(i);
if (id == 0x01 || id == 0x7f) {
continue;
}
rewriteRValues(cl, packageIdentifiers.valueAt(i), id);
}
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
NetworkSecurityConfigProvider.handleNewApplication(appContext);
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
}
mActivityThread.mAllApplications.add(app);
mApplication = app;
if (instrumentation != null) {
//SystemServer进程instrumentation为null,不会走这段逻辑,也就不会走应用开发常用的application中的oncreate方法回调
try {
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
}
}
return app;
}
systemserver我们关注的第一步就是创建系统上下文
1.createSystemContext();
1.ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
2.mInitialApplication = context.mPackageInfo.makeApplication(true, null);
SystemServer进程会有一个进程独有的ContextImpl上下文,这个上下文是通过getSystemContext系统上下文关联创建的,然后类似一般的app应用进程,会有application类,但是具体的makeApplication()执行流程跟应用进程还是有差距,不会回调application的oncreate()方法,这部分只需要了解systemserver进程里面有自己的contextImpl,也有自己的application对象
2 启动SystemServiceManager
#SystemServiceManager
//系统服务的大管家,里面有一个系统服务的集合,系统服务是继承自SystemService
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
public SystemService startService(String className) {
final Class<SystemService> serviceClass = loadClassFromLoader(className,
this.getClass().getClassLoader());
return startService(serviceClass);
}
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (Exception ex) {
}
startService(service);
return service;
} finally {
}
}
然后就是会启动一个SystemServiceManager的进程,这个通过名字就能知道是用来管理不同的系统服务的进程,在SystemServer进程后续的流程中启动各种系统需要的基础服务,这些服务启动后都是被SystemServiceManager进程进行生命周期的管理
3 startBootstrapServices
//各种系统的服务的启动都是通过SystemServiceManager的start方法
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
mSystemServiceManager.startService(FileIntegrityService.class);
Installer installer = mSystemServiceManager.startService(Installer.class);
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
//ATMS管理app常见的四大组件之Activity,Android10.0后新增的系统服务
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//app开发耳熟能详的AMS,AMS里面会持有ATMS的引用,ATMS等于将AMS里面的Activity单独管理
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
mDataLoaderManagerService = mSystemServiceManager.startService(
DataLoaderManagerService.class);
mIncrementalServiceHandle = startIncrementalService();
//电量管理服务
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
mSystemServiceManager.startService(ThermalManagerService.class);
mActivityManagerService.initPowerManagement();
mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
mSystemServiceManager.startService(LightsService.class);
...
}
启动引导服务里面会启动很多系统服务,各个服务的启动方式类似,都是由SystemServiceManager去start,管理声明周期,以Atms为例子,实际启动的是ActivityTaskManagerService的内部类Lifecycle,这个类是SystemService的子类
#SystemServer->启动引导服务
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
#ActivityTaskManagerService
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;
public Lifecycle(Context context) {
super(context);
mService = new ActivityTaskManagerService(context);
}
@Override
public void onStart() {
//从上面的ActivityTaskManagerService类的分析中,会start对应的系统服务,最终就会回调到对应的onstart()方法中
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
mService.start();
}
@Override
public void onUnlockUser(int userId) {
synchronized (mService.getGlobalLock()) {
mService.mStackSupervisor.onUserUnlocked(userId);
}
}
@Override
public void onCleanupUser(int userId) {
synchronized (mService.getGlobalLock()) {
mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
}
}
public ActivityTaskManagerService getService() {
return mService;
}
}
创建完后,会回调LifeCycle中的onStart方法,会执行mService的start()方法,启动后并加入到systemservicemanager中
4 startCoreServices 启动核心服务
private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
mSystemServiceManager.startService(SystemConfigService.class);
mSystemServiceManager.startService(BatteryService.class);
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
mSystemServiceManager.startService(CachedDeviceStateService.class);
mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);
mSystemServiceManager.startService(BugreportManagerService.class);
mSystemServiceManager.startService(GpuService.class);
}
5 startOtherServices 启动其他服务 WMS等
启动其他服务中的其他系统服务上面的类似,在启动服务后,会执行AMS的systemReady方法,然后在里面去执行系统UI的启动
mActivityManagerService.systemReady(() -> { //启动launcher
try {
startSystemUi(context, windowManagerF); //启动系统 systemUI
} catch (Throwable e) {
}
//系统服务的启动状态会通过startBootPhase方法去设置
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY);
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_SYSTEM_SERVICES_READY);
}
启动完其他服务后,会在系统准备好的时候启动系统ui,并且会通过startBootPhase进行状态设置,启动系统ui就是去运行launcher3桌面应用,我们平时看到的操作系统界面就是一个系统提供的普通应用层app
总结
到这个阶段,已经启动完了systemserver进程,启动了用来管理系统服务的systemservciemanager进程,也启动了系统运行需要的各种系统服务,在系统服务启动好后会去执行启动系统UI界面,后续会分析部分系统服务的启动和launcher应用启动的流程










网友评论