当前位置: 首页 > news >正文

Android SystemServer进程解析

SystemServer进程在android系统中占了举足轻重的地位,系统的所有服务和SystemUI都是由它启动。

一、SystemServer进程主函数流程

1、主函数三部曲

//frameworks/base/services/java/com/android/server/SystemServer.java    /** * The main entry point from zygote. */public static void main(String[] args) {new SystemServer().run();}

SystemServer的入口函数同样是main,调用顺序先是构造函数,再是run,构造函数没有什么重点地方后文dump详细介绍,主要流程主要还是run方法。run里面哦流程其实还是遵循普遍的三部曲:初始化上下文->启动服务->进入loop循环

1)初始化上下文
//frameworks/base/services/java/com/android/server/SystemServer.java    private void run() {TimingsTraceAndSlog t = new TimingsTraceAndSlog();try {t.traceBegin("InitBeforeStartServices");//.....一些属性的初始化....// The system server should never make non-oneway callsBinder.setWarnOnBlocking(true);// The system server should always load safe labelsPackageItemInfo.forceSafeLabels();// Default to FULL within the system server.SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;// Deactivate SQLiteCompatibilityWalFlags until settings provider is initializedSQLiteCompatibilityWalFlags.init(null);// Here we go! Slog.i(TAG, "Entered the Android system server!");final long uptimeMillis = SystemClock.elapsedRealtime(); //记录开始启动的时间错,调试系统启动时间的时候需要关注// Mmmmmm... more memory!VMRuntime.getRuntime().clearGrowthLimit();// 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);// Within the system server, any incoming Bundles should be defused to avoid throwing BadParcelableException.BaseBundle.setShouldDefuse(true);// Within the system server, when parceling exceptions, include the stack traceParcel.setStackTraceParceling(true);// Ensure binder calls into the system always run at foreground priority.BinderInternal.disableBackgroundScheduling(true);// Increase the number of binder threads in system_serverBinderInternal.setMaxThreads(sMaxBinderThreads);// Prepare the main looper thread (this thread).              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);SystemServiceRegistry.sEnableServiceNotFoundWtf = true;// Initialize native services.System.loadLibrary("android_servers");// Allow heap / perf profiling.initZygoteChildHeapProfiling();// Check whether we failed to shut down last time we tried. This call may not return.performPendingShutdown();// Initialize the system context.createSystemContext();// Call per-process mainline module initialization.ActivityThread.initializeMainlineModules();} finally {t.traceEnd();  // InitBeforeStartServices}
2)启动系统所有服务
//frameworks/base/services/java/com/android/server/SystemServer.java    // Start services.try {t.traceBegin("StartServices");startBootstrapServices(t);   //启动BOOT服务(即没有这些服务系统无法运行)startCoreServices(t);        //启动核心服务startOtherServices(t);       //启动其他服务startApexServices(t);        //启动APEX服务,此服务必现要在前面的所有服务启动之后才能启动,为了防止OTA相关问题// Only update the timeout after starting all the services so that we use// the default timeout to start system server.updateWatchdogTimeout(t);} catch (Throwable ex) {Slog.e("System", "******************************************");Slog.e("System", "************ Failure starting system services", ex);throw ex;} finally {t.traceEnd(); // StartServices}/*** Starts system services defined in apexes.* <p>Apex services must be the last category of services to start. No other service must be* starting after this point. This is to prevent unnecessary stability issues when these apexes* are updated outside of OTA; and to avoid breaking dependencies from system into apexes.*/private void startApexServices(@NonNull TimingsTraceAndSlog t) {t.traceBegin("startApexServices");// TODO(b/192880996): get the list from "android" package, once the manifest entries are migrated to system manifest.List<ApexSystemServiceInfo> services = ApexManager.getInstance().getApexSystemServices();for (ApexSystemServiceInfo info : services) {String name = info.getName();String jarPath = info.getJarPath();t.traceBegin("starting " + name);if (TextUtils.isEmpty(jarPath)) {mSystemServiceManager.startService(name);} else {mSystemServiceManager.startServiceFromJar(name, jarPath);}t.traceEnd();}// make sure no other services are started after this pointmSystemServiceManager.sealStartedServices();t.traceEnd(); // startApexServices}

如上代码大体启动了四类服务:

  • startBootstrapServices:启动一些关键引导服务,这些服务耦合到一起
  • startCoreServices:启动一些关键引导服务,这些服务没有耦合到一起
  • startOtherServices:启动其他一些杂七杂八的服务
  • startApexServices:启动apex类的服务,其实就是mainline那些东西,详情参考请点击我
3)进入loop循环
//frameworks/base/services/java/com/android/server/SystemServer.javaStrictMode.initVmDefaults(null);if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {final long uptimeMillis = SystemClock.elapsedRealtime();final long maxUptimeMillis = 60 * 1000;if (uptimeMillis > maxUptimeMillis) {Slog.wtf(SYSTEM_SERVER_TIMING_TAG, "SystemServer init took too long. uptimeMillis=" + uptimeMillis);}}// Loop forever.Looper.loop();throw new RuntimeException("Main thread loop unexpectedly exited");

和之前讲的binder一样,基本上所有的进程最后都会进入loop进行循环,轮询主线程相关的handle消息和binder消息,如下日志堆栈,表示handle消息处理过程中发生异常:

2、顺序启动服务

二、SystemServer正常启动日志

