Android的启动过程

       Android从Kernel启动有4个步骤(以android4.2为例)


(1) init进程启动

(2) Native服务启动

(3) System ServerAndroid服务启动

(4) Home启动

总体启动框架图如:

image

 

第一步:initial进程(system/core/init)

    init进程,它是一个由内核启动的用户级进程。内核自行启动(已经被载入内存,开始运行,并已初始化所有的设备驱动程序和数据结构等)之后,就通过启动一个用户级程序init的方式,完成引导进程。init始终是第一个进程.

Init进程一起来就根据init.rc脚本文件建立了几个基本的服务:

  •  servicemanamger
  •  zygote

最后Init并不退出,而是担当起property service的功能。

1.1进程启动

/system/core/Init中的init.c入口:

  1. int main(int argc, char **argv)  
  2. {  
  3.     ...  
  4.     ...  
  5.     /* clear the umask */  
  6.     umask(0);  
  7.   
  8.     /* Get the basic filesystem setup we need put 
  9.      * together in the initramdisk on / and then we'll 
  10.      * let the rc file figure out the rest. 
  11.      */  
  12.         /*创建基本的文件系统*/  
  13.     mkdir("/dev", 0755);  
  14.     mkdir("/proc", 0755);  
  15.     mkdir("/sys", 0755);  
  16.     ...  
  17.     INFO("reading config file\n");  
  18.     /*解析init.rc文件*/  
  19.     init_parse_config_file("/init.rc");  
  20.     ...  
  21.     /* execute all the boot actions to get us started */  
  22.     /*触发需要执行的action*/  
  23.     action_for_each_trigger("init", action_add_queue_tail);  
  24.     ...  
  25.   
  26.     for(;;)  
  27.         {  
  28.             int nr, i, timeout = -1;  
  29.                         /*执行当前action的一个command*/  
  30.             execute_one_command();  
  31.             ...  
  32.             /*loop 处理来自property, signal的event*/  
  33.             for (i = 0; i < fd_count; i++)  
  34.             {  
  35.                 if (ufds[i].revents == POLLIN)  
  36.                 {  
  37.                     if (ufds[i].fd == get_property_set_fd())  
  38.                     handle_property_set_fd();  
  39.                     else if (ufds[i].fd == get_keychord_fd())  
  40.                     handle_keychord();  
  41.                     else if (ufds[i].fd == get_signal_fd())  
  42.                     handle_signal();  
  43.                 }  
  44.             }  
  45.         }  
  46.   
  47.     }  



Init.rcAndroid自己规定的初始化脚本(Android Init Language, system/core/init/readme.txt)

该脚本包含四个类型的声明:

  • Actions
  • Commands
  • Services
  • Options.
1.2 解析init.rc中的service

system/core/init/下的init_parser.c中的 init_parse_config_file("/init.rc")——> parse_config(fn, data)——>parse_new_section(&state, kw, nargs, args)——>parse_service(state, nargs, args)——>  list_add_tail(&service_list, &svc->slist);

添加service到service_list

init_parser.c解析:

  1. static list_declare(service_list);  
  2. static list_declare(action_list);  
  3. static list_declare(action_queue);  


1.3 启动native service

execute_one_command():从action_queue链表上移除头结点(action)

class_start default对应的入口函数,主要用于启动native service

system/core/init/ builtins.c中的:

  1. int do_class_start(int nargs, char **args)  
  2. {  
  3.         /* Starting a class does not start services 
  4.          * which are explicitly disabled.  They must 
  5.          * be started individually. 
  6.          */  
  7.     service_for_each_class(args[1], service_start_if_not_disabled);  
  8.     return 0;  
  9. }  

init_parser.c中的service_for_each_class(...)遍历service_list链表上的所有结点

  1. static void service_start_if_not_disabled(struct service *svc)  
  2. {  
  3.     if (!(svc->flags & SVC_DISABLED)) {  
  4.         service_start(svc, NULL);  
  5.     }  
  6. }  

如果不是disabled就启动service。

init.c中的service_start(...)调用fork()创建进程,调用execve(...)调用执行新的service。


system/core/init/property_service.c中的handle_property_set_fd处理系统属性服务请求,如:service, wlan和dhcp.

property_service服务可以参考Android——SystemProperties的应用

system/core/init/keycords.c中的handle_keychord处理注册在service structure上的keychord,通常是启动service.

system/core/init/signal_handler.c中的handle_signal处理SIGCHLD signal(僵尸进程).

