1. 概述:

1. Zygote进程是Android Java世界的开创者,所有的Java应用程序进程都由Zygote进程创建;

2. Zygote创建应用程序进程过程其实就是复制自身进程地址空间作为应用程序进程的地址空间,因此在Zygote进程中加载的类和资源都可以共享给所有由Zygote进程孵化的应用程序,应用程序进程只需加载自身私有资源就可以正常运行;

3. Zygote进程是所有Android Java应用程序进程的父进程,Zygote进程和普通应用程序进程之间的关系正是面向对象编程语言中的继承关系,应用程序进程继承Zygote进程的所有资源,Zygote进程在启动时加载所有应用程序进程运行所需的公共资源,即应用程序运行的共性资源;由于普通应用程序有自己的特性资源,因此普通应用程序在启动时,只需要加载自身特性资源就可以了。Linux进程间这种继承关系加快了普通应用程序启动的速度,也简化了应用程序进程的创建过程。既然所有Java应用程序进程都是由Zygote进程创建,那么Android系统是如何请求Zygote进程创建一个新的应用程序进程的呢?在之前,我们介绍了Zygote进程在启动过程中,会根据启动参数创建第一Java进程,它就是SystemServer进程,它是Android系统至关重要的进程,运行中Android系统的绝大部分服务;

4. 普通应用程序进程是无法直接请求Zygote进程孵化新进程的,所有的进程创建请求都是由SystemServer进程发出的。本文依据源码,详细分析SystemServer进程的启动过程。在Zygote进程进入循环监听Socket模式前,会根据Zygote启动参数来选择是否启动SystemServer进程,而Zygote进程的启动是在Android的启动脚本init.rc文件中配置的:

 

2. 从zygote到SystemServer(没看懂,预留)

看的不是很懂,大概知道是zygote会fork一个子进程去启动SystemServer,然后中途会加载各类资源,最后通过反射,跳转至SystemServer

i.mx6 Android5.1.1 Zygote这篇文章的第七章节可知,SystemServer是由zygote产生的

在frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

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 */
       //这里fork一个子进程
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;
}

3. SystemServer.java

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

上面各种调来调取,最后会首先调到SystemServer.java里的main方法

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

然后新建一个对象接着调用run方法

private void run() {
// 如果设置的时间比1970更早,就设置为1970
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()); //后面几个都是跟虚拟机相关的,设置一些参数属性之类的吧。
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.
     //加载动态库libandroid_servers.so,这个是重点!!!!注册了很多本地服务
System.loadLibrary("android_servers");
     //初始化本地服务(里面其实就是Sensor服务),见第4章
nativeInit(); //hj sensormanager libandroid_servers.so // 查看上次关机是否失败,该方法可能不会返回
performPendingShutdown(); // Initialize the system context.
//创建context对象,见第5章
createSystemContext();// Create the system service manager.
//创建SystemServiceManager,并把它加入的LocalServices当中(注意:这里不是加入到ServiceManager)
     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.");
} //循环.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

4. System.loadLibrary("android_servers")

在这里加载了非常多的本地服务,加载的是libandroid_servers.so,对应到的函数接口为onload.cpp;后面会有一个博客讲解相关技术

frameworks/base/services/core/jni/onload.cpp

extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -; if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
ALOGE("GetEnv failed!");
return result;
}
ALOG_ASSERT(env, "Could not retrieve the env!");
   //注册的本地服务,有了这些,就可以通过JNI去调用了
register_android_server_PowerManagerService(env);
register_android_server_SerialService(env);
register_android_server_InputApplicationHandle(env);
register_android_server_InputWindowHandle(env);
register_android_server_InputManager(env);
register_android_server_LightsService(env);
register_android_server_AlarmManagerService(env);
register_android_server_UsbDeviceManager(env);
register_android_server_UsbHostManager(env);
register_android_server_VibratorService(env);
register_android_server_SystemServer(env);
register_android_server_location_GpsLocationProvider(env);
register_android_server_location_FlpHardwareProvider(env);
register_android_server_connectivity_Vpn(env);
register_android_server_AssetAtlasService(env);
register_android_server_ConsumerIrService(env);
register_android_server_BatteryStatsService(env);
register_android_server_hdmi_HdmiCecController(env);
register_android_server_tv_TvInputHal(env);
register_android_server_PersistentDataBlockService(env);
register_android_server_fingerprint_FingerprintService(env);
register_android_server_Watchdog(env); return JNI_VERSION_1_4;
}

5. nativeInit

frameworks/base/services/core/jni/com_android_server_SystemServer.cpp

这是一个本地服务,搜索全局,可以查到,功能一句话说就是实例化SensorService,并把它添加进ServiceManager

static JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "nativeInit", "()V", (void*) android_server_SystemServer_nativeInit },
};

接着查看

static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {
char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsensorservice", propBuf, "");
if (strcmp(propBuf, "") == ) {
// Start the sensor service
SensorService::instantiate();
}
}

