相关源码路径
/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
/frameworks/base/core/services/java/com/android/server/SystemServer.java
/frameworks/base/core/java/com/android/internal/os/Zygote.java
/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
/frameworks/base/cmds/app_process/App_main.cpp (内含AppRuntime类)
/frameworks/base/core/jni/AndroidRuntime.cpp
frameworks/base/core/java/android/app/ActivityThread.java
frameworks/base/core/java/android/app/LoadedApk.java
frameworks/base/core/java/android/app/ContextImpl.java
frameworks/base/core/java/com/android/server/LocalServices.java
frameworks/base/services/java/com/android/server/SystemServer.java
frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
frameworks/base/services/core/java/com/android/server/ServiceThread.java
frameworks/base/services/core/java/com/android/server/pm/Installer.java
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
/**
* Prepare the arguments and fork for the system server process.
*/
private static boolean startSystemServer(String abiList, String socketName)
throws MethodAndArgsCaller, RuntimeException {
long capabilities = posixCapabilitiesAsBits(
OsConstants.CAP_BLOCK_SUSPEND,
OsConstants.CAP_KILL,
OsConstants.CAP_NET_ADMIN,
OsConstants.CAP_NET_BIND_SERVICE,
OsConstants.CAP_NET_BROADCAST,
OsConstants.CAP_NET_RAW,
OsConstants.CAP_SYS_MODULE,
OsConstants.CAP_SYS_NICE,
OsConstants.CAP_SYS_RESOURCE,
OsConstants.CAP_SYS_TIME,
OsConstants.CAP_SYS_TTY_CONFIG
);
/* 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,1032,3001,3002,3003,3006,3007",
"--capabilities=" + capabilities + "," + capabilities,
"--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) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
handleSystemServerProcess(parsedArgs);
}
return true;
}
startSystemServer()函数的关键代码有三处。
(2)调用forkSystemServer()从当前的zygote进程孵化出新的进程。该函数是一个native函数,其作用与folkAndSpecilize()相似;
(3)第三处,新进程启动后。在handleSystemServerProcess()函数中主要完成两件事情,第一是关闭Socket服务端,第二是抛出异常MethodAndArgsCaller,通过caller.run()启动com.android.server.SystemServer的main 方法。调用类如下:
startSystemServer
Zygote.forkSystemServer
handleSystemServerProcess
closeServerSocket
RuntimeInit.zygoteInit
applicationInit
invokeStaticMain
throw new ZygoteInit.MethodAndArgsCaller
一、启动流程
startSystemServer()函数是system_server启动流程的起点,启动流程图如下:
上图前4步骤(即颜色为紫色的流程)运行在是Zygote进程,从第5步(即颜色为蓝色的流程)ZygoteInit.handleSystemServerProcess开始是运行在新创建的system_server,这是fork机制实现的(fork会返回2次)。
二、SystemServer.main()
调用栈:
SystemServer.main
SystemServer.run
createSystemContext
ActivityThread.systemMain
ActivityThread.attach
LoadedApk.makeApplication
ActivityThread.getSystemContext
ContextImpl.createSystemContext
startBootstrapServices();
startCoreServices();
startOtherServices();
Looper.loop();
流程图:
源码:
public static void main(String[] args) {
new SystemServer().run();
}
main 函数创建一个 SystemServer 对象,调用其 run() 方法。
private void run() {
// 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.
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
} // 检测时间设置
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());
// In case the runtime switched since last boot (such as when
// the old runtime was removed in an OTA), set the system
// property so that it is in sync. We can't do this in
// libnativehelper's JniInvocation::Init code where we already
// had to fallback to a different runtime because it is
// running as root and we need to be the system user to set
// the property. http://b/11463182
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// Enable the sampling profiler.
if (SamplingProfilerIntegration.isEnabled()) {
SamplingProfilerIntegration.start();
mProfilerSnapshotTimer = new Timer();
mProfilerSnapshotTimer.schedule(new TimerTask() {
@Override
public void run() {
SamplingProfilerIntegration.writeSnapshot("system_server", null);
}
}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
} // 启动性能分析采样
// Mmmmmm... more memory!
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);
// Some devices rely on runtime fingerprint generation, so make sure
// we've defined it before booting further.
Build.ensureFingerprintProperty();
// Within the system server, it is an error to access Environment paths without
// explicitly specifying a user.
Environment.setUserRequired(true);
// Ensure binder calls into the system always run at foreground priority.
BinderInternal.disableBackgroundScheduling(true);
// Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper(); // 准备主线程循环
// Initialize native services.
System.loadLibrary("android_servers");
nativeInit();
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
createSystemContext();
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Start services. // 启动服务
try {
startBootstrapServices();
startCoreServices();
startOtherServices();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
}
// For debug builds, log event loop stalls to dropbox for analysis.
if (StrictMode.conditionallyEnableDebugLogging()) {
Slog.i(TAG, "Enabled StrictMode for system server main thread.");
}
// Loop forever.
Looper.loop(); // 启动线程循环,等待消息处理
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在这个 run 方法中,主要完成三件事情,创建 system context 和 system service manager,启动一些系统服务,进入主线程消息循环。
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}
ActivityThread.systemMain
ActivityThread.attach
ActivityThread.getSystemContext
ActivityThread.attach :主要工作是创建应用上下文ContextImpl,创建Application以及调用其onCreate()方法,设置DropBox以及ComponentCallbacks2回调方法。
public static ActivityThread systemMain() {
// The system process on low-memory devices do not get to use hardware
// accelerated drawing, since this can add too much overhead to the
// process.
if (!ActivityManager.isHighEndGfx()) {
HardwareRenderer.disable(true);
} else {
HardwareRenderer.enableForegroundTrimming();
}
ActivityThread thread = new ActivityThread();
thread.attach(true);
return thread;
}
通过ActivityManager.isHighEndGfx()判断是否运行在大内存的设备中:假如是,则开启硬件加速;否则关闭。
创建一个ActivityThread,并调用其attath方法。
private void attach(boolean system) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
......
......
// 省略部分代码
} else {
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
// add dropbox logging to libcore
DropBox.setReporter(new DropBoxReporter());
ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
@Override
public void onConfigurationChanged(Configuration newConfig) {
synchronized (mResourcesManager) {
// We need to apply this change to the resources
// immediately, because upon returning the view
// hierarchy will be informed about it.
if (mResourcesManager.applyConfigurationToResourcesLocked(newConfig, null)) {
// This actually changed the resources! Tell
// everyone about it.
if (mPendingConfiguration == null ||
mPendingConfiguration.isOtherSeqNewer(newConfig)) {
mPendingConfiguration = newConfig;
sendMessage(H.CONFIGURATION_CHANGED, newConfig);
}
}
}
}
@Override
public void onLowMemory() {
}
@Override
public void onTrimMemory(int level) {
}
});
}
Instrumentation:创建该类的实例,该类用于监控该应用与系统之间的交互,调用ContextImpl.createAppContext()创建一个ContextImpl,接着调用context.mPackageInfo.makeApplication(true, null)创建该应用的Application对象,并调用该Application的onCreate()方法:这里启动了一个包名为android的系统应用程序。
(2)startBootstrapServices()
private void startBootstrapServices() {
//阻塞等待与installd建立socket通道
Installer installer = mSystemServiceManager.startService(Installer.class);
//启动服务ActivityManagerService
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
//启动服务PowerManagerService
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
//初始化power management
mActivityManagerService.initPowerManagement();
//启动服务LightsService
mSystemServiceManager.startService(LightsService.class);
//启动服务DisplayManagerService
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
//在初始化package manager之前,需要默认的显示
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
//当设备正在加密时,仅运行核心
String cryptState = SystemProperties.get("vold.decrypt");
if (ENCRYPTING_STATE.equals(cryptState)) {
mOnlyCore = true;
} else if (ENCRYPTED_STATE.equals(cryptState)) {
mOnlyCore = true;
}
//启动服务PackageManagerService
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
//启动服务UserManagerService,新建目录/data/user/
ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());
AttributeCache.init(mSystemContext);
//设置AMS
mActivityManagerService.setSystemProcess();
//启动传感器服务
startSensorService();
}
【system_server中启动的服务介绍】
system_server进程中的服务启动方式有两种,分别是SystemServiceManager的startService()和ServiceManager的addService
1)startService例如:ServiceManager.addService(Context.WINDOW_SERVICE, wm);
3)system_server进程,从源码角度划分为引导服务、核心服务、其他服务3类。
引导服务(7个):ActivityManagerService、PowerManagerService、LightsService、DisplayManagerService、PackageManagerService、UserManagerService、SensorService;
核心服务(3个):BatteryService、UsageStatsService、WebViewUpdateService;
其他服务(70个+):AlarmManagerService、VibratorService等。
(3)startCoreServices()
private void startCoreServices() {
//启动服务BatteryService,用于统计电池电量,需要LightService.
mSystemServiceManager.startService(BatteryService.class);
//启动服务UsageStatsService,用于统计应用使用情况
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();
//启动服务WebViewUpdateService
mSystemServiceManager.startService(WebViewUpdateService.class);
}
(4)startOtherServices()
private void startOtherServices() {
...
SystemConfig.getInstance();
mContentResolver = context.getContentResolver(); // resolver
...
mActivityManagerService.installSystemProviders(); //provider
mSystemServiceManager.startService(AlarmManagerService.class); // alarm
// watchdog
watchdog.init(context, mActivityManagerService);
inputManager = new InputManagerService(context); // input
wm = WindowManagerService.main(...); // window
inputManager.start(); //启动input
mDisplayManagerService.windowManagerAndInputReady();
...
mSystemServiceManager.startService(MOUNT_SERVICE_CLASS); // mount
mPackageManagerService.performBootDexOpt(); // dexopt操作
ActivityManagerNative.getDefault().showBootMessage(...); //显示启动界面
...
statusBar = new StatusBarManagerService(context, wm); //statusBar
//dropbox
ServiceManager.addService(Context.DROPBOX_SERVICE,
new DropBoxManagerService(context, new File("/data/system/dropbox")));
mSystemServiceManager.startService(JobSchedulerService.class); //JobScheduler
lockSettings.systemReady(); //lockSettings
//phase480 和phase500
mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
...
// 准备好window, power, package, display服务
wm.systemReady();
mPowerManagerService.systemReady(...);
mPackageManagerService.systemReady();
mDisplayManagerService.systemReady(...);
mActivityManagerService.systemReady(new Runnable() {...});
}
其中AMS.systemReady()的大致过程如下:
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
public void systemReady(final Runnable goingCallback) {
... //update相关
mSystemReady = true;
//杀掉所有非persistent进程
removeProcessLocked(proc, true, false, "system update done");
mProcessesReady = true;
goingCallback.run();
addAppLocked(info, false, null); //启动所有的persistent进程
mBooting = true;
//启动home
startHomeActivityLocked(mCurrentUserId, "systemReady");
//恢复栈顶的Activity
mStackSupervisor.resumeTopActivitiesLocked();
}
}