1、SystemServerTiming日志封装

2、SystemServer启动阶段OnBootPhase

3、SystemServer无法找到服务

4、Slow operation

三、SystemServer dumpsys解读

1、SystemServer的dump

2、其他服务的dump

SystemServer:Runtime restart: falseStart count: 1Runtime start-up time: +8s0msRuntime start-elapsed time: +8s0msSystemServiceManager:Current phase: 1000Current user not set!1 target users: 0(full)172 started services:com.transsion.hubcore.server.TranBootstrapServiceManagerServicecom.android.server.security.FileIntegrityServicecom.android.server.pm.Installercom.android.server.os.DeviceIdentifiersPolicyServicecom.android.server.uri.UriGrantsManagerService.Lifecyclecom.android.server.powerstats.PowerStatsServicecom.android.server.permission.access.AccessCheckingServicecom.android.server.wm.ActivityTaskManagerService.Lifecyclecom.android.server.am.ActivityManagerService.Lifecycle......com.android.server.Watchdog:WatchdogTimeoutMillis=60000SystemServerInitThreadPool:has instance: falsenumber of threads: 8service: java.util.concurrent.ThreadPoolExecutor@7bf04fb[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 351]is shutdown: trueno pending tasksAdServices:mAdServicesModuleName: com.google.android.adservicesmAdServicesModuleVersion: 341131050mHandlerThread: Thread[AdServicesManagerServiceHandler,5,main]mAdServicesPackagesRolledBackFrom: {}mAdServicesPackagesRolledBackTo: {}ShellCmd enabled: falseUserInstanceManagermAdServicesBaseDir: /data/system/adservicesmConsentManagerMapLocked: {}mAppConsentManagerMapLocked: {}mRollbackHandlingManagerMapLocked: {}mBlockedTopicsManagerMapLocked={}TopicsDbHelperCURRENT_DATABASE_VERSION: 1mDbFile: /data/system/adservices_topics.dbmDbVersion: 1

相关文章:

  • 自媒体人应该收藏的32个渠道,流量变现,不上班也能月入过万!
  • 高精度计算
  • 蓝桥杯物联网竞赛_STM32L071_12_按键中断与串口中断
  • 【Unity】详细介绍
  • Windows10/11添加打印完整图文演示步骤
  • 设置应用软件开机自动启动
  • SpringBoot(拦截器+文件上传)
  • SpringBoot(RESTful,统一响应结构,输出日志,增删改查功能,分页功能,批量删除,常见bug)【详解】
  • (黑马出品_高级篇_01)SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式
  • Elasticsearch:调整近似 kNN 搜索
  • 微信小程序调用百度智能云API(菜品识别)
  • 【计算机网络】集线器
  • 鸿蒙Harmony应用开发—ArkTS声明式开发(基础手势:Search)
  • 前端开发者如何打造自己的生态以及ip
  • 哥斯拉流量webshell分析-->ASP/PHP
  • 9月CHINA-PUB-OPENDAY技术沙龙——IPHONE
  • LeetCode29.两数相除 JavaScript
  • Python代码面试必读 - Data Structures and Algorithms in Python
  • XForms - 更强大的Form
  • 基于Javascript, Springboot的管理系统报表查询页面代码设计
  • 码农张的Bug人生 - 初来乍到
  • 世界上最简单的无等待算法(getAndIncrement)
  • 用jQuery怎么做到前后端分离
  • 看到一个关于网页设计的文章分享过来!大家看看!
  • 你对linux中grep命令知道多少?
  • 阿里云服务器如何修改远程端口?
  • 阿里云重庆大学大数据训练营落地分享
  • 长三角G60科创走廊智能驾驶产业联盟揭牌成立,近80家企业助力智能驾驶行业发展 ...
  • ​Z时代时尚SUV新宠:起亚赛图斯值不值得年轻人买?
  • #NOIP 2014# day.2 T2 寻找道路
  • (9)YOLO-Pose:使用对象关键点相似性损失增强多人姿态估计的增强版YOLO
  • (PHP)设置修改 Apache 文件根目录 (Document Root)(转帖)
  • (ros//EnvironmentVariables)ros环境变量
  • (分布式缓存)Redis持久化
  • (附源码)springboot学生选课系统 毕业设计 612555
  • (三)c52学习之旅-点亮LED灯
  • (十五)使用Nexus创建Maven私服
  • (转) Android中ViewStub组件使用
  • (转) ns2/nam与nam实现相关的文件
  • (转载)Google Chrome调试JS
  • .net 程序发生了一个不可捕获的异常
  • .Net的DataSet直接与SQL2005交互
  • .NET中的十进制浮点类型,徐汇区网站设计
  • .php结尾的域名,【php】php正则截取url中域名后的内容
  • @Autowired多个相同类型bean装配问题
  • [ vulhub漏洞复现篇 ] Hadoop-yarn-RPC 未授权访问漏洞复现
  • [8-27]正则表达式、扩展表达式以及相关实战
  • [C#C++]类CLASS
  • [E链表] lc83. 删除排序链表中的重复元素(单链表+模拟)
  • [Google Guava] 1.1-使用和避免null
  • [HOW TO]如何在iPhone应用程序中发送邮件
  • [HTTP]HTTP协议的状态码
  • [JavaWeb玩耍日记]Maven的安装与使用
  • [leetcode 双指针]
  • [Linux] Ubuntu install Miniconda