最近新发现一个查看aosp源码的网站https://cs.android.com/android,记录一下 追踪android启动的大致顺序。开整;
init.rc:zygote-start
# It is recommended to put unnecessary data/ initialization from post-fs-data
# to start-zygote in device'sinit.rcto unblock zygote start.
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
start zygote_secondary
on zygote-start && property:ro.crypto.state=unsupported
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
start zygote_secondary
on zygote-start && property:ro.crypto.state=encrypted && property:ro.crypto.type=file
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
start zygote_secondary
....
经过如上的步骤,初始化android依赖的内核环境.
然后到了 app_main.cpp ,来到c++的main方法了
int main (int argc,char*const argv[])
{
// We're in zygote mode.
.....
maybeCreateDalvikCache();
if(startSystemServer) {
args.add(String8("start-system-server"));
}
c
if(zygote) {
调用AndroidRuntime的 start方法,
runtime.start("com.android.internal.os.ZygoteInit",args,zygote);
}elseif(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.");
}
}
看下 AndroidRuntime.cpp 里面 做了啥?
voidAndroidRuntime::start(constchar*className,constVector
{
省略若干。。。
constchar*rootDir=get env("ANDROID_ROOT");
if(rootDir==NULL) {
rootDir="/system";
);
/* start the virtual machine */
开启虚拟机;
JniInvocationjni_invocation;
jni_invocation.Init(NULL);
JNIEnv*env;
//拿到 jni桥梁 JNIEnv指针。
if(startVm(&mJavaVM, &env,zygote,primary_zygote) !=0) {
return;
}
onVmCreated(env);
拿到java层静态main方法 调用;从这开始就进入java的main方法了,而上方的 className 根据传参过来的确定是两个:ZygoteInit,RuntimeInit
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{
env->CallStaticVoidMethod(startClass,startMeth,strArray);
然后就来带分别的 ZygoteInit.java和RuntimeInit.java 看 main方法了
/**
* Initialize the native state of the Zygote. This inclues
* - Fetching socket FDs from the environment
* - Initializing security properties
* - Unmounting storage as appropriate
* - Loading necessary performance profile information
*
* @param isPrimary True if this is the zygote process, false if it is zygote_secondary
*/
main{
Zygote.initNativeState(isPrimaryZygote);
ZygoteHooks.stopZygoteNoThreadCreation();
zygoteServer=newZygoteServer(isPrimaryZygote);
if(startSystemServer) {
Runnabler=forkSystemServer(abiList,zygoteSocketName,zygoteServer);
r.run();
// The select loop returns early in the child process after a fork and
// loops forever in the zygote.
// The select loop returns early in the child process after a fork and
// loops forever in the zygote.
caller=zygoteServer.runSelectLoop(abiList);
}
1.static void initNativeState(booleanisPrimary) {
nativeInitNativeState(isPrimary);
}
protected static native void nativeInitNativeState(boolean isPrimary);
调用c++ com_android_internal_os_Zygote.cpp nativeInitNativeState方法
static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv*env,jclass,
jboolean is_primary) {
/*
* Obtain file descriptors created by init from the environment.
*/
。。。。。。
}
2.如果系统服务开启成功,根据zygote fork一个进程
if(startSystemServer) {
Runnabler=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;
}
}
当中runnable 如下
/**
* Finish remaining work for the newly forked system server process.
完成新fork的系统服务进程的剩余工作
*/
privatestatic Runnable handleSystemServerProcess(ZygoteArgumentsparsedArgs) {
......
通过命令启动systemserver服务
/* 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,1021,1023,"
+"1024,1032,1065,3001,3002,3003,3006,3007,3009,3010,3011",
"--capabilities="+capabilities+","+capabilities,
"--nice-name=system_server",
"--runtime-args",
"--target-sdk-version="+VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
"com.android.server.SystemServer",
};
}
大致了解了下 zygoteInit的工作,然后进入RuntimeInit
publicstaticfinalvoidmain(String[]argv) {
......
commonInit();
/*
* Now that we're running in interpreted code, call back into native code
* to run the system.
*/
nativeFinishInit();
}
看 commonInit ,主要 设置 Handlers,Logger
protectedstaticfinalvoid commonInit() {
if(DEBUG)Slog.d(TAG,"EnteredRuntimeInit!");
/*
* set handlers; these apply to all threads in the VM. Apps can replace
* the default handler, but not the pre handler.
*/
LoggingHandlerloggingHandler=newLoggingHandler();
RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
Thread.setDefaultUncaughtExceptionHandler(newKillApplicationHandler(loggingHandler));
/*
* Install a time zone supplier that uses the Android persistent time zone system property.
*/
RuntimeHooks.setTimeZoneIdSupplier(() ->SystemProperties.get("persist.sys.timezone"));
/*
* Sets handler for java.util.logging to use Android log facilities.
* The odd "new instance-and-then-throw-away" is a mirror of how
* the "java.util.logging.config.class" system property works. We
* can't use the system property here since the logger has almost
* certainly already been initialized.
*/
LogManager.getLogManager().reset();
new AndroidConfig();
......
}
来到我们熟悉的Logger
public AndroidConfig() {
super();
try{
LoggerrootLogger=Logger.getLogger("");
rootLogger.addHandler(newAndroidHandler());
rootLogger.setLevel(Level.INFO);
// Turn down logging in Apache libraries.
Logger.getLogger("org.apache").setLevel(Level.WARNING);
}catch(Exceptionex) {
ex.printStackTrace();
}
}
;
来到"com.android.server.SystemServer",
main(String[]args) {
newSystemServer().run();
}
run(){
......
// The system server should never make non-oneway calls
Binder.setWarnOnBlocking(true);
......
// Increase the number of binder threads in system_server
BinderInternal.setMaxThreads(sMaxBinderThreads);
//主线程的looper创建
// Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS,SLOW_DELIVERY_THRESHOLD_MS);
// Initialize the system context.
android context 的诞生
createSystemContext();
......
// Create the system service manager.
mSystemServiceManager=newSystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime,mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class,mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.start();
......
// Start services.
try{
t.traceBegin("StartServices");
startBootstrapServices(t);
startCoreServices(t);
startOtherServices(t);
}
// Loop forever.
Looper.loop();
}
createSystemContext() {
ActivityThreadactivityThread=ActivityThread.systemMain();
mSystemContext=activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
finalContextsystemUiContext=activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
startBootStrapService(){
ams....
startOtherService(){
wms...
}
之后就是各个系统service的启动 过程了;