目標:
1. system_server進程的創(chuàng)建;
2. AMS的創(chuàng)建以及核心服務(wù)的注冊;
3. App進程何時創(chuàng)建;
4. App進程的Binder線程何時創(chuàng)建;
5. App線程何時創(chuàng)建;
6. Application.attachBaseContext()方法為什么不會ANR;
圍繞這幾個問題分幾篇筆記進行分析;
這篇筆記主要包括以下幾個點
1. system_server進程的創(chuàng)建;
2. binder線程的創(chuàng)建;
3. SSM的創(chuàng)建;
4. PMS的創(chuàng)建;
5. AMS的創(chuàng)建;
6. 通過SM進行服務(wù)的注冊;
一、參考文章:
1. Android系統(tǒng)開篇;
2. Android系統(tǒng)啟動-zygote篇;
3. Android系統(tǒng)啟動-SystemServer上篇;
4. Android系統(tǒng)啟動-SystemServer下篇;
5. Binder系列3—啟動ServiceManager;
6. 理解Android進程創(chuàng)建流程;
二、相關(guān)源碼地址:
- 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系統(tǒng)啟動流程 :
進程啟動流程圖
android系統(tǒng)啟動流程圖
序號 | 進程啟動 | 概述 |
---|---|---|
1 | init進程 | Linux系統(tǒng)中用戶空間的第一個進程 |
2 | Zygote進程 | 所有App進程的父進程 |
3 | system_server進程 | 系統(tǒng)各大服務(wù)的載體 |
4 | ServiceManager進程 | Binder服務(wù)的大管家, 守護進程循環(huán)運行在binder_loop |
5 | APP進程 | 通過Process.start啟動APP進程 |
system_server進程創(chuàng)建流程圖
四、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, 為了后續(xù)system_server進程通過socket與zygote進程進行通信;
registerZygoteSocket(socketName);
// 進行資源的預(yù)加載, 在談jvm與dvm的區(qū)別時, 提到的一些概念涉及到這里, Zygote進程創(chuàng)建時
// 會進行部分資源的預(yù)加載, 然后在fork創(chuàng)建子進程時, 直接拷貝這些資源;
preload();
if (startSystemServer) {
// 這里進行system_server進程的創(chuàng)建, 傳入socketName, 方便后續(xù)system_server進程與
// zygote進程進行通信;
startSystemServer(abiList, socketName);
}
// 進程創(chuàng)建完成以后, zygote進程便會進入休眠狀態(tài), 利用io多路復用機制監(jiān)聽文件描述符;
runSelectLoop(abiList);
} catch (MethodAndArgsCaller caller) {
// 在創(chuàng)建system_server和app進程時, 都會通過拋MethodAndArgsCaller來觸發(fā)這里caller.run的執(zhí)行;
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進程為父進程創(chuàng)建的system_server子進程即可;
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
if (pid == 0) {
// system_server進程創(chuàng)建完成以后, 開始處理system_server進程的相關(guān)邏輯;
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, 后續(xù)App進程創(chuàng)建時也需要注意;
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 {
...
// 進行常規(guī)初始化操作, 這里暫時不進行任何分析;
commonInit();
// 這里會觸發(fā)Binder線程的創(chuàng)建;
nativeZygoteInit();
// 到這里已經(jīng)完成了system_server進程的創(chuàng)建, system_server對應(yīng)的Binder線程的創(chuàng)建;
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)
{
// 觸發(fā)app_main.onZygoteInit()方法的執(zhí)行;
gCurRuntime->onZygoteInit();
}
4.6 app_main.onZygoteInit
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
// 知道這里是創(chuàng)建Binder線程即可, 至于線程創(chuàng)建細節(jié), 感覺沒必要知道;
// 內(nèi)部就是調(diào)用了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()的分析可知, 這里會觸發(fā)SystemServer.main的執(zhí)行;
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();
// 創(chuàng)建AMS, AMS在system_server進程中創(chuàng)建的證據(jù);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
// 創(chuàng)建PMS, PMS也是在system_server進程中創(chuàng)建的;
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mPackageManager = mSystemContext.getPackageManager();
// 這里的操作是非常關(guān)鍵的, 后期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, 注意這里的寫法, 后續(xù)啟動Activity時, 也是類似這種寫法
// AMN觸發(fā)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(這里通過添加服務(wù))
// 這里有幾個點需要注意一下, service指向的是ActivityManagerService, 最終通過BinderProxy, 將數(shù)據(jù)
// 以及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();
}