android启动之SystemServer启动
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准备就绪
android启动之SystemServer启动的更多相关文章
- Android服务之PackageManagerService启动源码分析
了解了Android系统的启动过程的读者应该知道,Android的所有Java服务都是通过SystemServer进程启动的,并且驻留在SystemServer进程中.SystemServer进程在启 ...
- Android应用程序进程启动过程(前篇)
在此前我讲过Android系统的启动流程,系统启动后,我们就比较关心应用程序是如何启动的,这一篇我们来一起学习Android7.0 应用程序进程启动过程,需要注意的是“应用程序进程启动过程”,而不是应 ...
- Android5 Zygote 与 SystemServer 启动流程分析
Android5 Zygote 与 SystemServer 启动流程分析 Android5 Zygote 与 SystemServer 启动流程分析 前言 zygote 进程 解析 zygoterc ...
- 如何在android studio 1.0 启动时设置代理【解决WARN - ateSettings.impl.UpdateChecker - Connection failed.】
今天第一次用android studio,下了个比较新的1.0.1 linux版本,结果启动时老是出现以下错误: [ 6987] WARN - ateSettings.impl.UpdateCheck ...
- Android开发之---Activity启动模式
在Android开发中,启动一个新的activity我们可以使用startActivity或startActivityForResult,Android系统使用栈的方式来管理一个APP的页面显示与保存 ...
- Android中Activity的启动模式
简介 Android中的活动启动方式分为4种:standard, singleTop, singleTask, singleInstance.可以在AndroidManifest.xml中通过给< ...
- Android service介绍和启动方式
1.Android service的作用: service通常是用来处理一些耗时操作,或后台执行不提供用户交互界面的操作,例如:下载.播放音乐. 2.Android service的生命周期: ser ...
- 【Android】应用程序启动过程源码分析
在Android系统中,应用程序是由Activity组成的,因此,应用程序的启动过程实际上就是应用程序中的默认Activity的启动过程,本文将详细分析应用程序框架层的源代码,了解Android应用程 ...
- init进程 && 解析Android启动脚本init.rc && 修改它使不启动android && init.rc中启动一个sh文件
Android启动后,系统执行的第一个进程是一个名称为init 的可执行程序.提供了以下的功能:设备管理.解析启动脚本.执行基本的功能.启动各种服务.代码的路径:system/core/init,编译 ...
随机推荐
- Producer Flow Control 和 vmQueueCursor
ActiveMQ可以开启或关闭生产者流量控制Producer Flow Control ,基本原理是producer 发送一条消息会收到broker返回的ack响应,当磁盘或内存快满的时候broker ...
- C++学习笔记--从虚函数说开去
虚函数与纯虚函数: 虚函数:在某基类中声明为virtual并在一个或多个派生类中被重新定义的成员函数,virtual 函数返回类型 函数名(参数表){函数体;} ,实现多态性,通过指向派生类的基类 ...
- Java的BIO,NIO,AIO
Java中的IO操作可谓常见.在Java的IO体系中,常有些名词容易让人困惑不解.为此,先通俗地介绍下这些名词. 1 什么是同步? 2 什么是异步? 3 什么是阻塞? 4 什么是非阻塞? 5 什么是同 ...
- PHP中的魔术方法和关键字
PHP中的魔术方法总结 :__construct, __destruct , __call, __callStatic,__get, __set, __isset, __unset , __sleep ...
- 完全禁用Wordpress的升级功能
wordpress自己带有一个自动升级的功能,也就是说,如果wp检测到官方已经有新的升级可用的话他就会自己升级上去.这可能对于某些场合是个不错的功能,但是对于一些已经对系统大量魔改或者对插件稳定性不抱 ...
- WMI技术介绍和应用——WMI概述
https://blog.csdn.net/breaksoftware/article/details/8424317
- MP3 Music Library in Tornado
Web2.0的lab3,使用tornado实现,自己改了改UI 效果 选中播放列表后的效果 原来的图标长得太丑了,有空找些好看点的加进去……以后继续完成extra feature,当复习python了 ...
- Java学习(if wihle switch for语句)
一.if语句 定义:if语句是指如果满足某种条件,就进行某种处理. 语句: if (条件语句){ 执行语句; …… } 上述格式中,判断条件是一个布尔值,当判断条件为true时,{}中的执行语句才会执 ...
- 什么是泛型 转载自http://www.blogjava.net/Jack2007/archive/2008/05/05/198566.html
我们在编写程序时,经常遇到两个模块的功能非常相似,只是一个是处理int数据,另一个是处理string数据,或者其他自定义的数据类型,但我们没有办法,只能分别写多个方法处理每个数据类型,因为方法的参数类 ...
- ref:Adding AFL Bloom Filter to Domato for Fun
ref:https://www.sigpwn.io/blog/2018/5/13/adding-afl-bloom-filter-to-domato-for-fun Adding AFL Bloom ...