servicemanager是init的子进程

mediaserver是init的子进程

zygote是init的子进程,管理所有虚拟机实例

system_server和所有的java应用程序是zygote的子进程。system_server负责管理系统服务。




第二步 Zygote

Servicemanager 是init通过init.rc加载的第一个进程,接下来启动了zygote

Servicemanagerzygote进程就奠定了Android的基础。Zygote这个进程起来才会建立起真正的Android运行空间,初始化建立的Service都是Navtive service..rc脚本文件中zygote的描述:

service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server

所以Zygoteframeworks/base/cmds/app_main.cpp的main()开始。

其中:

  1. AppRuntime runtime;  

初始化运行时间.

  1. if (zygote) {  
  2.      runtime.start("com.android.internal.os.ZygoteInit",  
  3.              startSystemServer ? "start-system-server" : "");  
  4.  }  

runtime调用start方法,但是AppRuntime没有此方法,而在其父类AndroidRuntime

  1. class AppRuntime : public AndroidRuntime  

所以调用AndroidRuntime的start方法:

  1. void AndroidRuntime::start(const char* className, const char* options)  
  2. {  
  3.     ALOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",  
  4.             className != NULL ? className : "(unknown)");  
  5.   
  6.   
  7.     blockSigpipe();  
  8. ...  
  9.   /* start the virtual machine */  
  10.     JNIEnv* env;  
  11.     if (startVm(&mJavaVM, &env) != 0) {  
  12.         return;  
  13.     }  
  14.     onVmCreated(env);  
  15.   
  16.   
  17.     /* 
  18.      * Register android functions. 
  19.      */  
  20.     if (startReg(env) < 0) {  
  21.         ALOGE("Unable to register all android natives\n");  
  22.         return;  
  23.     }  
  24. ...  
  25.      env->CallStaticVoidMethod(startClass, startMeth, strArray);  
  26. ...  
  27. }  

调用startVM(...)新建VM:

  1. int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv)  
  2. {  
  3.     int result = -1;  
  4.     JavaVMInitArgs initArgs;  
  5. ...  
  6.  /* 
  7.      * Initialize the VM. 
  8.      * 
  9.      * The JavaVM* is essentially per-process, and the JNIEnv* is per-thread. 
  10.      * If this call succeeds, the VM is ready, and we can start issuing 
  11.      * JNI calls. 
  12.      */  
  13.     if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {  
  14.         ALOGE("JNI_CreateJavaVM failed\n");  
  15.         goto bail;  
  16.     }  
  17. ...  
  18. }  

其中调用到的是JNI_CreateJavaVM(...)创建VM.

onVmCreated(env)为空函数,没用!


startReg()函数用于注册JNI接口:

  1. /* 
  2.  * Register android native functions with the VM. 
  3.  */  
  4. /*static*/ int AndroidRuntime::startReg(JNIEnv* env)  
  5. {  
  6.     /* 
  7.      * This hook causes all future threads created in this process to be 
  8.      * attached to the JavaVM.  (This needs to go away in favor of JNI 
  9.      * Attach calls.) 
  10.      */  
  11.     androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);  
  12.   
  13.     ALOGV("--- registering native functions ---\n");  
  14.   
  15.     /* 
  16.      * Every "register" function calls one or more things that return 
  17.      * a local reference (e.g. FindClass).  Because we haven't really 
  18.      * started the VM yet, they're all getting stored in the base frame 
  19.      * and never released.  Use Push/Pop to manage the storage. 
  20.      */  
  21.     env->PushLocalFrame(200);  
  22.   
  23.     if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {  
  24.         env->PopLocalFrame(NULL);  
  25.         return -1;  
  26.     }  
  27.     env->PopLocalFrame(NULL);  
  28.   
  29.     //createJavaThread("fubar", quickTest, (void*) "hello");  
  30.   
  31.     return 0;/fameworks/base/core/java/com/android/internal/os/ZygoteInit.java  
  32. }  


AndroidRuntime的start()方法最后调用
  1. env->CallStaticVoidMethod(startClass, startMeth, strArray)  

