Android之初始化流程总结
Android设备上电至launcher出现的开机流程如上图所示,即主要分为三个阶段:Boot Loader,Linux Kernel和Android系统服务。默认情况下每个阶段都有各自的启动画面,启动画面的修改,是实际开发中经常遇到的需求。Boot Loader和Linux Kernel的启动,请参考Linux 启动流程图。本文主要集中在Android系统关键服务的启动解析。
1,init
init作为android中第一个被启动的进程(pid=0),它通过解析init.rc来启动android中大多数系统服务。具体语法格式请参考另一篇文章,Android启动之配置文件分析。
2,ServiceManager
service servicemanager /system/bin/servicemanager
class core
user system
group system
critical
onrestart restart healthd
onrestart restart zygote
onrestart restart media
onrestart restart surfaceflinger
onrestart restart drm
由 Android启动之配置文件分析 可知,servicemanager由init进程启动。由上图可知,ServiceManager所属class是core,其它同类的系统进程包括ueventd,console(system/bin/sh),adbd等,这些进程会被同时启动或停止。另外,请留意其中的critical选项,说明它是关键进程。
3,Zygote
service zygote /system/bin/app_process -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 media
onrestart restart netd
有上述可知:
ServiceName:zygote
Path: /system/bin/app_process
Arguments: -Xzygote /system/bin --zygote --start-system-server
Zygote所属class为main,而不是core,与其同class的系统进程有netd,debuggerd,rild等。
3.1, 我们来看下app_process的main函数
// frameworks/base/cmds/app_process/App_main.cpp
int main(int argc, char* const argv[])
{
......
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
......
// --zygote : Start in zygote mode
// --start-system-server : Start the system server.
// --application : Start in application (stand alone, non zygote) mode.
// --nice-name : The nice name for this process.
......
bool zygote = false;
bool startSystemServer = false;
bool application = false;
String8 niceName;
String8 className;
++i; // Skip unused "parent dir" argument.
while (i < argc) {
const char* arg = argv[i++];
if (strcmp(arg, "--zygote") == 0) {
zygote = true;
niceName = ZYGOTE_NICE_NAME;
} else if (strcmp(arg, "--start-system-server") == 0) {
startSystemServer = true;
} else if (strcmp(arg, "--application") == 0) {
application = true;
} else if (strncmp(arg, "--nice-name=", 12) == 0) {
niceName.setTo(arg + 12);
} else if (strncmp(arg, "--", 2) != 0) {
className.setTo(arg);
break;
} else {
--i;
break;
}
}
......
if (startSystemServer) {
args.add(String8("start-system-server"));
}
......
if (zygote) {
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
}
}
这个main函数很简单,但重要功能却是由AppRuntime完成。
3.2,AppRuntime::start()
// frameworks/base/core/jni/AndroidRuntime.cpp
/*
* Start the Android runtime. This involves starting the virtual machine
* and calling the "static void main(String[] args)" method in the class
* named by "className".
*
* Passes the main function two arguments, the class name and the specified
* options string.
*/
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{
ALOGD(">>>>>> START %s uid %d <<<<<<\n",
className != NULL ? className : "(unknown)", getuid());
static const String8 startSystemServer("start-system-server");
/*
* 'startSystemServer == true' means runtime is obsolete and not run from
* init.rc anymore, so we print out the boot start event here.
*/
for (size_t i = 0; i < options.size(); ++i) {
if (options[i] == startSystemServer) {
/* track our progress through the boot sequence */
const int LOG_BOOT_PROGRESS_START = 3000;
LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START, ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
}
}
const char* rootDir = getenv("ANDROID_ROOT");
if (rootDir == NULL) {
rootDir = "/system";
if (!hasDir("/system")) {
LOG_FATAL("No root directory specified, and /android does not exist.");
return;
}
setenv("ANDROID_ROOT", rootDir, 1);
}
//const char* kernelHack = getenv("LD_ASSUME_KERNEL");
//ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
/* start the virtual machine */
JniInvocation jni_invocation;
jni_invocation.Init(NULL);
JNIEnv* env;
if (startVm(&mJavaVM, &env, zygote) != 0) {//启动虚拟机
return;
}
onVmCreated(env);//虚拟机启动后的回调
/*
* Register android functions.
*/
if (startReg(env) < 0) {//注册JNI函数
ALOGE("Unable to register all android natives\n");
return;
}
/*
* We want to call main() with a String array with arguments in it.
* At present we have two arguments, the class name and an option string.
* Create an array to hold them.
*/
jclass stringClass;
jobjectArray strArray;
jstring classNameStr;
stringClass = env->FindClass("java/lang/String");
assert(stringClass != NULL);
strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
assert(strArray != NULL);
classNameStr = env->NewStringUTF(className);
assert(classNameStr != NULL);
env->SetObjectArrayElement(strArray, 0, classNameStr);
for (size_t i = 0; i < options.size(); ++i) {
jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
assert(optionsStr != NULL);
env->SetObjectArrayElement(strArray, i + 1, optionsStr);
}
/*
* Start VM. This thread becomes the main thread of the VM, and will
* not return until the VM exits.
*/
char* slashClassName = toSlashClassName(className);
jclass startClass = env->FindClass(slashClassName);
if (startClass == NULL) {
ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
/* keep going */
} else {
// 找到ZygoteInit类的static 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 {
/*调用com.android.internal.os.ZygoteInit的main函数,进入Java 世界!*/
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)
ALOGW("Warning: unable to detach main thread\n");
if (mJavaVM->DestroyJavaVM() != 0)
ALOGW("Warning: VM did not shut down cleanly\n");
}
3.3,ZygoteInit.java
ZygoteInit::main() ->ZygoteInit::startSystemServer()->Zygote.forkSystemServer()->Zygote.nativeForkSystemServer(),最终调用fork()函数来创建SystemServer进程。Zygote.java位于frameworks/base/core/java/com/android/internal/os/Zygote.java
4,SystemServer
SystemServer::main()->SystemServer::run()
private void run() {
......
// Initialize native services.
System.loadLibrary("android_servers");
......
// Create the system service manager.
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;
}
......
}
至此,一些关键的本地native services 和 java services都已经被启动。其中,ActivityManagerService是导致Launcher被启动的关键。更多细节,请参考源码!
参考:
<<深入理解Android内核设计思想>> - 林学森