frameworks/native/include/binder/BinderService.h

static void instantiate() { publish(); }

在这个函数就不接着往下追了,下面的可以查看博客:SensorService那一篇,总之:在这里就是实例化了SensorService并将它添加进ServiceManager

static status_t publish(bool allowIsolated = false) {
     //得到ServiceManager的对象sm
sp<IServiceManager> sm(defaultServiceManager());
     //将SensorService添加进ServiceManager
return sm->addService(
String16(SERVICE::getServiceName()),
new SERVICE(), allowIsolated);
}

6. createSystemContext

createSystemContext的创建过程可以看看: Android vibrator服务(从APP到kernel driver完全解析)

private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}

7. SystemServiceManager(还没分析清楚)

8. startBootstrapServices(启动引导服务)

private void startBootstrapServices() {
     //启动Installer服务
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(); //启动DisplayManagerService
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class); // We need the default display before we can initialize the package manager.
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY); // Only run "core" apps if we're encrypting the device.
String cryptState = SystemProperties.get("vold.decrypt");
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;
} // Start the package manager.
Slog.i(TAG, "Package Manager");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager(); Slog.i(TAG, "User Service");
ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance()); // Initialize attribute cache used to cache resources from packages.
AttributeCache.init(mSystemContext); // Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();
}

9. startCoreServices(启动核心服务)

private void startCoreServices() {
// Manages LEDs and display backlight.
mSystemServiceManager.startService(LightsService.class); // Tracks the battery level. Requires LightService.
mSystemServiceManager.startService(BatteryService.class); // Tracks application usage stats.
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
// Update after UsageStatsService is available, needed before performBootDexOpt.
mPackageManagerService.getUsageStatsIfNoPackageUsageInfo(); // Tracks whether the updatable WebView is in a ready state and watches for update installs.
mSystemServiceManager.startService(WebViewUpdateService.class);
}

10. startOtherServices(启动其他服务)

基本上我们需要启动的其他大部分服务都在这里了

private void startOtherServices() {
final Context context = mSystemContext;
AccountManagerService accountManager = null;
ContentService contentService = null;
VibratorService vibrator = null;
。。。boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);
boolean disableMedia = SystemProperties.getBoolean("config.disable_media", false);
boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);
boolean disableTelephony = SystemProperties.getBoolean("config.disable_telephony", false);
boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);
boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);
boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);
boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);
boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime", false);
boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1"); try {
Slog.i(TAG, "Reading configuration...");
SystemConfig.getInstance(); Slog.i(TAG, "Scheduling Policy");
ServiceManager.addService("scheduling_policy", new SchedulingPolicyService()); mSystemServiceManager.startService(TelecomLoaderService.class); Slog.i(TAG, "Telephony Registry");
telephonyRegistry = new TelephonyRegistry(context);
ServiceManager.addService("telephony.registry", telephonyRegistry); Slog.i(TAG, "Entropy Mixer");
ServiceManager.addService("entropy", new EntropyMixer(context)); 。。。// These are needed to propagate to the runnable below.
final MountService mountServiceF = mountService;
final NetworkManagementService networkManagementF = networkManagement;
final NetworkStatsService networkStatsF = networkStats;
final NetworkPolicyManagerService networkPolicyF = networkPolicy;
final ConnectivityService connectivityF = connectivity;
final NetworkScoreService networkScoreF = networkScore;
final WallpaperManagerService wallpaperF = wallpaper;
final InputMethodManagerService immF = imm;
final LocationManagerService locationF = location;
final CountryDetectorService countryDetectorF = countryDetector;
final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
final TextServicesManagerService textServiceManagerServiceF = tsms;
final StatusBarManagerService statusBarF = statusBar;
final AssetAtlasService atlasF = atlas;
final InputManagerService inputManagerF = inputManager;
final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
final MediaRouterService mediaRouterF = mediaRouter;
final AudioService audioServiceF = audioService;
final MmsServiceBroker mmsServiceF = mmsService; // We now tell the activity manager it is okay to run third party
// code. It will call back into us once it has gotten to the state
// where third party code can really run (but before it has actually
// started launching the initial applications), for us to complete our
// initialization.
mActivityManagerService.systemReady(new Runnable() {
@Override
public void run() {
Slog.i(TAG, "Making services ready");
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY); try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
} 。。。
}
});
}

11. loop

public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
     //死循环
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
} // This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
} msg.target.dispatchMessage(msg); if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
} // Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
} msg.recycleUnchecked();
}
}

