失眠必读系列——System Server启动流程

456 阅读3分钟

启动System Server进程

参考【Android系统启动流程】中启动System Server部分,主要是经过一系列调用,返回一个Runnable,执行Runnable的run方法,run方法中通过反射执行System Server的main方法,启动完后开始初始化各项服务,大致过程如下


初始化各项服务

/frameworks/base/services/java/com/android/server/SystemServer.java

public static void main(String[] args) {
    new SystemServer().run();
}

精简代码如下:

private void run() {
    //设置时区
    timezoneProperty
    //设置区域和语言等
    SystemProperties
    ……
    //设置进程优先级为前台进程
    android.os.Process.setThreadPriority(
    android.os.Process.THREAD_PRIORITY_FOREGROUND);
    ……
    //当前线程作为主线程
    Looper.prepareMainLooper();
    …… 
    //创建System Context
    createSystemContext();
    ……
    //创建SystemServiceManager,管理所有系统服务
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    ……
    //启动引导服务
    startBootstrapServices();
    //启动核心服务
    startCoreServices();
    //启动其他服务
    startOtherServices();
    ……
    Looper.loop();
    loop循环
}
  • 设置各种参数
  • 创建System Context
  • 创建SystemServiceManager
  • 启动各项Service
  • 开启Looper循环,等待Client请求

startBootstrapServices

精简部分服务:

final Watchdog watchdog = Watchdog.getInstance();

watchdog.start();

看门狗(Linux内核中也有Watchdog,启动后设定一个定时器,如果在规定时间内没有对/dev/Watchdog进行写操作,则会导致系统重启,可以自行谷歌Linux看门狗)

final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";

SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);

读取系统配置

Installer installer = mSystemServiceManager.startService(Installer.class);

PMS依赖Installer服务,它是安装应用的真正执行者

ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();

mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);

mActivityManagerService.setSystemServiceManager(mSystemServiceManager);

mActivityManagerService.setInstaller(installer);

mWindowManagerGlobalLock = atm.getGlobalLock();

创建ATMS,AMS

mPowerManagerService =mSystemServiceManager.startService(PowerManagerService.class);

电源管理服务

mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

显示服务

try{
    Watchdog.getInstance().
    pauseWatchingCurrentThread("packagemanagermain");
    
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer,mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
} finally {
    Watchdog.getInstance().
    resumeWatchingCurrentThread("packagemanagermain");
}

创建PMS

mSensorServiceStart =
SystemServerInitThreadPool.get().submit(() -> {
    startSensorService();
}, START_SENSOR_SERVICE);

单独开启一个线程,启动传感器服务

总结:startBootstrapServices中启动了比较重要的AMS/ATMS、PMS、电源、显示等服务

startCoreServices

mSystemServiceManager.startService(BatteryService.class);

电量服务

mSystemServiceManager.startService(UsageStatsService.class);

mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));

应用统计服务(其余服务可自行查看)

startOtherServices

mSystemServiceManager.startService(TelecomLoaderService.class);

电信加载服务

//The AccountManager must come before theContentService
mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);

账号服务

mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);

内容服务

vibrator = new VibratorService(context);

ServiceManager.addService("vibrator", vibrator);

震动服务

mSystemServiceManager.startService(new AlarmManagerService(context));

闹钟服务

inputManager = new InputManagerService(context);

创建输入服务对象(稍后启动)

// WMS needs sensor service ready 
ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);

mSensorServiceStart = null;

wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);

启动WMS,启动前先准备传感器服务

inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());

inputManager.start();

关联WMS,启动输入服务

mSystemServiceManager.startService(BluetoothService.class);

启动蓝牙服务

非低级工厂模式下:
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {...}

statusBar = new StatusBarManagerService(context);

ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);

启动状态栏服务

networkManagement = NetworkManagementService.create(context);

ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);

ipSecService = IpSecService.create(context);

ServiceManager.addService(Context.IPSEC_SERVICE, ipSecService);

networkStats = NetworkStatsService.create(context, networkManagement);

ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);

networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,networkManagement);

ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);

mSystemServiceManager.startService(WIFI_SERVICE_CLASS);

网络相关服务

ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,new SystemUpdateManagerService(context));

系统更新服务

mSystemServiceManager.startService(NotificationManagerService.class);

通知服务

location = new LocationManagerService(context);              ServiceManager.addService(Context.LOCATION_SERVICE, location);

位置服务

mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);

墙纸服务

mSystemServiceManager.startService(AudioService.Lifecycle.class);

音频服务

mSystemServiceManager.startService(ADB_SERVICE_CLASS);

ADB服务

mSystemServiceManager.startService(USB_SERVICE_CLASS);

USB服务

mSystemServiceManager.startService(CameraServiceProxy.class);

相机服务

总结:
startOtherServices中启动了比较重要的WMS、IMS、网络、通知等服务

服务之间是存在依赖关系的,所以服务的启动划分了8个阶段:0-100-480-500-520-550-600-1000


SystemServiceManager(121次调用)

/frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

可以看到大部分服务是SystemServiceManager启动的

startService

public SystemService startService(String className)
public <T extends SystemService> T startService(Class<T> serviceClass)
public void startService(@NonNull final SystemService service)

反射获取class,实例化后,调用service.onStart();

startBootPhase

mSystemServiceManager.startBootPhase(100);
……
mSystemServiceManager.startBootPhase(1000);

public void startBootPhase(@NonNull TimingsTraceAndSlog t, int phase) {
    final int serviceLen = mServices.size();
    
    for (int i = 0; i < serviceLen; i++) {
        final SystemService service = mServices.get(i);
        service.onBootPhase(mCurrentPhase);
    }
    
    if (phase == SystemService.PHASE_BOOT_COMPLETED) {
        SystemServerInitThreadPool.shutdown();
    }
}

通知目前已经启动的SystemService,具体到哪个阶段了,直到1000时,表示所有服务启动完成,关闭SystemServerInitThreadPool线程池


ServiceManager(27次调用)

通过ServiceManager.addService注册服务,可以供其他地方调用 /frameworks/base/core/java/android/os/ServiceManager.java

//其中getIServiceManager()返回sServiceManager
//sServiceManager为ServiceManagerProxy
//其实是调用了ServiceManagerProxy的addService
getIServiceManager().addService(name, service, allowIsolated, dumpPriority);

//其中BinderInternal.getContextObject() 返回IBinder
//Binder.allowBlocking(IBinder)返回BinderProxy
sServiceManager = ServiceManagerNative
.asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));

/frameworks/base/core/java/android/os/ServiceManagerNative.java

static public IServiceManager asInterface(IBinder obj){
    ……
    return new ServiceManagerProxy(obj);
}
//其中mRemote为BinderProxy
class ServiceManagerProxy implements IServiceManager {
    ……
    public void addService(String name, IBinder service, boolean allowIsolated, int dumpPriority)throws RemoteException {
        ……
        mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
        ……
        }
    ……
}

/frameworks/base/core/java/android/os/BinderProxy.java

public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
    ……
    return transactNative(code, data, reply, flags);
    ……
}

public native boolean transactNative(int code, Parcel data, Parcel reply, int flags)
……

最后向/dev/binder中写入消息,在servicemanager进程中接收到了这个消息并处理这个请求

向SM中注册服务过程很复杂,这里只是大概流程,后续会有失眠必读系列来介绍服务注册过程


结尾:

失眠必读系列未完待续,有任何错误,虚心讨教,欢迎指正...


参考资料:
juejin.cn/post/705415…
juejin.cn/post/705854…