调用/fameworks/base/core/java/com/android/internal/os/ZygoteInit.java中的main(...)函数.

  1.     public static void main(String argv[]) {  
  2.         try {  
  3.             // Start profiling the zygote initialization.  
  4.             SamplingProfilerIntegration.start();  
  5.   
  6.   
  7.             registerZygoteSocket();  
  8. ...  
  9.           preload();  
  10. ...  
  11.           if (argv[1].equals("start-system-server")) {  
  12.                 startSystemServer();  
  13.             } else if (!argv[1].equals("")) {  
  14.                 throw new RuntimeException(argv[0] + USAGE_STRING);  
  15.             }  
  16. ...  
  17. }  

  • registerZygoteSocket();//来注册Socket的Listen端口,用来接受请求
    1. /** 
    2.    * Registers a server socket for zygote command connections 
    3.    * 
    4.    * @throws RuntimeException when open fails 
    5.    */  
    6.   private static void registerZygoteSocket() {  
    7.       if (sServerSocket == null) {  
    8.           int fileDesc;  
    9.           try {  
    10.               String env = System.getenv(ANDROID_SOCKET_ENV);  
    11.               fileDesc = Integer.parseInt(env);  
    12.           } catch (RuntimeException ex) {  
    13.               throw new RuntimeException(  
    14.                       ANDROID_SOCKET_ENV + " unset or invalid", ex);  
    15.           }  
    16.   
    17.           try {  
    18.               sServerSocket = new LocalServerSocket(  
    19.                       createFileDescriptor(fileDesc));  
    20.           } catch (IOException ex) {  
    21.               throw new RuntimeException(  
    22.                       "Error binding to local socket '" + fileDesc + "'", ex);  
    23.           }  
    24.       }  
    25.   }  

       preload()主要进行预加载类和资源,以加快启动速度。preload的class列表保存在/frameworks/base/preloaded-classes文件中
    1. static void preload() {  
    2.         preloadClasses();  
    3.         preloadResources();  
    4.     }  

    startSystemServer(),fork进程:

  1. int pid;  
  2.   
  3.      try {  
  4.          parsedArgs = new ZygoteConnection.Arguments(args);  
  5.          ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);  
  6.          ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);  
  7.   
  8.          /* Request to fork the system server process */  
  9.          pid = Zygote.forkSystemServer(  
  10.                  parsedArgs.uid, parsedArgs.gid,  
  11.                  parsedArgs.gids,  
  12.                  parsedArgs.debugFlags,  
  13.                  null,  
  14.                  parsedArgs.permittedCapabilities,  
  15.                  parsedArgs.effectiveCapabilities);  
  16.      } catch (IllegalArgumentException ex) {  
  17.          throw new RuntimeException(ex);  
  18.      }  


经过这几个步骤,Zygote就建立好了,利用Socket通讯,接收ActivityManangerService的请求



第三步 System Server

Zygote上fork的systemserver进程入口在/frameworks/base/services/java/com/android/server/SystemServer.java的main(...)Android的所有服务循环框架都是建立SystemServer上。在SystemServer.java中看不到循环结构。

  1. public static void main(String[] args) {  
  2.    ...  
  3.     ...  
  4.   
  5.        System.loadLibrary("android_servers");  
  6.        init1(args);  
  7.    }  

加载一个叫android_servers的本地库,他提供本 地方法的接口(源程序在framework/base/services/jni/目录中)。然后调用本地方法设置服务。具体执行设置的代码在 frameworks/base/cmds/system_server/library/system_init.cpp中。

