Android启动过程大致可分为bootloader引导,装载和启动Linux内核,启动Android系统3个大阶段。
其中启动Android系统可以细分为启动Init进程、启动Zygote进程、启动SystemService、启动Home等多个阶段。
bootloader做的事情主要有:初始化CPU时钟,内存,串口等;设置linux启动参数;加载Linux各种各样的内核镜像到SDRAM中。
开机按组合键可进入相应的模式,fastboot/recovery模式/按开机则正常启动流程。
内核启动时,设置缓存、被保护存储器、计划列表,加载驱动。当内核完成系统设置,它首先在系统文件中寻找”init”文件,然后启动root进程或者系统的第一个进程。
3.1 Init进程
Init进程,它是一个由内核启动的用户级进程。内核自行启动(已经被载入内存,开始运行,并已初始化所有的设备驱动程序和数据结构等)之后,就通过启动一个用户级程序init的方式,完成引导进程。init始终是第一个进程.
int main(int argc, char** argv) {
....
//第一阶段,挂载文件系统和创建文件目录
if (is_first_stage) {
mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
mkdir("/dev/pts", 0755);
mkdir("/dev/socket", 0755);
mount("devpts", "/dev/pts", "devpts", 0, NULL);
#define MAKE_STR(x) __STRING(x)
mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
mount("sysfs", "/sys", "sysfs", 0, NULL);
}
//初始化内核log系统
open_devnull_stdio();
klog_init();
klog_set_level(KLOG_NOTICE_LEVEL);
...
if (!is_first_stage) {
// Indicate that booting is in progress to background fw loaders, etc.
close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
//初始化属性相关资源
property_init();
// If arguments are passed both on the command line and in DT,
// properties set in DT always have priority over the command-line ones.
process_kernel_dt();
process_kernel_cmdline();
// Propagate the kernel variables to internal variables
// used by init as well as the current required properties.
export_kernel_boot_props();
}
//设置SELinux policy策略
// Set up SELinux, including loading the SELinux policy if we're in the kernel domain.
selinux_initialize(is_first_stage);
....
//创建epoll句柄
epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (epoll_fd == -1) {
ERROR("epoll_create1 failed: %s\n", strerror(errno));
exit(1);
}
signal_handler_init();
property_load_boot_defaults();
export_oem_lock_status();
//启动属性服务
start_property_service();
const BuiltinFunctionMap function_map;
Action::set_function_map(&function_map);
Parser& parser = Parser::GetInstance();
parser.AddSectionParser("service",std::make_unique<ServiceParser>());
parser.AddSectionParser("on", std::make_unique<ActionParser>());
parser.AddSectionParser("import", std::make_unique<ImportParser>());
//解析init.rc。
parser.ParseConfig("/init.rc");
//解析完成配置文件之后,会得到一系列的action动作。init和boot。
ActionManager& am = ActionManager::GetInstance();
...
//while循环不断调用ExecuteOneCommand函数时,匹配的action。
while (true) {
....
//通过epoll来监听,处理属性服务相关的事情。
epoll_event ev;
int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, timeout));
if (nr == -1) {
ERROR("epoll_wait failed: %s\n", strerror(errno));
} else if (nr == 1) {
((void (*)()) ev.data.ptr)();
}
}
return 0;
}
小结下init的main函数主要工作:
1.创建文件系统目录并挂载相关的文件系统。
2.初始化内核log系统。
3.初始化属性相关资源,利用ashmem共享。
4.设置SELinux policy策略
5.创建epoll句柄。
6.启动属性服务。
7.通过parser拆分,解析init.rc。
8.while循环,通过epoll句柄来处理属性服务相关的事情。
import /init.environ.rc
import /init.usb.rc
import /init.${ro.hardware}.rc
import /init.usb.configfs.rc
import /init.${ro.zygote}.rc
import用来初始化一些配置文件的。我们可以看到配置了zygote。 这里区分了不同平台(32,64,64_32)
转而看一下init.zygote64.rc
#service [ ]*
#<名字><执行程序路径><参数>
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
class main
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart audioserver
onrestart restart cameraserver
onrestart restart media
onrestart restart netd
writepid /dev/cpuset/foreground/tasks
看一下子进程(system/bin/app_process)到底做了什么,framework/cmds/app_process/app_main.cpp的main函数。
3.2 zygote 进程
int main(int argc, char* const argv[])
{
....
if (zygote) {
//com.android.internal.os.ZygoteInit"是Android Java运行时环境的初始化类
//start方法具体所做的事,注册一系列本地函数到虚拟机,通过反射机制找到ZygoteInit.main方法并执行。
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
} else if (className) {
runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
} else {
fprintf(stderr, "Error: no class name or --zygote supplied.\n");
app_usage();
LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
return 10;
}
}
runtime.start通过反射机制调用ZygoteInit.java的main方法
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static void main(String argv[]) {
...
//注册socket
registerZygoteSocket(socketName);
Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "ZygotePreload");
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,SystemClock.uptimeMillis());
//加载
preload();
...
if (startSystemServer) {
//启动SystemServer
startSystemServer(abiList, socketName);
}
//进入runSelectLoop循环
runSelectLoop(abiList);
...
}
ZygoteInit.main方法主要做四件事:
1.注册soceket监听端口接收应用程序的消息
2.预加载系统资源,当应用程序被fork处理后,已经包含了这些资源,大大节省了应用启动的时间
3.启动SystemServer进程,经过层层调用,最终会调用到SystemServer.main方法。
4进入runSelectLoop循环处理事件。
private static boolean startSystemServer(String abiList, String socketName)
throws MethodAndArgsCaller, RuntimeException {
...
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"com.android.server.SystemServer",
};
...
//母进程开始分叉服务 启动SystemServer
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
...
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
handleSystemServerProcess(parsedArgs);
}
...
}
在startSystemServer中主要做了三件事:
1.为SystemServer准备启动参数,可以看到进程id和组id都被指定为1000,执行类是com.android.server.SystemServer。
2.调用Zygote.forkSystemServer来fork出SystemServer的子进程。forkSystemServer调用了native层的ForkAndSpecializeCommon函数来完成实际工作。Zygote会检查SystemServer启动情况,如果启动失败,Zygote会让自己退出,重新再启动。由此可见SystemServer的重要性。
static jint com_android_internal_os_Zygote_nativeForkSystemServer(
JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
jlong effectiveCapabilities) {
pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
debug_flags, rlimits,
permittedCapabilities, effectiveCapabilities,
MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
NULL, NULL);
if (pid > 0) {
// The zygote process checks whether the child process has died or not.
ALOGI("System server process %d has been created", pid);
gSystemServerPid = pid;
// There is a slight window that the system server process has crashed
// but it went unnoticed because we haven't published its pid yet. So
// we recheck here just to make sure that all is well.
int status;
if (waitpid(pid, &status, WNOHANG) == pid) {
ALOGE("System server process %d has died. Restarting Zygote!", pid);
//启动SystemServer失败,重启系统
RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
}
}
return pid;
}
//ForkAndSpecializeCommon在fork子进程之前还调用了SetSigChldHandler().设置处理SIGCHLD信号函数的
//SigChldHandler.这是接收子进程信号。
static void SigChldHandler(int /*signal_number*/) {
...
//接收到子进程死亡的信号,调用waitpid防止子进程变成僵尸,
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
...
//如果是SystemServer,Zygote会自杀,这样会导致Init进程kill所有的进程,再重启Zygote.
if (pid == gSystemServerPid) {
ALOGE("Exit zygote because system server (%d) has terminated", pid);
kill(getpid(), SIGKILL);
}
}
...
}
3.fork出SystemServer后,调用handleSystemServerProcess来初始化SystemServer进程。
然后分析下接下来是如果进入到SystemServer的main。
Zygoteinit.handleSystemServerProcess()->RuntimeInit.zygoteInit() ->RuntimeInit.applicationInit()
->RuntimeInit.invokeStaticMain()这个方法最后抛出了一个 ZygoteInit.MethodAndArgsCaller。然后在Zygoteinit.main()中catch了这个异常。->caller.run(){ mMethod.invoke(null, new Object[] { mArgs });…}
通过反射启动SystemServer.main();目的为了清空栈帧,提高栈帧的利用率。
3.3 SystemServer 进程
SystemServer是Android系统核心之一,大部分的Android系统服务都是运行在这里。
public static void main(String[] args) {
//创建一个SystemServer对象然后执行run();
new SystemServer().run();
}
private void run() {
try {
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitBeforeStartServices");
//如果时间不对,调整系统时间
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
//设置系统语言
if (!SystemProperties.get("persist.sys.language").isEmpty()) {
final String languageTag = Locale.getDefault().toLanguageTag();
SystemProperties.set("persist.sys.locale", languageTag);
SystemProperties.set("persist.sys.language", "");
SystemProperties.set("persist.sys.country", "");
SystemProperties.set("persist.sys.localevar", "");
}
// 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());
...
//调整虚拟机堆内存,设置堆利用率0.8。
VMRuntime.getRuntime().clearGrowthLimit();
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
Build.ensureFingerprintProperty();
Environment.setUserRequired(true);
BaseBundle.setShouldDefuse(true);
BinderInternal.disableBackgroundScheduling(true);
BinderInternal.setMaxThreads(sMaxBinderThreads);
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
//装载库libandroid_servers.so
System.loadLibrary("android_servers");
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.获取Context。
createSystemContext();
// Create the system service manager.
//创建SystemServiceManager负责系统Service的启动。
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
// Start services.
try {
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
//创建并运行所有的java服务。由此可见系统默认把java服务分为三类
startBootstrapServices();
startCoreServices();
startOtherServices();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
// For debug builds, log event loop stalls to dropbox for analysis.
if (StrictMode.conditionallyEnableDebugLogging()) {
Slog.i(TAG, "Enabled StrictMode for system server main thread.");
}
// Loop forever.处理消息
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在SystemServer的run方法里,启动了所有的java服务。其中startBootstrapServices()中主要启动了ActivityManagerService.
private void startBootstrapServices() {
...
//启动AMS服务
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
//设置AMS的系统服务管理器
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//设置AMS的APP安装器
mActivityManagerService.setInstaller(installer);
//初始化AMS相关的PMS
mActivityManagerService.initPowerManagement();
...
//设置SystemServer
mActivityManagerService.setSystemProcess();
...
}
private void startOtherServices() {
...
// 准备好window, power, package, display服务
wm.systemReady();
mPowerManagerService.systemReady(...);
mPackageManagerService.systemReady();
mDisplayManagerService.systemReady(...);
mActivityManagerService.systemReady(new Runnable() {
public void run() {
...
}
});
}
public void systemReady(final Runnable goingCallback) {
...
synchronized (this) {
...
mStackSupervisor.resumeFocusedStackTopActivityLocked();
mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
}
...
}
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && isFocusedStack(targetStack)) {
//1
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || r.state != RESUMED) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
}
return false;
}
在注释1处会调用ActivityStack的resumeTopActivityUncheckedLocked函数,ActivityStack对象是用来描述Activity堆栈的,resumeTopActivityUncheckedLocked函数如下所示。
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mStackSupervisor.inResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean result = false;
try {
// Protect against recursion.
mStackSupervisor.inResumeTopActivity = true;
if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
mService.updateSleepIfNeededLocked();
}
//1
result = resumeTopActivityInnerLocked(prev, options);
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
//注释1调用了resumeTopActivityInnerLocked函数,
//resumeTopActivityInnerLocked代码很长我们截取我们要分析的关键的一句:调用ActivityStackSupervisor的resumeHomeStackTask函数。
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
return isOnHomeDisplay() &&
mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
...
boolean resumeHomeStackTask(int homeStackTaskType, ActivityRecord prev, String reason) {
if (!mService.mBooting && !mService.mBooted) {
// Not ready yet!
return false;
}
if (homeStackTaskType == RECENTS_ACTIVITY_TYPE) {
mWindowManager.showRecentApps(false /* fromHome */);
return false;
}
if (prev != null) {
prev.task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
}
mHomeStack.moveHomeStackTaskToTop(homeStackTaskType);
ActivityRecord r = getHomeActivity();
final String myReason = reason + " resumeHomeStackTask";
// Only resume home activity if isn't finishing.
if (r != null && !r.finishing) {
mService.setFocusedActivityLocked(r, myReason);
return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
}
return mService.startHomeActivityLocked(mCurrentUser, myReason);
}
最后回到ActivityManagerService的startHomeActivityLocked()
boolean startHomeActivityLocked(int userId, String reason) {
// mFactoryTest代表系统的运行模式,系统的运行模式分为三种,
//分别是非工厂模式、低级工厂模式和高级工厂模式
//mTopAction则用来描述第一个被启动Activity组件的Action,它的值为Intent.ACTION_MAIN。
//因此注释1的代码意思就是mFactoryTest为FactoryTest.FACTORY_TEST_LOW_LEVEL(低级工厂模式)
//并且mTopAction=null时,直接返回false
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
&& mTopAction == null) {
return false;
}
//getHomeIntent函数中创建了Intent,并将mTopAction和mTopData传入。mTopAction的值为
//Intent.ACTION_MAIN,并且如果系统运行模式不是低级工厂模式则将intent的Category设置为
//Intent.CATEGORY_HOME。
Intent intent = getHomeIntent();
ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
if (aInfo != null) {
intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
// Don't do this if the home app is currently being
// instrumented.
aInfo = new ActivityInfo(aInfo);
aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
ProcessRecord app = getProcessRecordLocked(aInfo.processName,
aInfo.applicationInfo.uid, true);
//判断符合Action为Intent.ACTION_MAIN,Category为Intent.CATEGORY_HOME的应用程序是否已经启动
if (app == null || app.instrumentationClass == null) {
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
//如果没启动则调用startHomeActivityLocked方法启动该应用程序。这个被启动的应用程序就是Launcher,
//因为Launcher的Manifest文件中的intent-filter标签匹配了Action为Intent.ACTION_MAIN,
//Category为Intent.CATEGORY_HOME。
//这样,应用程序Launcher就会被启动起来,并执行它的onCreate函数。
mActivityStarter.startHomeActivityLocked(intent, aInfo, reason);
}
} else {
Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
}
return true;
}
总结一下,Android系统启动流程如下: