標籤:android 源碼 系統架構
SystemServer是Android系統的核心,APK應用中能夠直接互動的大部分系統服務都在該進程中運行,常見的比如WindowManagerServer(Wms)、ActivityManagerSystemService(AmS)、 PackageManagerServer(PmS)等,這些系統服務都是以一個線程的方式存在於SystemServer進程中。startSystemServer
systemServer是通過zygote啟動的時候fork啟動的,我們先看回到ZygoteInit.java類中看一下SystemServer的啟動。在zygote啟動過程中,通過調用startSystemServer啟動systemServer:
private static boolean startSystemServer() throws MethodAndArgsCaller, RuntimeException { /* Hardcoded command line to start the system server */ String args[] = { "--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007", "--capabilities=130104352,130104352", "--runtime-init", "--nice-name=system_server",//最終的進程名 "com.android.server.SystemServer", }; ZygoteConnection.Arguments parsedArgs = null; int pid; try { parsedArgs = new ZygoteConnection.Arguments(args); ZygoteConnection.applyDebuggerSystemProperty(parsedArgs); ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs); /* Request to fork the system server process */ pid = Zygote.forkSystemServer( parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } /* For child process */ if (pid == 0) { handleSystemServerProcess(parsedArgs); } return true; }首先通過Zygote.forkSystemServer fork出一個子進程來,並傳入了一些參數來設定新進程的一些資訊,如uid、gid等,函數返回後,如果是子進程pid=0,進入handleSystemServerProcess函數,如下:
private static void handleSystemServerProcess( ZygoteConnection.Arguments parsedArgs) throws ZygoteInit.MethodAndArgsCaller { closeServerSocket(); // set umask to 0077 so new files and directories will default to owner-only permissions. Libcore.os.umask(S_IRWXG | S_IRWXO); //ps可以看到system 261 98 391508 49008 ffffffff 4005c880 S system_server,此處system_server就是那個parsedArgs.niceName if (parsedArgs.niceName != null) { Process.setArgV0(parsedArgs.niceName); } if (parsedArgs.invokeWith != null) { WrapperInit.execApplication(parsedArgs.invokeWith, parsedArgs.niceName, parsedArgs.targetSdkVersion, null, parsedArgs.remainingArgs); } else { /* * Pass the remaining arguments to SystemServer. */ RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs); } /* should never reach here 注意不應該運行到這裡*/ }在此函數中首先調用 closeServerSocket()關閉從父進程zygote複製來的socket服務,因為只要zygote去監聽處理socket請求就夠了。然後繼續執行,RuntimeInit.zygoteInit()會通過JNI調用app_main.cpp中的onZygoteInit,啟動線程池處理Binder事件 。最後通過invokeStaticMain()函數拋出異常MethodAndArgsCaller。
public static class MethodAndArgsCaller extends Exception implements Runnable { /** method to call */ private final Method mMethod; /** argument array */ private final String[] mArgs; public MethodAndArgsCaller(Method method, String[] args) { mMethod = method; mArgs = args; } public void run() { try { mMethod.invoke(null, new Object[] { mArgs }); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } throw new RuntimeException(ex); } } }這個類繼承自Exception,實現了Runnable。該異常被ZygoteInit.java類的main函數catch,並執行run()函數,通過反射啟動SystemServer的main函數。
下面是ZygoteInit.java類的main函數捕獲異常的代碼:
} catch (MethodAndArgsCaller caller) { caller.run();}
這樣我們就啟動了SystemServer.java的main函數了,源碼在 (base\services\java\com\android\server)。
SystemServer.java
讓我們來看看這個類中的部分代碼:
/** * This method is called from Zygote to initialize the system. This will cause the native * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back * up into init2() to start the Android services. */ native public static void init1(String[] args); public static void main(String[] args) { //首先檢查系統時間設定和SamplingProfiler if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) { // If a device‘s clock is before 1970 (before 0), a lot of // APIs crash dealing with negative numbers, notably // java.io.File#setLastModified, so instead we fake it and // hope that time from cell towers or NTP fixes it // shortly. Slog.w(TAG, "System clock is before 1970; setting to 1970."); SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME); } if (SamplingProfilerIntegration.isEnabled()) { SamplingProfilerIntegration.start(); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { SamplingProfilerIntegration.writeSnapshot("system_server", null); } }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL); } // Mmmmmm... more memory! dalvik.system.VMRuntime.getRuntime().clearGrowthLimit(); // The system server has to run all of the time, so it needs to be // as efficient as possible with its memory usage. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); //載入動態庫libandroid_servers.so System.loadLibrary("android_servers"); //init1()函數是一個native函數,通過JNI最終調用system_init.cpp中的system_init()函數,內部會進行一些與Dalvik虛擬機器相關的初始化工作。該函數執行完畢後,其內部會調用Java端的init2()函數,這就是為什麼Java源碼中沒有引用init2()的地方. init1(args); } //主要的系統服 務都是在init2()函數中完成的。 public static final void init2() { Slog.i(TAG, "Entered the Android system server!"); //該函數首先建立了一個ServerThread對象,該對象是一個線程,然後直接運行該線程,從ServerThread的run()方法內部開始真正啟動各種服務線程。 Thread thr = new ServerThread(); thr.setName("android.server.ServerThread"); thr.start(); }main()函數首先會執行init1()函數,init1()函數是一個native函數,通過JNI最終調用system_init.cpp中的system_init()函數:
extern "C" status_t system_init(){ ALOGI("Entered system_init()"); sp<ProcessState> proc(ProcessState::self()); sp<IServiceManager> sm = defaultServiceManager(); ALOGI("ServiceManager: %p\n", sm.get()); sp<GrimReaper> grim = new GrimReaper(); sm->asBinder()->linkToDeath(grim, grim.get(), 0); char propBuf[PROPERTY_VALUE_MAX]; property_get("system_init.startsurfaceflinger", propBuf, "1"); if (strcmp(propBuf, "1") == 0) { //啟動SurfaceFlinger SurfaceFlinger::instantiate(); } property_get("system_init.startsensorservice", propBuf, "1"); if (strcmp(propBuf, "1") == 0) { //啟動sensor service SensorService::instantiate(); } // And now start the Android runtime. We have to do this bit // of nastiness because the Android runtime initialization requires // some of the core system services to already be started. // All other servers should just start the Android runtime at // the beginning of their processes‘s main(), before calling // the init function. ALOGI("System server: starting Android runtime.\n"); AndroidRuntime* runtime = AndroidRuntime::getRuntime(); ALOGI("System server: starting Android services.\n"); JNIEnv* env = runtime->getJNIEnv(); if (env == NULL) { return UNKNOWN_ERROR; } //通過“com/android/server/SystemServer”找到SystemServer.java的類 jclass clazz = env->FindClass("com/android/server/SystemServer"); if (clazz == NULL) { return UNKNOWN_ERROR; } //找到SystemServer.java的類的init2方法 jmethodID methodId = env->GetStaticMethodID(clazz, "init2", "()V"); if (methodId == NULL) { return UNKNOWN_ERROR; } //運行init2()函數 env->CallStaticVoidMethod(clazz, methodId); ALOGI("System server: entering thread pool.\n"); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); ALOGI("System server: exiting thread pool.\n"); return NO_ERROR;}system_init()函數回調init2()函數,init2()函數啟動ServerThread線程來添加各種服務以及其他的一些初始化工作,ServerThread是一個內部類,大體代碼如下;
class ServerThread extends Thread { ... @Override public void run() { EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis()); Looper.prepareMainLooper(); ... String factoryTestStr = SystemProperties.get("ro.factorytest"); int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF : Integer.parseInt(factoryTestStr); final boolean headless = "1".equals(SystemProperties.get("ro.config.headless", "0"));//定義變數,初始化服務,建立各種服務執行個體,如:電源、網路、Wifi、藍芽,USB等 ... Context context = null; ... // Create a shared handler thread for UI within the system server. // This thread is used by at least the following components: // - WindowManagerPolicy // - KeyguardViewManager // - DisplayManagerService HandlerThread uiHandlerThread = new HandlerThread("UI"); uiHandlerThread.start(); Handler uiHandler = new Handler(uiHandlerThread.getLooper()); uiHandler.post(new Runnable() { @Override public void run() { //Looper.myLooper().setMessageLogging(new LogPrinter( // Log.VERBOSE, "WindowManagerPolicy", Log.LOG_ID_SYSTEM)); android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false); // For debug builds, log event loop stalls to dropbox for analysis. if (StrictMode.conditionallyEnableDebugLogging()) { Slog.i(TAG, "Enabled StrictMode logging for UI Looper"); } } }); // Create a handler thread just for the window manager to enjoy. HandlerThread wmHandlerThread = new HandlerThread("WindowManager"); wmHandlerThread.start(); Handler wmHandler = new Handler(wmHandlerThread.getLooper()); wmHandler.post(new Runnable() { @Override public void run() { //Looper.myLooper().setMessageLogging(new LogPrinter( // android.util.Log.DEBUG, TAG, android.util.Log.LOG_ID_SYSTEM)); android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_DISPLAY); android.os.Process.setCanSelfBackground(false); // For debug builds, log event loop stalls to dropbox for analysis. if (StrictMode.conditionallyEnableDebugLogging()) { Slog.i(TAG, "Enabled StrictMode logging for WM Looper"); } } }); // Critical services... boolean onlyCore = false; try { // Wait for installd to finished starting up so that it has a chance to // create critical directories such as /data/user with the appropriate // permissions. We need this to complete before we initialize other services. Slog.i(TAG, "Waiting for installd to be ready."); installer = new Installer(); installer.ping(); //原來的EntropyService,熵混淆,增加隨機數的不可預測性 Slog.i(TAG, "Entropy Mixer"); ServiceManager.addService("entropy", new EntropyMixer());//用Context.getSystemService (String name) 才擷取到相應的服務 //向ServiceManager添加電源管理服務 Slog.i(TAG, "Power Manager"); power = new PowerManagerService(); ServiceManager.addService(Context.POWER_SERVICE, power); //啟動ActivityManagerService,注意返回了一個context Slog.i(TAG, "Activity Manager"); context = ActivityManagerService.main(factoryTest); //使用uiHandler、wmHandler Slog.i(TAG, "Display Manager"); display = new DisplayManagerService(context, wmHandler, uiHandler); ServiceManager.addService(Context.DISPLAY_SERVICE, display, true); ... //使用wmHandler Slog.i(TAG, "Input Manager"); inputManager = new InputManagerService(context, wmHandler); //使用uiHandler、wmHandler Slog.i(TAG, "Window Manager"); wm = WindowManagerService.main(context, power, display, inputManager, uiHandler, wmHandler, factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL, !firstBoot, onlyCore); ServiceManager.addService(Context.WINDOW_SERVICE, wm); ServiceManager.addService(Context.INPUT_SERVICE, inputManager); ActivityManagerService.setSystemProcess(); ... Slog.i(TAG, "System Content Providers"); ActivityManagerService.installSystemProviders();... // only initialize the power service after we have started the lights service, content providers and the battery service. power.init(context, lights, ActivityManagerService.self(), battery, BatteryStatsService.getService(), display); ... Slog.i(TAG, "Init Watchdog"); Watchdog.getInstance().init(context, battery, power, alarm, ActivityManagerService.self()); ... ActivityManagerService.self().setWindowManager(wm);... //使用wmHandler if (context.getResources().getBoolean( com.android.internal.R.bool.config_dreamsSupported)) { try { Slog.i(TAG, "Dreams Service"); // Dreams (interactive idle-time views, a/k/a screen savers) dreamy = new DreamManagerService(context, wmHandler); ServiceManager.addService(DreamService.DREAM_SERVICE, dreamy); } catch (Throwable e) { reportWtf("starting DreamManagerService", e); } } } catch (RuntimeException e) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting core service", e); }... try { Slog.i(TAG, "NetworkPolicy Service"); networkPolicy = new NetworkPolicyManagerService( context, ActivityManagerService.self(), power, networkStats, networkManagement); ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy); } catch (Throwable e) { reportWtf("starting NetworkPolicy Service", e); } ... } ... if (safeMode) { ActivityManagerService.self().showSafeModeOverlay(); } ...//系統服務初始化準備就緒,通知各個模組 ActivityManagerService.self().systemReady(new Runnable() { public void run() { Slog.i(TAG, "Making services ready"); if (!headless) startSystemUi(contextF); try { if (mountServiceF != null) mountServiceF.systemReady(); } catch (Throwable e) { reportWtf("making Mount Service ready", e); } ... try { if (telephonyRegistryF != null) telephonyRegistryF.systemReady(); } catch (Throwable e) { reportWtf("making TelephonyRegistry ready", e); } } }); // For debug builds, log event loop stalls to dropbox for analysis. if (StrictMode.conditionallyEnableDebugLogging()) { Slog.i(TAG, "Enabled StrictMode for system server main thread."); }//開始處理訊息的迴圈 Looper.loop(); Slog.d(TAG, "System ServerThread is exiting!"); } static final void startSystemUi(Context context) { Intent intent = new Intent(); intent.setComponent(new ComponentName("com.android.systemui", "com.android.systemui.SystemUIService")); //Slog.d(TAG, "Starting service: " + intent); context.startServiceAsUser(intent, UserHandle.OWNER); }}
到這裡系統ApplicationFramework層的XxxServiceManager準備就緒