目标:
1. system_server进程的创建;
2. AMS的创建以及核心服务的注册;
3. App进程何时创建;
4. App进程的Binder线程何时创建;
5. App线程何时创建;
6. Application.attachBaseContext()方法为什么不会ANR;
围绕这几个问题分几篇笔记进行分析;
这篇笔记主要包括以下几个点
1. system_server进程的创建;
2. binder线程的创建;
3. SSM的创建;
4. PMS的创建;
5. AMS的创建;
6. 通过SM进行服务的注册;
一、参考文章:
1. Android系统开篇;
2. Android系统启动-zygote篇;
3. Android系统启动-SystemServer上篇;
4. Android系统启动-SystemServer下篇;
5. Binder系列3—启动ServiceManager;
6. 理解Android进程创建流程;
二、相关源码地址:
- 1、https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/cmds/app_process/app_main.cpp
- 2、https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/core/jni/AndroidRuntime.cpp
- 3、https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
- 4、https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/native/libs/binder/ProcessState.cpp
三、Android系统启动流程 :
序号 | 进程启动 | 概述 |
---|---|---|
1 | init进程 | Linux系统中用户空间的第一个进程 |
2 | Zygote进程 | 所有App进程的父进程 |
3 | system_server进程 | 系统各大服务的载体 |
4 | ServiceManager进程 | Binder服务的大管家, 守护进程循环运行在binder_loop |
5 | APP进程 | 通过Process.start启动APP进程 |
四、system_server进程
4.1 ZygoteInit.main((Zygote进程))
public static void main(String argv[]) {
try {
boolean startSystemServer = false;
String socketName = "zygote";
String abiList = null;
for (int i = 1; i < argv.length; i++) {
if ("start-system-server".equals(argv[i])) {
startSystemServer = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
abiList = argv[i].substring(ABI_LIST_ARG.length());
} else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
socketName = argv[i].substring(SOCKET_NAME_ARG.length());
}
}
// 为Zygote注册socket, 为了后续system_server进程通过socket与zygote进程进行通信;
registerZygoteSocket(socketName);
// 进行资源的预加载, 在谈jvm与dvm的区别时, 提到的一些概念涉及到这里, Zygote进程创建时
// 会进行部分资源的预加载, 然后在fork创建子进程时, 直接拷贝这些资源;
preload();
if (startSystemServer) {
// 这里进行system_server进程的创建, 传入socketName, 方便后续system_server进程与
// zygote进程进行通信;
startSystemServer(abiList, socketName);
}
// 进程创建完成以后, zygote进程便会进入休眠状态, 利用io多路复用机制监听文件描述符;
runSelectLoop(abiList);
} catch (MethodAndArgsCaller caller) {
// 在创建system_server和app进程时, 都会通过抛MethodAndArgsCaller来触发这里caller.run的执行;
caller.run();
}
}
4.2 ZygoteInit.startSystemServer(Zygote进程)
private static boolean startSystemServer(String abiList, String socketName) throws MethodAndArgsCaller {
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
// 知道这里是fork方式以Zygote进程为父进程创建的system_server子进程即可;
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
if (pid == 0) {
// system_server进程创建完成以后, 开始处理system_server进程的相关逻辑;
handleSystemServerProcess(parsedArgs);
}
return true;
}
4.3 ZygoteInit.handleSystemServerProcess(system_server进程)
private static void handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs)
throws ZygoteInit.MethodAndArgsCaller {
if (parsedArgs.invokeWith != null) {
...
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
// 注意这里初始化了PathClassLoader, 后续App进程创建时也需要注意;
cl = new PathClassLoader(systemServerClasspath, ClassLoader.getSystemClassLoader());
Thread.currentThread().setContextClassLoader(cl);
}
RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
}
4.4 RuntimeInit.zygoteInit
private static final native void nativeZygoteInit();
public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
...
// 进行常规初始化操作, 这里暂时不进行任何分析;
commonInit();
// 这里会触发Binder线程的创建;
nativeZygoteInit();
// 到这里已经完成了system_server进程的创建, system_server对应的Binder线程的创建;
applicationInit(targetSdkVersion, argv, classLoader);
}
4.5 AndroidRuntime.com_android_internal_os_RuntimeInit_nativeZygoteInit
static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
// 触发app_main.onZygoteInit()方法的执行;
gCurRuntime->onZygoteInit();
}
4.6 app_main.onZygoteInit
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
// 知道这里是创建Binder线程即可, 至于线程创建细节, 感觉没必要知道;
// 内部就是调用了new PoolThread().start()操作;
proc->startThreadPool();
}
4.7 RuntimeInit.applicationInit
private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
final Arguments args;
args = new Arguments(argv);
// 通过对ZygoteInit.startSystemServer()的分析可知, 这里会触发SystemServer.main的执行;
invokeStaticMain(args.startClass, args.startArgs, classLoader);
}
4.8 SystemServer.main
public static void main(String[] args) {
new SystemServer().run();
}
4.9 SystemServer.run
private void run() {
Looper.prepareMainLooper();
// Initialize native services.
System.loadLibrary("android_servers");
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
createSystemContext();
// 初始化SSM
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Start services.
startBootstrapServices();
startCoreServices();
startOtherServices();
// Loop forever.
Looper.loop();
}
4.10 SystemServer.startBootstrapServices
private void startBootstrapServices() {
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
// 创建AMS, AMS在system_server进程中创建的证据;
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
// 创建PMS, PMS也是在system_server进程中创建的;
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mPackageManager = mSystemContext.getPackageManager();
// 这里的操作是非常关键的, 后期Activity启动流程离不开这里的操作;
mActivityManagerService.setSystemProcess();
}
4.11 ActivityManagerService.setSystemProcess
public void setSystemProcess() {
// Context.ACTIVITY_SERVICE = "activity";
// ProcessStats.SERVICE_NAME = "procstats";
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this));
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this));
}
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo("android", STOCK_PM_FLAGS);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
synchronized (this) {
ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
app.persistent = true;
app.pid = MY_PID;
app.maxAdj = ProcessList.SYSTEM_ADJ;
app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
synchronized (mPidsSelfLocked) {
mPidsSelfLocked.put(app.pid, app);
}
updateLruProcessLocked(app, false, null);
updateOomAdjLocked();
}
}
4.12 ServiceManager.addService
public static void addService(String name, IBinder service) {
// getIServiceManager()通过SMN返回SMP, 注意这里的写法, 后续启动Activity时, 也是类似这种写法
// AMN触发AMP;
getIServiceManager().addService(name, service, false);
}
private static IServiceManager getIServiceManager() {
if (sServiceManager != null) {
return sServiceManager;
}
// sServiceManager指向的是SMP, 再次记住, 这里还是system_server进程;
// 这里只需要记住BinderInternal.getContextObject()返回的是BinderProxy;
sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
return sServiceManager;
}
4.13 SMP.addService(这里通过添加服务)
// 这里有几个点需要注意一下, service指向的是ActivityManagerService, 最终通过BinderProxy, 将数据
// 以及AMS传给Native层;
public void addService(String name, IBinder service, boolean allowIsolated) {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IServiceManager.descriptor);
data.writeString(name);
data.writeStrongBinder(service);
data.writeInt(allowIsolated ? 1 : 0);
// mRemote指向的是BinderProxy;
mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
reply.recycle();
data.recycle();
}