1、Android10 源码编译相关问题
2、Android10 系统进程Zygote启动
3、Android10 系统进程SystemServer
4、Android10 launcher启动流程
5、Android10 系统发送开机广播时机
6、Android10 AppComponentFactory源码梳理
7、Android10 InputManagerService事件输入输出
8、Android10 InputManagerService本地实现
9、Android10 SystemUI系统手势导航
在上一节Android10 系统进程Zygote启动中主要是说了Zygote进程启动,在其中有说到Zygote进程会创建SystemServer进程,并执行其中的main()函数。SystemServer进程承载整个Android framework层的核心服务,这里就先来看看/frameworks/base/services/java/com/android/server/SystemServer.java的main()函数:
public static void main(String[] args) {
new SystemServer().run();
}
创建一个SystemServer对象,并执行它的run()方法:
private void run() {
try {
traceBeginAndSlog("InitBeforeStartServices");
// Record the process start information in sys props.
//在创建这个对象的时候会初始化如下属性,这里再把这些属性设置到系统中
SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));//设置开机的次数
SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START,
mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);
//如果一个设备的时钟是在1970年之前(0年之前),
//那么很多api 都会因为处理负数而崩溃,尤其是java.io.File#setLastModified
//我把把时间设置为1970
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
//如果时区不存在,设置时区为GMT
String timezoneProperty = SystemProperties.get("persist.sys.timezone");
if (timezoneProperty == null || timezoneProperty.isEmpty()) {
Slog.w(TAG, "Timezone not set; setting to GMT.");
SystemProperties.set("persist.sys.timezone", "GMT");
}
//变更虚拟机的库文件,对于Android 10.0默认采用的是libart.so
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// Mmmmmm... more memory!
//清除vm内存增长上限,由于启动过程需要较多的虚拟机内存空间
VMRuntime.getRuntime().clearGrowthLimit();
...
//系统服务器必须一直运行,所以它需要尽可能高效地使用内存
//设置内存的可能有效使用率为0.8
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
//一些设备依赖于运行时指纹生成,所以在进一步启动之前,请确保我们已经定义了它。
Build.ensureFingerprintProperty();
//访问环境变量前,需要明确地指定用户
//在system_server中,任何传入的包都应该被解除,以避免抛出BadParcelableException。
BaseBundle.setShouldDefuse(true);
//在system_server中,当打包异常时,信息需要包含堆栈跟踪
Parcel.setStackTraceParceling(true);
//确保当前系统进程的binder调用,总是运行在前台优先级(foreground priority)
BinderInternal.disableBackgroundScheduling(true);
//设置system_server中binder线程的最大数量,最大值为31
BinderInternal.setMaxThreads(sMaxBinderThreads);
//准备主线程lopper,即在当前线程运行
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
//加载android_servers.so库,初始化native service
System.loadLibrary("android_servers");
// Debug builds - allow heap profiling.
//如果是Debug版本,允许堆内存分析
if (Build.IS_DEBUGGABLE) {
initZygoteChildHeapProfiling();
}
//检测上次关机过程是否失败,这个调用可能不会返回
performPendingShutdown();
//初始化系统上下文
createSystemContext();
//创建系统服务管理--SystemServiceManager
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
//将mSystemServiceManager添加到本地服务的成员sLocalServiceObjects
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
//为可以并行化的init任务准备线程池
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}
// Start services.
//启动服务
try {
traceBeginAndSlog("StartServices");
startBootstrapServices(); // 启动引导服务
startCoreServices(); // 启动核心服务
startOtherServices(); // 启动其他服务
SystemServerInitThreadPool.shutdown(); //停止线程池
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
//为当前的虚拟机初始化VmPolicy
StrictMode.initVmDefaults(null);
...
// Loop forever.
//死循环执行
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这里主要是初始化一些系统变量、创建系统上下文、创建系统服务管理对象SystemServiceManager,最后才是去启动系统服务,这里启动系统服务又分为三类:引导服务、核心服务、其他服务,下面来进入里面去看看:
创建系统上下文:
private void createSystemContext() {
//创建systemserver进程的上下文信息
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
//设置主题
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
//获取systemui上下文信息,并设置主题
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
该过程会创建对象有ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application,这可以有个注意的地方,创建ActivityThread是通过它的systemMain()方法,而正常通过ActivityThread创建应用进程是通过它的main()方法。
创建系统服务管理对象SystemServiceManager:
SystemServiceManager这个对象主要作用是用于创建 已经管理系统服务,下面将这个类简化下:
public class SystemServiceManager {
private static final String TAG = "SystemServiceManager";
private final Context mContext;
// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
SystemServiceManager(Context context) {
mContext = context;
}
/*
* Loads and initializes a class from the given classLoader. Returns the class.
*/
@SuppressWarnings("unchecked")
private static Class<SystemService> loadClassFromLoader(String className,
ClassLoader classLoader) {
try {
return (Class<SystemService>) Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException("Failed to create service " + className
+ " from class loader " + classLoader.toString() + ": service class not "
+ "found, usually indicates that the caller should "
+ "have called PackageManager.hasSystemFeature() to check whether the "
+ "feature is available on this device before trying to start the "
+ "services that implement it. Also ensure that the correct path for the "
+ "classloader is supplied, if applicable.", ex);
}
}
/**
* Creates and starts a system service. The class must be a subclass of
* {@link com.android.server.SystemService}.
*
* @param serviceClass A Java class that implements the SystemService interface.
* @return The service instance, never null.
* @throws RuntimeException if the service fails to start.
*/
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
Slog.i(TAG, "Starting " + name);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
// Create the service.
if (!SystemService.class.isAssignableFrom(serviceClass)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.getName());
}
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service constructor threw an exception", ex);
}
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
}
这个对象里面有一个mServices集合,这个集合主要保存的就是系统服务,可以看到,所有的系统服务都需要继承com.android.server.SystemService,并且通过反射的方式去实例化系统服务对象,最后会调用系统服务的onStart()方法,关于实例化的系统服务对象,可以通过过滤SystemServiceManager来查看打印的系统服务日志。
启动系统服务:
启动系统服务会分为三类,主要是通过三个方法来依次启动:
startBootstrapServices(); // 启动引导服务
startCoreServices(); // 启动核心服务
startOtherServices(); // 启动其他服务
这里主要是来看下startBootStrapServices(),其他的两个实现方法差不多:
private void startBootstrapServices() {
traceBeginAndSlog("StartWatchdog");
//启动watchdog
//尽早启动watchdog,如果在早起启动时发生死锁,我们可以让system_server崩溃,从而进行详细分析
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
traceEnd();
...
//阻塞等待installd完成启动,以便有机会创建具有适当权限的关键目录,如/data/user。
//我们需要在初始化其他服务之前完成此任务。
traceBeginAndSlog("StartInstaller");
Installer installer = mSystemServiceManager.startService(Installer.class);
traceEnd();
...
//启动服务ActivityManagerService,并为其设置mSystemServiceManager和installer
traceBeginAndSlog("StartActivityManager");
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
traceEnd();
//启动服务PowerManagerService
//Power manager需要尽早启动,因为其他服务需要它。
//本机守护进程可能正在监视它的注册,
//因此它必须准备好立即处理传入的绑定器调用(包括能够验证这些调用的权限)。
traceBeginAndSlog("StartPowerManager");
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
traceEnd();
...
//初始化power management
traceBeginAndSlog("InitPowerManagement");
mActivityManagerService.initPowerManagement();
traceEnd();
//启动recovery system,以防需要重新启动
traceBeginAndSlog("StartRecoverySystemService");
mSystemServiceManager.startService(RecoverySystemService.class);
traceEnd();
...
//启动服务LightsService
//管理led和显示背光,所以我们需要它来打开显示
traceBeginAndSlog("StartLightsService");
mSystemServiceManager.startService(LightsService.class);
traceEnd();
...
//启动服务DisplayManagerService
//显示管理器需要在包管理器之前提供显示指标
traceBeginAndSlog("StartDisplayManager");
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
traceEnd();
//在初始化package manager之前,需要默认的显示.
traceBeginAndSlog("WaitForDisplay");
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
traceEnd();
//当设备正在加密时,仅运行核心
String cryptState = VoldProperties.decrypt().orElse("");
if (ENCRYPTING_STATE.equals(cryptState)) {
Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
mOnlyCore = true;
} else if (ENCRYPTED_STATE.equals(cryptState)) {
Slog.w(TAG, "Device encrypted - only parsing core apps");
mOnlyCore = true;
}
...
//启动服务PackageManagerService
traceBeginAndSlog("StartPackageManagerService");
try {
Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
...
//启动服务UserManagerService,新建目录/data/user/
traceBeginAndSlog("StartUserManagerService");
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
traceEnd();
// Set up the Application instance for the system process and get started.
//为系统进程设置应用程序实例并开始。
//设置AMS
traceBeginAndSlog("SetSystemProcess");
mActivityManagerService.setSystemProcess();
traceEnd();
//使用一个ActivityManager实例完成watchdog设置并监听重启,
//只有在ActivityManagerService作为一个系统进程正确启动后才能这样做
traceBeginAndSlog("InitWatchdog");
watchdog.init(mSystemContext, mActivityManagerService);
traceEnd();
//传感器服务需要访问包管理器服务、app ops服务和权限服务,
//因此我们在它们之后启动它。
//在单独的线程中启动传感器服务。在使用它之前应该检查完成情况。
mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(START_SENSOR_SERVICE);
startSensorService(); //启动传感器服务
traceLog.traceEnd();
}, START_SENSOR_SERVICE);
}
从这里可以看出,服务的创建基本都是通过SystemServiceManager的startService()进行创建的,PackageManagerService例外,它是直接调用它的main()方法。关于具体服务的创建,后面讲具体服务的时候说了。