i.mx6 Android5.1.1 System server的更多相关文章

  1. i.mx6 Android5.1.1 初始化流程之框架

    Android启动过程分为以下几个步骤: 1.  Boot ROM:  上电后启动芯片固话代码. 2.  BootLoader:固话代码会根据启动模式启动bootloader,(一般为启动引脚的电平的 ...

  2. i.mx6 Android5.1.1 servicemanager本地服务

    接在之前的 i.mx6 Android5.1.1 初始化流程之init进程 i.mx6 Android5.1.1 初始化流程之init.rc解析 servicemanager是由init创建的本地服务 ...

  3. i.mx6 Android5.1.1 初始化流程之init进程(未完成)

    概述: 接在i.mx6 Android5.1.1 初始化流程之框架之后 参考资料:http://blog.csdn.net/mr_raptor/article/category/799879 相关源码 ...

  4. i.mx6 Android5.1.1 初始化流程之init.rc解析(未完成)

    接上一篇:i.mx6 Android5.1.1 初始化流程之init进程 参考资料:http://blog.csdn.net/mr_raptor/article/category/799879 这个博 ...

  5. 图解Android - Zygote, System Server 启动分析

    Init 是所有Linux程序的起点,而Zygote于Android,正如它的英文意思,是所有java程序的'孵化池'(玩过星际虫族的兄弟都晓得的).用ps 输出可以看到 >adb shell ...

  6. i.mx6 Android5.1.1 Zygote

    0. 总结: 0.1 相关源码目录: framework/base/cmds/app_process/app_main.cppframeworks/base/core/jni/AndroidRunti ...

  7. i.mx6 Android5.1.1 vibrator系统服务流程

    0. 概述 0.1 小结 下面来从APP一直分析到kernel的driver,因为vibrator是我所知的最简单的系统服务,分析过程过来,可以获取整个安卓服务的运行思路,把相关知识点都串联起来,又不 ...

  8. i.mx6 Android5.1.1 系统属性

    属性变更的请求时init事件循环处理的另一个事件,在Android平台中,为了让运行中的所有进程共享系统运行时所需要的各种设置值,系统开辟了属性存储区域,并提供了访问该区域的API.属性由键(key) ...

  9. i.mx6 Android5.1.1 build解析

    参考资料:理解 Android Build 系统 把总结放前面: 1. 常用编译命令 make clean 执行清理,等同于:rm -rf out/. make sdk 编译出 Android 的 S ...

随机推荐

  1. corss、inner、outer三种join方式

    cross join(没有on)inner join(一般用于交集)outer join(你懂得)后面两个 on 1=1 效果同cross join

  2. 对java位运算之异或运算的一点记录

    首先,异或运算是,每个位上的数不同为1,相同为0. 其次,对两个数值变量的值进行三次异或运算就等于是交换了两个变量的值. 例如: int a = 4; int b = 10; a = a ^ b; b ...

  3. DevExpress GridControl+UserControl实现分页

    志向不过是记忆的奴隶,生气勃勃地降生,但却很难成长. —— 莎士比亚 时隔一年,我写随笔真的很随意,想起了就来博客园写写,想不起来就任由懒惰支配着我.不过我到觉得这不是什么坏事,你不用为了完成某事而让 ...

  4. EasyUi控件Datagrid

    很久没有打开我的博客园,刚刚大概扫了一眼我之前写的笔记,关于Devexpress那篇居然有四千多的浏览记录,不知道对浏览过的博友有没有起到一点点作用.当然我写笔记仅仅只是给自己留个记忆,如果歪打正着帮 ...

  5. Android App的破解技术有哪些?如何防止反编译?

     现在最流行的App破解技术大多是基于一定相关技术的基础:如一定阅读Java代码的能力.有一些Android基础.会使用eclipse的一些Android调试的相关工具以及了解一些smali的语法规范 ...

  6. python--类与类之间的关系,(魔术方法)特殊成员方法

    1.依赖关系 类与类之间存在这几种关系:1.依赖关系 2.关联关系 3.组合关系 4.聚合关系 5.继承关系 6.实现关系 我们来设置下面两个场景 玩电脑和打僵尸 class Person: def ...

  7. GO学习笔记 - Go 只有一种循环结构—— for 循环。

    一,Go 只有一种循环结构—— for 循环. 官方教程:https://tour.go-zh.org/flowcontrol/1 Go 只有一种循环结构—— for 循环. 基本的 for 循环包含 ...

  8. “全栈2019”Java多线程第八章:放弃执行权yield()方法详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  9. 洛谷P4069 [SDOI2016]游戏(李超线段树)

    题面 传送门 题解 如果我们把路径拆成两段,那么这个路径加可以看成是一个一次函数 具体来说,设\(dis_u\)表示节点\(u\)到根节点的距离,那么\((x,lca)\)这条路径上每个节点的权值就会 ...

  10. 【经典漏洞案例】NSA黑客工具包——Windows 0day验证实验

    还记得今年4月中旬,Shadow Brokers(影子经纪人)黑客组织发布出一份震惊世界的机密文档,其中包含了多个Windows 远程漏洞利用工具,此工具集覆盖大量的Windows服务 器,可以被任何 ...