赞
踩
1、Boot ROM:
上电后,BootRom会被激活,引导芯片代码
开始从预定义的地方(固化在ROM)开始执行,然后加载引导程序到RAM
。
2、 Boot Loader引导程序
Android是基于Linux系统的,它没有BIOS程序,取而代之的是BootLoader(系统启动引导程序)。引导程序是厂商加锁和限制的地方,它是针对特定的主板与芯片的。厂商要么使用很受欢迎的引导程序比如redboot
、uboot
、ARMboot
等或者开发自己的引导程序,它不是Android操作系统的一部分。流程图如下:
swapper进程用于初始化进程管理、内存管理,加载Display,Camera Driver,Binder Driver等相关工作。
2、1号进程——就是init进程
init进程(pid=1):由0号进程通过kernel_thread创建,在内核空间完成初始化后, 加载init程序, 并最终运行在用户空间,init进程是所有用户进程的鼻祖,他的作用是:
(1)是挂载tmpfs, devpts, proc, sysfs文件系统
。
(2)是运行init.rc脚本,init将会解析init.rc,并且执行init.rc中的命令。
(3)当一些关键进程死亡时,重启该进程;
(4)提供Android系统的属性服务
3、2号进程
kthreadd进程(pid=2):由0号进程通过kernel_thread创建,是Linux系统的内核进程,会创建内核工作线程kworkder,软中断线程ksoftirqd,thermal等内核守护进程。
kthreadd运行在内核空间, 负责所有内核线程的调度和管理 , kthreadd进程是所有内核进程的鼻祖
。
我们先给个大体的流程如下图:
init进程启动执行了两个重要操作:
1.启动了Zygote(包括32位、64位Zygote进程),Zygote 又fork了systemService
2.启动serviceManager
我们来看看具体代码实现
内核启动后加载system/core/init/init.rc文件,启动init进程。我们看一下init.rc文件
start servicemanager // 2.servicemanager启动
start hwservicemanager
start vndservicemanager
import /system/etc/init/hw/init.${ro.zygote}.rc
trigger zygote-start //启动zygote的代码实现在服务声明
on zygote-start && property:ro.crypto.state=unencrypted
wait_for_prop odsign.verification.done 1
# A/B update verifier that marks a successful boot.
exec_start update_verifier_nonencrypted
start statsd
start netd
start zygote //1.启动32位Zygote兼容32位程序
start zygote_secondary //2.启动64位Zygote兼容64位程序
接下来我们通过这两个过程详细分析一下
我们来看一下 zygote 的服务声明文件 init.zygote64.rc
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
class main
socket zygote stream 660 root system
从服务声明可见启动start zygote 就是执行app_process64程序,app_process的源码在frameworks/base/cmds/app_process/app_main.cpp
int main(int argc, const char* const argv[])
{
//...省略
AppRuntime runtime;
while (i < argc) {
if (!parentDir) {
} else if (strcmp(arg, "--zygote") == 0) {
zygote = true;//zygote进程
niceName = "zygote";
} else if (strcmp(arg, "--start-system-server") == 0) {
startSystemServer = true;//启动系统服务
}
}
if (niceName && *niceName) {
setArgv0(argv0, niceName);
set_process_name(niceName);
}
runtime.mParentDir = parentDir;
if (zygote) {
//参数 0、类名 1、
runtime.start("com.android.internal.os.ZygoteInit",
startSystemServer ? "start-system-server" : "");//在这里通过runtime启动ZygoteInit从此由内核C层进入了我们的应用层。
} else if (className) {
runtime.start("com.android.internal.os.RuntimeInit",
application ? "application" : "tool");
} else {
}
}
runtime.start的源代码在jni/AndroidRuntime.cpp 如下
runtime.start("com.android.internal.os.ZygoteInit",
startSystemServer ? "start-system-server" : "") 做了四件事:
(1).检查化文件目录
(2).初始化Jni调用
(3).启动Java虚拟机
(4).调用 ZygoteInit main函数
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{
static const String8 startSystemServer("start-system-server");
bool primary_zygote = false;
//省略。。。
//一系列目录操作 1.检查化文件目录
const char* rootDir = getenv("ANDROID_ROOT");
if (rootDir == NULL) {
rootDir = "/system";
if (!hasDir("/system")) {
LOG_FATAL("No root directory specified, and /system does not exist.");
return;
}
setenv("ANDROID_ROOT", rootDir, 1);
}
const char* artRootDir = getenv("ANDROID_ART_ROOT");
if (artRootDir == NULL) {
LOG_FATAL("No ART directory specified with ANDROID_ART_ROOT environment variable.");
return;
}
const char* i18nRootDir = getenv("ANDROID_I18N_ROOT");
if (i18nRootDir == NULL) {
LOG_FATAL("No runtime directory specified with ANDROID_I18N_ROOT environment variable.");
return;
}
const char* tzdataRootDir = getenv("ANDROID_TZDATA_ROOT");
if (tzdataRootDir == NULL) {
LOG_FATAL("No tz data directory specified with ANDROID_TZDATA_ROOT environment variable.");
return;
}
//2.初始化Jni调用
JniInvocation jni_invocation;
jni_invocation.Init(NULL);
JNIEnv* env;
//3.启动Java虚拟机
if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {
return;
}
onVmCreated(env);
if (startReg(env) < 0) {
ALOGE("Unable to register all android natives\n");
return;
}
//省略。。。
jclass startClass = env->FindClass(slashClassName);
if (startClass == NULL) {
ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
/* keep going */
} else {
//查找 com.android.internal.os.ZygoteInit的main函数
jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
"([Ljava/lang/String;)V");
if (startMeth == NULL) {
ALOGE("JavaVM unable to find main() in '%s'\n", className);
/* keep going */
} else {
//4.调用 ZygoteInit main函数
env->CallStaticVoidMethod(startClass, startMeth, strArray);
#if 0
if (env->ExceptionCheck())
threadExitUncaughtException(env);
#endif
}
}
free(slashClassName);
ALOGD("Shutting down VM\n");
if (mJavaVM->DetachCurrentThread() != JNI_OK)
}
我们重点关注/java/com/android/internal/os/ZygoteInit.java main函数,main函数做了如下:
(1).准备Fork
(2).调用预加载
(3).初始化zygote
(4).new 了一个 ZygoteServer
(5).forkSystemServer
(6)启动Looper 不停的检查 ZygoteServer 的 Sockect变化
public static void main(String[] argv) {
ZygoteServer zygoteServer = null;
//1.添加多次启动zygote检查 ,当前就是Zygote了
ZygoteHooks.startZygoteNoThreadCreation();
try {
Os.setpgid(0, 0);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to setpgid(0,0)", ex);
}
Runnable caller;
try {
// Store now for StatsLogging later.
final long startTime = SystemClock.elapsedRealtime();
final boolean isRuntimeRestarted = "1".equals(
SystemProperties.get("sys.boot_completed"));
String bootTimeTag = Process.is64Bit() ? "Zygote64Timing" : "Zygote32Timing";
TimingsTraceLog bootTimingsTraceLog = new TimingsTraceLog(bootTimeTag,
Trace.TRACE_TAG_DALVIK);
bootTimingsTraceLog.traceBegin("ZygoteInit");
//1.准备Fork
RuntimeInit.preForkInit();
boolean startSystemServer = false;
String zygoteSocketName = "zygote";
String abiList = null;
boolean enableLazyPreload = false;
for (int i = 1; i < argv.length; i++) {
if ("start-system-server".equals(argv[i])) {
startSystemServer = true;
} else if ("--enable-lazy-preload".equals(argv[i])) {
enableLazyPreload = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
abiList = argv[i].substring(ABI_LIST_ARG.length());
} else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
zygoteSocketName = argv[i].substring(SOCKET_NAME_ARG.length());
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}
final boolean isPrimaryZygote = zygoteSocketName.equals(Zygote.PRIMARY_SOCKET_NAME);
if (!isRuntimeRestarted) {
if (isPrimaryZygote) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__ZYGOTE_INIT_START,
startTime);
} else if (zygoteSocketName.equals(Zygote.SECONDARY_SOCKET_NAME)) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SECONDARY_ZYGOTE_INIT_START,
startTime);
}
}
if (abiList == null) {
throw new RuntimeException("No ABI list supplied.");
}
if (!enableLazyPreload) {
bootTimingsTraceLog.traceBegin("ZygotePreload");
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
SystemClock.uptimeMillis());
preload(bootTimingsTraceLog);//2.调用预加载
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
SystemClock.uptimeMillis());
bootTimingsTraceLog.traceEnd(); // ZygotePreload
}
// Do an initial gc to clean up after startup
bootTimingsTraceLog.traceBegin("PostZygoteInitGC");
gcAndFinalize();
bootTimingsTraceLog.traceEnd(); // PostZygoteInitGC
bootTimingsTraceLog.traceEnd(); // ZygoteInit
Zygote.initNativeState(isPrimaryZygote);//3.初始化zygote状态
ZygoteHooks.stopZygoteNoThreadCreation();
//4.new 了一个 ZygoteServer
zygoteServer = new ZygoteServer(isPrimaryZygote);
if (startSystemServer) {//5.forkSystemServer
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
if (r != null) {
r.run();
return;
}
}
Log.i(TAG, "Accepting command socket connections");
// The select loop returns early in the child process after a fork and
// loops forever in the zygote.
caller = zygoteServer.runSelectLoop(abiList);//6.启动Looper 不停的检查 ZygoteServer 的 Sockect变化
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with fatal exception", ex);
throw ex;
} finally {
if (zygoteServer != null) {
zygoteServer.closeServerSocket();
}
}
// We're in the child process and have exited the select loop. Proceed to execute the
// command.
if (caller != null) {
caller.run();
}
}
static void preload(TimingsTraceLog bootTimingsTraceLog) {
Log.d(TAG, "begin preload");
beginPreload();
preloadClasses();//预加载类,其中就包括我们熟悉的系统API
cacheNonBootClasspathClassLoaders();加载无法放入Boot classpath的文件
preloadResources();加载drawables、colors
nativePreloadAppProcessHALs();加载hal 硬件
maybePreloadGraphicsDriver();调用OpenGL/Vulkan加载图形驱动程序
preloadSharedLibraries();//加载共享库
preloadTextResources();初始化TextView ,对,你没看错
WebViewFactory.prepareWebViewInZygote();//初始化webview
endPreload();// 取消软引用保护
warmUpJcaProviders(); 初始化JCA安全相关的参数,比如AndroidKeyStoreProvider安装
sPreloadComplete = true;
}
java/com/android/internal/os/ZygoteServer.java
class ZygoteServer {
ZygoteServer(boolean isPrimaryZygote) {
mUsapPoolEventFD = Zygote.getUsapPoolEventFD();
//创建Zygote Socket 链接
if (isPrimaryZygote) {
mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.PRIMARY_SOCKET_NAME);
mUsapPoolSocket =
Zygote.createManagedSocketFromInitSocket(
Zygote.USAP_POOL_PRIMARY_SOCKET_NAME);
} else {
mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.SECONDARY_SOCKET_NAME);
mUsapPoolSocket =
Zygote.createManagedSocketFromInitSocket(
Zygote.USAP_POOL_SECONDARY_SOCKET_NAME);
}
mUsapPoolSupported = true;
fetchUsapPoolPolicyProps();//USAP 预创建进程机制,提前Fork好一定数量进程待用,提高效率
}
}
public final class Zygote { //Zygote Socket 链接的最终实现是 LocalServerSocket
static LocalServerSocket createManagedSocketFromInitSocket(String socketName) {
int fileDesc;
final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
try {
String env = System.getenv(fullSocketName);
fileDesc = Integer.parseInt(env);
} catch (RuntimeException ex) {
throw new RuntimeException("Socket unset or invalid: " + fullSocketName, ex);
}
try {
FileDescriptor fd = new FileDescriptor();//创建文件描述符,Linux中socket也是文件
fd.setInt$(fileDesc);
return new LocalServerSocket(fd);//建立 socket
} catch (IOException ex) {
throw new RuntimeException(
"Error building socket from file descriptor: " + fileDesc, ex);
}
}
}
public LocalServerSocket(FileDescriptor fd) throws IOException
{
impl = new LocalSocketImpl(fd);//socket实现类
impl.listen(LISTEN_BACKLOG);//监听socket 消息,比如需要fork新进程
localAddress = impl.getSockAddress();
}
public class ZygoteInit {
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
StructCapUserHeader header = new StructCapUserHeader(
OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
StructCapUserData[] data;
try {
data = Os.capget(header);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to capget()", ex);
}
capabilities &= Integer.toUnsignedLong(data[0].effective) |
(Integer.toUnsignedLong(data[1].effective) << 32);
String[] args = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
+ "1024,1032,1065,3001,3002,3003,3005,3006,3007,3009,3010,3011,3012",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
"com.android.server.SystemServer",//后续会调用 SystemServer 的main函数
};
ZygoteArguments parsedArgs;
int pid;
try {//添加命令参数
ZygoteCommandBuffer commandBuffer = new ZygoteCommandBuffer(args);
try {
parsedArgs = ZygoteArguments.getInstance(commandBuffer);
} catch (EOFException e) {
throw new AssertionError("Unexpected argument error for forking system server", e);
}
commandBuffer.close();
Zygote.applyDebuggerSystemProperty(parsedArgs);
Zygote.applyInvokeWithSystemProperty(parsedArgs);//获取需要的系统属性参数
if (Zygote.nativeSupportsMemoryTagging()) {
String mode = SystemProperties.get("arm64.memtag.process.system_server", "");
if (mode.isEmpty()) {
/* The system server has ASYNC MTE by default, in order to allow
* system services to specify their own MTE level later, as you
* can't re-enable MTE once it's disabled. */
mode = SystemProperties.get("persist.arm64.memtag.default", "async");
}
if (mode.equals("async")) {
parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_ASYNC;
} else if (mode.equals("sync")) {
parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_SYNC;
} else if (!mode.equals("off")) {
/* When we have an invalid memory tag level, keep the current level. */
parsedArgs.mRuntimeFlags |= Zygote.nativeCurrentTaggingLevel();
Slog.e(TAG, "Unknown memory tag level for the system server: \"" + mode + "\"");
}
} else if (Zygote.nativeSupportsTaggedPointers()) {
/* Enable pointer tagging in the system server. Hardware support for this is present
* in all ARMv8 CPUs. */
parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI;
}
/* Enable gwp-asan on the system server with a small probability. This is the same
* policy as applied to native processes and system apps. */
parsedArgs.mRuntimeFlags |= Zygote.GWP_ASAN_LEVEL_LOTTERY;
if (shouldProfileSystemServer()) {
parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
}
/* Request to fork the system server process */
pid = Zygote.forkSystemServer( //调用zygote fork 系统服务
parsedArgs.mUid, parsedArgs.mGid,
parsedArgs.mGids,
parsedArgs.mRuntimeFlags,
null,
parsedArgs.mPermittedCapabilities,
parsedArgs.mEffectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
return handleSystemServerProcess(parsedArgs);//
}
return null;
}
}
先调用 java/com/android/internal/os/Zygote.java 的 forkSystemServer,我们看一下源码
static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
ZygoteHooks.preFork();
int pid = nativeForkSystemServer(//调用native层fork system Server
uid, gid, gids, runtimeFlags, rlimits,
permittedCapabilities, effectiveCapabilities);
// Set the Java Language thread priority to the default value for new apps.
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
ZygoteHooks.postForkCommon();
return pid;
}
nativeForkSystemServer 在 com_android_internal_os_Zygote.cpp
static jint com_android_internal_os_Zygote_nativeForkSystemServer(
JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
jlong effective_capabilities) {
std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
fds_to_ignore(fds_to_close);
fds_to_close.push_back(gUsapPoolSocketFD);
if (gUsapPoolEventFD != -1) {
fds_to_close.push_back(gUsapPoolEventFD);
fds_to_ignore.push_back(gUsapPoolEventFD);
}
if (gSystemServerSocketFd != -1) {
fds_to_close.push_back(gSystemServerSocketFd);
fds_to_ignore.push_back(gSystemServerSocketFd);
}
pid_t pid = zygote::ForkCommon(env, true,//fork 函数
fds_to_close,
fds_to_ignore,
true);
if (pid == 0) {//0号进程
//省略...
} else if (pid > 0) {//非0号进程,也就是init或者其他进程
ALOGI("System server process %d has been created", pid);
gSystemServerPid = pid;
int status;
if (waitpid(pid, &status, WNOHANG) == pid) {
ALOGE("System server process %d has died. Restarting Zygote!", pid);
RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
}
if (UsePerAppMemcg()) {
if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
ALOGE("couldn't add process %d into system memcg group", pid);
}
}
}
return pid;
}
pid_t zygote::ForkCommon(JNIEnv* env, bool is_system_server,
const std::vector<int>& fds_to_close,
const std::vector<int>& fds_to_ignore,
bool is_priority_fork,
bool purge) {
SetSignalHandlers();
auto fail_fn = std::bind(zygote::ZygoteFailure, env,
is_system_server ? "system_server" : "zygote",
nullptr, _1);
BlockSignal(SIGCHLD, fail_fn);
__android_log_close();
AStatsSocket_close();
if (gOpenFdTable == nullptr) {
gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
} else {
gOpenFdTable->Restat(fds_to_ignore, fail_fn);
}
pid_t pid = fork();//真实的fork 进程
if (pid == 0) {
if (is_priority_fork) {
setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
} else {
setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MIN);
}
#if defined(__BIONIC__) && !defined(NO_RESET_STACK_PROTECTOR)
android_reset_stack_guards();
#endif
PreApplicationInit(); //分配内存
DetachDescriptors(env, fds_to_close, fail_fn);
ClearUsapTable();
gOpenFdTable->ReopenOrDetach(fail_fn);
android_fdsan_set_error_level(fdsan_error_level);
gSystemServerSocketFd = -1;
} else if (pid == -1) {
ALOGE("Failed to fork child process: %s (%d)", strerror(errno), errno);
} else {
ALOGD("Forked child process %d", pid);
}
UnblockSignal(SIGCHLD, fail_fn);
return pid;
}
然后调用 handleSystemServerProcess
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
Os.umask(S_IRWXG | S_IRWXO);//为用户文件创建权限掩码
if (parsedArgs.mNiceName != null) {
Process.setArgV0(parsedArgs.mNiceName);//执行AndroidRuntime::getRuntime()->setArgv0设置进程名 为system_server
}
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
if (shouldProfileSystemServer() && (Build.IS_USERDEBUG || Build.IS_ENG)) {
try {
Log.d(TAG, "Preparing system server profile");
final String standaloneSystemServerJars =
Os.getenv("STANDALONE_SYSTEMSERVER_JARS");
final String systemServerPaths = standaloneSystemServerJars != null
? String.join(":", systemServerClasspath, standaloneSystemServerJars)
: systemServerClasspath;
prepareSystemServerProfile(systemServerPaths);//加载系统属性配置文件
} catch (Exception e) {
Log.wtf(TAG, "Failed to set up system server profile", e);
}
}
}
if (parsedArgs.mInvokeWith != null) {
String[] args = parsedArgs.mRemainingArgs;
if (systemServerClasspath != null) {
String[] amendedArgs = new String[args.length + 2];
amendedArgs[0] = "-cp";
amendedArgs[1] = systemServerClasspath;
System.arraycopy(args, 0, amendedArgs, 2, args.length);
args = amendedArgs;
}
WrapperInit.execApplication(parsedArgs.mInvokeWith,
parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
VMRuntime.getCurrentInstructionSet(), null, args);//启动app_process程序//后面有源码
throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
} else {
ClassLoader cl = getOrCreateSystemServerClassLoader();
if (cl != null) {
Thread.currentThread().setContextClassLoader(cl);
}
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl); //看后续源码
}
}
WrapperInit.execApplication
public static void execApplication(String invokeWith, String niceName,
int targetSdkVersion, String instructionSet, FileDescriptor pipeFd,
String[] args) {
StringBuilder command = new StringBuilder(invokeWith);
final String appProcess;
if (VMRuntime.is64BitInstructionSet(instructionSet)) {
appProcess = "/system/bin/app_process64";
} else {
appProcess = "/system/bin/app_process32";
}
command.append(' ');
command.append(appProcess);
command.append(" -Xcompiler-option --generate-mini-debug-info");
command.append(" /system/bin --application");
if (niceName != null) {
command.append(" '--nice-name=").append(niceName).append("'");
}
command.append(" com.android.internal.os.WrapperInit ");
command.append(pipeFd != null ? pipeFd.getInt$() : 0);
command.append(' ');
command.append(targetSdkVersion);
Zygote.appendQuotedShellArgs(command, args);
preserveCapabilities();
Zygote.execShell(command.toString());//执行命令
}
ZygoteInit.zygoteInit
public static Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit();//异常捕捉,设置时区等
ZygoteInit.nativeZygoteInit();//注册了 zygote 初始化的各种 jni 方法
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);//看后续源码
}
private static void applicationInit(int targetSdkVersion, String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
nativeSetExitWithoutCleanup(true);
VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);//设置目标sdk版本
final Arguments args;
try {
args = new Arguments(argv);
} catch (IllegalArgumentException ex) {
Slog.e(TAG, ex.getMessage());
// let the process exit
return;
}
invokeStaticMain(args.startClass, args.startArgs);
}
private static void invokeStaticMain(String className, String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
Class<?> cl;
try {
cl = Class.forName(className);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });//调用SystemServer.java类的main函数
} catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Missing static main on " + className, ex);
} catch (SecurityException ex) {
throw new RuntimeException(
"Problem getting static main on " + className, ex);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
SystemServer 的main函数如下
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
703 try {
800 Looper.prepareMainLooper();
807 System.loadLibrary("android_servers");
825 ActivityThread.initializeMainlineModules();
828 ServiceManager.addService("system_server_dumper", mDumper);
832 mSystemServiceManager = new SystemServiceManager(mSystemContext);
833 mSystemServiceManager.setStartInfo(mRuntimeRestart,
834 mRuntimeStartElapsedTime, mRuntimeStartUptime);
837 LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
867 } finally {
868 t.traceEnd(); // InitBeforeStartServices
869 }
874 // Start services.
875 try {
876 t.traceBegin("StartServices");
877 startBootstrapServices(t);//启动引导服务
878 startCoreServices(t);//启动内核服务
879 startOtherServices(t);//启动其他服务
880 } catch (Throwable ex) {
881 Slog.e("System", "******************************************");
882 Slog.e("System", "************ Failure starting system services", ex);
883 throw ex;
884 } finally {
885 t.traceEnd(); // StartServices
886 }
903 Looper.loop();
904
905 }
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
992
1011 ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
1012 ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE,
1013 new PlatformCompatNative(platformCompat));
1014 AppCompatCallbacks.install(new long[0]);
1015
1021 mSystemServiceManager.startService(FileIntegrityService.class);
1022
1028 Installer installer = mSystemServiceManager.startService(Installer.class);
1029
1034 mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
1035
1039 mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
1040
1044 mSystemServiceManager.startService(PowerStatsService.class);
1045
1048 startIStatsService();
1049
1054 startMemtrackProxyService();
1055
1060 ActivityTaskManagerService atm = mSystemServiceManager.startService(
1061 ActivityTaskManagerService.Lifecycle.class).getService();
1062 mActivityManagerService = ActivityManagerService.Lifecycle.startService(
1063 mSystemServiceManager, atm);
1064 mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
1065 mActivityManagerService.setInstaller(installer);
1066 mWindowManagerGlobalLock = atm.getGlobalLock();
1067
1071 mDataLoaderManagerService = mSystemServiceManager.startService(
1072 DataLoaderManagerService.class);
1073
1077 mIncrementalServiceHandle = startIncrementalService();
1078
1085 mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
1086
1089 mSystemServiceManager.startService(ThermalManagerService.class);
1090
1093 mSystemServiceManager.startService(HintManagerService.class);
1094
1099 mActivityManagerService.initPowerManagement();
1100
1104 mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
1105
1110 RescueParty.registerHealthObserver(mSystemContext);
1111 PackageWatchdog.getInstance(mSystemContext).noteBoot();
1112
1113
1115 mSystemServiceManager.startService(LightsService.class);
1116
1128 mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
1129
1133 mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
1134
1147 if (!mRuntimeRestart) {
1148
1155 DomainVerificationService domainVerificationService = new DomainVerificationService(
1156 mSystemContext, SystemConfig.getInstance(), platformCompat);
1157 mSystemServiceManager.startService(domainVerificationService);
1158
1173 SystemServerDexLoadReporter.configureSystemServerDexReporter(mPackageManagerService);
1174
1175 mFirstBoot = mPackageManagerService.isFirstBoot();
1176 mPackageManager = mSystemContext.getPackageManager();
1205 mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
1206
1215 mActivityManagerService.setSystemProcess();
1216
1219 platformCompat.registerPackageReceiver(mSystemContext);
1220
1233 mSystemServiceManager.startService(new OverlayManagerService(mSystemContext));
1234
1237 mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));
1238 LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
1249 mSystemServiceManager.startService(SensorService.class);
1250
1252 }
private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
1258
1262 mSystemServiceManager.startService(SystemConfigService.class);
1263
1267 mSystemServiceManager.startService(BatteryService.class);
1268
1272 mSystemServiceManager.startService(UsageStatsService.class);
1273 mActivityManagerService.setUsageStatsManager(
1274 LocalServices.getService(UsageStatsManagerInternal.class));
1275
1278 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
1279 t.traceBegin("StartWebViewUpdateService");
1280 mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
1281 t.traceEnd();
1282 }
1286 mSystemServiceManager.startService(CachedDeviceStateService.class);
1287
1291 mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
1292
1296 mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
1297
1301 mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);
1302
1306 mSystemServiceManager.startService(NativeTombstoneManagerService.class);
1307
1311 mSystemServiceManager.startService(BugreportManagerService.class);
1312
1316 mSystemServiceManager.startService(GpuService.class);
1317
1320 }
startOtherServices(){
//太多了,可以自己去看源码
http://aospxref.com/android-12.0.0_r3/xref/frameworks/base/services/java/com/android/server/SystemServer.java#run
}
systemserver服务启动就讲完了
我们看到 init 也启动了/system/bin/servicemanager程序,servicemanager程序的源码在android/frameworks/native/cmds/servicemanager/main.cpp
int main(int argc, char** argv) {
const char* driver = argc == 2 ? argv[1] : "/dev/binder";
sp<ProcessState> ps = ProcessState::initWithDriver(driver);//驱动层创建binder_proc
ps->setThreadPoolMaxThreadCount(0);
ps->setCallRestriction(ProcessState::CallRestriction::FATAL_IF_NOT_ONEWAY);
//创建ServiceManager
sp<ServiceManager> manager = sp<ServiceManager>::make(std::make_unique<Access>());
//添加服务
if (!manager->addService("manager", manager, false /*allowIsolated*/, IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT).isOk()) {
LOG(ERROR) << "Could not self register servicemanager";
}
IPCThreadState::self()->setTheContextObject(manager);
if (!ps->becomeContextManager()) {//注册成为binder服务的大管家
LOG(FATAL) << "Could not become context manager";
}
//开启looper 消息循环 监听 BinderCallback
sp<Looper> looper = Looper::prepare(false /*allowNonCallbacks*/);
BinderCallback::setupTo(looper); //处理Binder请求
ClientCallbackCallback::setupTo(looper, manager);//定时通知client变化
#ifndef VENDORSERVICEMANAGER
if (!SetProperty("servicemanager.ready", "true")) {
LOG(ERROR) << "Failed to set servicemanager ready property";
}
#endif
while(true) {
looper->pollAll(-1);
}
// should not be reached
return EXIT_FAILURE;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。