Init1()是在Native空间实现的(com_andoird_server_SystemServer.cpp

JNI如下:

  1. static JNINativeMethod gMethods[] = {  
  2.     /* name, signature, funcPtr */  
  3.     { "init1""([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 },  
  4. };  

  1. static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)  
  2. {  
  3.     system_init();  
  4. }  

system_init.cpp中的system_init()实现如下:

  1. extern "C" status_t system_init()  
  2. {  
  3. ...  
  4. property_get("system_init.startsurfaceflinger", propBuf, "1");  
  5. if (strcmp(propBuf, "1") == 0) {  
  6. // Start the SurfaceFlinger  
  7. SurfaceFlinger::instantiate();  
  8. }  
  9.   
  10. property_get("system_init.startsensorservice", propBuf, "1");  
  11. if (strcmp(propBuf, "1") == 0) {  
  12. // Start the sensor service  
  13. SensorService::instantiate();  
  14. }  
  15. ...  
  16. ALOGI("System server: starting Android services.\n");  
  17. JNIEnv* env = runtime->getJNIEnv();  
  18. if (env == NULL) {  
  19. return UNKNOWN_ERROR;  
  20. }  
  21. jclass clazz = env->FindClass("com/android/server/SystemServer");  
  22. if (clazz == NULL) {  
  23. return UNKNOWN_ERROR;  
  24. }  
  25. jmethodID methodId = env->GetStaticMethodID(clazz, "init2""()V");  
  26. if (methodId == NULL) {  
  27. return UNKNOWN_ERROR;  
  28. }  
  29. env->CallStaticVoidMethod(clazz, methodId);  
  30.   
  31.   
  32. ALOGI("System server: entering thread pool.\n");  
  33. ProcessState::self()->startThreadPool();  
  34. IPCThreadState::self()->joinThreadPool();  
  35. ALOGI("System server: exiting thread pool.\n");  
  36.   
  37.   
  38. return NO_ERROR;  
  39. }  

可以看到等初始化传感器,视频,音频等服务后通过env->CallStaticVoidMethod(clazz, methodId)回调到了SystemServer的init2().

SystemServer.java有这么一段话:

  1. /** 
  2.     * This method is called from Zygote to initialize the system. This will cause the native 
  3.     * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back 
  4.     * up into init2() to start the Android services. 
  5.     */  
  6.    native public static void init1(String[] args);  
init2会在init1的实现中回调到!

system_init()开启了线程池,join_threadpool() 将当前线程挂起,等待binder的请求,启动了循环状态。


SystemServer.javainit2()建立了Android主要的系统服务(WindowManagerServer(Wms)、ActivityManagerSystemService(AmS)、PackageManagerServer(PmS)......).

  1. public static final void init2() {  
  2.         Slog.i(TAG, "Entered the Android system server!");  
  3.         Thread thr = new ServerThread();  
  4.         thr.setName("android.server.ServerThread");  
  5.         thr.start();  
  6.     }  
这个init2()建立了一个线程 thr,ServerThread线程 中New ServiceAddService来建立服务:

  1. class ServerThread extends Thread {  
  2.     private static final String TAG = "SystemServer";  
  3.     private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";  
  4.     private static final String ENCRYPTED_STATE = "1";  
  5.   
  6.   
  7.     ContentResolver mContentResolver;  
  8. ...  
  9.             Slog.i(TAG, "Entropy Mixer");  
  10.             ServiceManager.addService("entropy"new EntropyMixer());  
  11.   
  12.   
  13.             Slog.i(TAG, "Power Manager");  
  14.             power = new PowerManagerService();  
  15.             ServiceManager.addService(Context.POWER_SERVICE, power);  
  16.   
  17.   
  18.             Slog.i(TAG, "Activity Manager");  
  19.             context = ActivityManagerService.main(factoryTest);  
  20. ...  
  21.         // We now tell the activity manager it is okay to run third party  
  22.         // code.  It will call back into us once it has gotten to the state  
  23.         // where third party code can really run (but before it has actually  
  24.         // started launching the initial applications), for us to complete our  
  25.         // initialization.  
  26.         ActivityManagerService.self().systemReady(new Runnable() {  
  27.             public void run() {  
  28.                 Slog.i(TAG, "Making services ready");  
  29.   
  30.   
  31.                 if (!headless) startSystemUi(contextF);  
  32.                 try {  
  33.                     if (mountServiceF != null) mountServiceF.systemReady();  
  34.                 } catch (Throwable e) {  
  35.                     reportWtf("making Mount Service ready", e);  
  36.                 }  
  37. ...  
  38. }  


执行完systemReady()后,会相继启动相关联服务的systemReady()函数,完成整体初始化。

SystemServer是Android系统的一个核心进程,它是由zygote进程创建的,因此在android的启动过程中位于zygote之后。android的所有服务循环都是建立在 SystemServer之上的。在SystemServer中,将可以看到它建立了android中的大部分服务,并通过ServerManager的add_service方法把这些服务加入到了ServiceManager的svclist中。从而完成ServcieManager对服务的管理。

APK应用中能够直接交互的大部分系统服务都在该进程中运 行,常见的比如WindowManagerServer(Wms)、ActivityManagerSystemService(AmS)、 PackageManagerServer(PmS)等,这些系统服务都是以一个线程的方式存在于SystemServer进程中。



第三步 Home启动


上面的ServerThread调用到ActivityManagerService的systemReady()然后回调到/frameworks/base/services/java/com/android/server/am/ActivityManagerServcie.java的systemReady(...).

  1. public final class ActivityManagerService extends ActivityManagerNative  
  2.         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {  
  3.     ......  
  4.   
  5.     public void systemReady(final Runnable goingCallback) {  
  6.         ......  
  7.   
  8.         synchronized (this) {  
  9.             ......  
  10.   
  11.             mMainStack.resumeTopActivityLocked(null);  
  12.         }  
  13.     }  
  14.   
  15.     ......  
  16. }  

调用/frameworks/base/services/java/com/android/server/am/ActivityStack.java中:

  1.  final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {  
  2.  // Find the first activity that is not finishing.  
  3.         ActivityRecord next = topRunningActivityLocked(null);  
  4. ...  
  5.   
  6.         if (next == null) {  
  7.               
  8.              Log.d(TAG,"jscese start Launcher");  
  9.             // There are no more activities!  Let's just start up the  
  10.             // Launcher...  
  11.             if (mMainStack) {  
  12.                 ActivityOptions.abort(options);  
  13.                 return mService.startHomeActivityLocked(mCurrentUser);  
  14.             }  
  15.         }  
  16. ...  
  17. }  

next为当前系统Activity堆栈最顶端的Activity,如果没有,next == null那么就启动home!

回调到ActivityManagerServcie.java的:

  1. boolean startHomeActivityLocked(int userId) {  
  2. ...  
  3.         Intent intent = new Intent(  
  4.             mTopAction,  
  5.             mTopData != null ? Uri.parse(mTopData) : null);  
  6.         intent.setComponent(mTopComponent);  
  7.         if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {  
  8.             intent.addCategory(Intent.CATEGORY_HOME);  
  9.         }  
  10.         ActivityInfo aInfo =  
  11.             resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);  
  12.         if (aInfo != null) {  
  13.             intent.setComponent(new ComponentName(  
  14.                     aInfo.applicationInfo.packageName, aInfo.name));  
  15.               
  16.             Log.d(TAG,"jscese first packageName==   "+aInfo.applicationInfo.packageName);  
  17.               
  18.             // Don't do this if the home app is currently being  
  19.             // instrumented.  
  20.             aInfo = new ActivityInfo(aInfo);  
  21.             aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);  
  22.             ProcessRecord app = getProcessRecordLocked(aInfo.processName,  
  23.                     aInfo.applicationInfo.uid);  
  24.             if (app == null || app.instrumentationClass == null) {  
  25.                 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);  
  26.                 mMainStack.startActivityLocked(null, intent, null, aInfo,  
  27.                         nullnull0000nullfalsenull);  
  28.             }  
  29.         }  
  30.   
  31.   
  32.         return true;  
  33.     }  

首先创建一个CATEGORY_HOME类型的Intent,然后通过Intent.resolveActivityInfo函数向PackageManagerService查询Category类型为HOME的Activity!

launcher的AndroidManifest.xml文件中可见:

  1.   <activity  
  2.             android:name="com.android.mslauncher.LauncherActivity"  
  3.  ...  
  4.   
  5.             <intent-filter>  
  6.                 <action android:name="android.intent.action.MAIN" />  
  7.                 <category android:name="android.intent.category.HOME" />  
  8.                 <category android:name="android.intent.category.DEFAULT" />  
  9.                 <category android:name="android.intent.category.MONKEY"/>  
  10.             </intent-filter>  
  11.         </activity>  
  12. ...  

跑到ActivityStack.java的:

  1.     final int startActivityLocked(IApplicationThread caller,  
  2.             Intent intent, String resolvedType,  
  3.             Uri[] grantedUriPermissions,  
  4.             int grantedMode, ActivityInfo aInfo, IBinder resultTo,  
  5.   
  6.         ......  
  7.   
  8.   
  9.         ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,  
  10.             intent, resolvedType, aInfo, mService.mConfiguration,  
  11.             resultRecord, resultWho, requestCode, componentSpecified);  
  12.   
  13.   
  14.         ......  
  15.   
  16.   
  17.           err = startActivityUncheckedLocked(r, sourceRecord, startFlags, true, options);  
  18. ...  
  19.     }  

往后走就是启动一个activity的流程了,最终启动的是launcher的onCreate方法!

至此启动完成!

此博文图片模型来自http://blog.csdn.net/maxleng/article/details/5508372

撰写不易,转载请注明出处http://blog.csdn.net/jscese/article/details/17115395

相关链接https://guolei1130.github.io/2017/01/02/android%E5%BA%94%E7%94%A8%E8%BF%9B%E7%A8%8B%E6%98%AF%E5%A6%82%E4%BD%95%E5%90%AF%E5%8A%A8%E7%9A%84/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值