Android Start-Up Process Analysis (11) zygote Start-up

Source: Internet
Author: User
Tags strcmp

#############################################

This article is extremely ice original, reproduced please indicate the source

#############################################

The previous article spent a lot of time explaining how the init process can parse init.rc, and how to perform some of the system's services.

So, how did we say zygote started? Zygote is also the specific responsibility of what work?

In this paper, we will explore the matter.

Zygote has the following description in Inir.rc:

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
We can simply analyze these two words,

Service Zygote/system/bin/app_process-xzygote/system/bin--zygote--start-system-server

Class Main

This is to say that zygote belongs to the class of Main.

Zygote is a service, the name of the service called Zygote. The command executed at startup is app_process, and the parameter passed is-xzygote/system/bin--zygote--start-system-server

So, according to the theory we analyzed earlier, let's go and see what app_process is.
First we go to the framework directory, in Base/cmds/app_process, we see the makefile of generating app_process.

Include $ (clear_vars) local_src_files:=         app_main.cpplocal_shared_libraries: =         libcutils         libutils         Liblog         libbinder         libandroid_runtimelocal_module:= app_processlocal_multilib: = bothlocal_module_stem_32: = app_process32local_module_stem_64: = App_process64include $ (build_executable)
We can see that app_process was executed to generate an application.

Imagine that the zygote service should be running all the time, but if the ADB shell goes to see PS, and can't find app_process, this command runs all the time.

What is this for?

First, we intercept a section from the main function of app_process.

    while (I < ARGC) {        const char* arg = argv[i++];        if (strcmp (ARG, "--zygote") = = 0) {//If the parameter passed in from Init.rc is--zygote, it must be in this judgment            zygote = true;  Set ZYGOTE to True            nicename = zygote_nice_name;  Set Nicename to Zygote_nice_name set to Zygote        } else if (strcmp (ARG, "--start-system-server") = = 0) {// If it is to start start-system-server,            startsystemserver = true;//will set Startsystemserver to True        } else if (strcmp (ARG, "-- Application ") = = 0) {  //             application = true;        } else if (strncmp (ARG,"--nice-name= ", n) = = 0) {            Nicen Ame.setto (arg +);        } else if (strncmp (ARG, "--", 2)! = 0) {            classname.setto (ARG);            break;        } else {-            I.;            break;        }    }

And how can these parameters be used?

Then look at the following code, how it is used.

    if (!nicename.isempty ()) {  //If Nicename is not empty        runtime.setargv0 (nicename.string ());        Set_process_name (Nicename.string ()); Call this function to set the name of the process to zygote    }    if (zygote) {///zygote must be True        Runtime.start (" Com.android.internal.os.ZygoteInit ", args); We entered this judgment    } else if (className) {        Runtime.start ("Com.android.internal.os.RuntimeInit", args);    } 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 ten;    }
We can see that runtime is calling the method of start to do this zygote start work, then we this runtime is the call to which side of the start?

In our current appruntime, there is no implementation of the related start function.

Let's go to his father's class and have a look.

Class Appruntime:public Androidruntime
What about the Androidruntime? Is there any way to start?

Androidruntime implementations are located at: Frameworks/base/core/jni/AndroidRuntime.cpp

We found the way to start from the inside.

951void Androidruntime::start (const char* className, const vector<string8>& options) 952{953 alogd (">> >>>> START%s uid%d <<<<<<\n ", 954 className! = NULL?      ClassName: "(unknown)", Getuid ()) 955956 static const STRING8 startsystemserver ("Start-system-server"); 957958/*959 * ' Startsystemserver = = True ' means runtime is obsolete and not run from960 * init.rc anymore, so we print out th E boot Start Event here.961 */962 for (size_t i = 0; i < options.size (); ++i) {963 if (options[i] = = Star Tsystemserver) {964/* track our progress through the boot sequence */965 const int Log_boot_progress_ START = 3000;966 Log_event_long (Log_boot_progress_start, ns2ms (SystemTime (system_time_monotonic))); 967} 968}969970 const char* RootDir = getenv ("Android_root"); 971 if (RootDir = = NULL) {972 RootDir = "/system"            ; 973 if (!hasdir ("/system")) {974Log_fatal ("No root directory specified, and/android does not exist.");  975 return;976}977 setenv ("Android_root", RootDir, 1); 978}979980//const char* kernelhack = getenv ("Ld_assume_kernel"); 981//alogd ("Found ld_assume_kernel= '%s ' \ n", kernelhack); 982983/* Start the virtual m Achine */984 jniinvocation jni_invocation;985 jni_invocation.    Init (NULL); 986 jnienv* env;987 if (STARTVM (&AMP;MJAVAVM, &env)! = 0) {//Create virtual machine 988 return;989}990 Onvmcreated (env); 991992/*993 * Register Android functions.994 */995 if (Startreg (env) < 0) {//Register JNI Method 996 Aloge ("Unable to register all Android natives\n"); 997 return;998}9991000/*1001 * We want  To call Main () with a String array with arguments in it.1002 * At present we have both arguments, the class name and an  Option string.1003 * Create an array to hold them.1004 */1005 jclass stringclass; Class object 1006 Jobjectarray straRray; Corresponding Objectarray object 1007 jstring classnamestr; A string10081009 Stringclass = Env->findclass ("java/lang/string"); The class1010 assert (stringclass! = NULL) of string is found first, 1011 Strarray = Env->newobjectarray (options.size () + 1, Strin  Gclass, NULL);  New has a ObjectArray1012 assert (strarray! = NULL); 1013 Classnamestr = Env->newstringutf (className); Convert classname to UTF8 type 1014 assert (classnamestr! = NULL); 1015 Env->setobjectarrayelement (Strarray, 0, Classnamest  R); The first element of the set Objectarray is classname10161017 for (size_t i = 0; i < options.size (); ++i) {//The subsequent parameters are converted to Strarray sequentially The array of 1018 jstring Optionsstr = Env->newstringutf (Options.itemat (i). String ()); 1019 assert (optionsstr! = NUL  L); 1020 Env->setobjectarrayelement (Strarray, i + 1, optionsstr); 1021}10221023/*1024 * Start VM. This thread becomes the main thread of the VM, and will1025 * not return until the VM exits.1026 */1027 char* s LashclassName = Toslashclassname (className); Convert classname to/form 1028 Jclass Startclass = Env->findclass (slashclassname); Look for this class 1029 if (Startclass = = NULL) {//If not found, we will return NULL1030 Aloge ("JAVAVM Unable to locate class '%s ' \ n", SL Ashclassname); 1031/* Keep going */1032} else {1033 Jmethodid Startmeth = Env->getstaticmethodid (star   Tclass, "main", 1034 "([ljava/lang/string;) V"); Get the main function of this class we are looking for 1035 if (Startmeth = = NULL) {1036 Aloge ("JAVAVM Unable to find main () in '%s ' \ n", c Lassname); 1037/* Keep going */1038} else {1039 Env->callstaticvoidmethod (Startclass, STA Rtmeth, Strarray); To execute the method of this class's main function. 10401041#if 01042 if (Env->exceptioncheck ()) 1043 threadexituncaughtexception (env); 1044#ENDIF1  045}1046}1047 Free (slashclassname); free10481049 alogd ("shutting down vm\n"); 1050 if (Mjavavm->detachcurrentthread ()! = JNI_OK) 1051 ALOGW("Warning:unable to detach main thread\n"); 1052 if (MJAVAVM-&GT;DESTROYJAVAVM ()! = 0) 1053 ALOGW ("Warning:vm di D Not shut down cleanly\n "); 1054}
To look at the main function of Zygoteinit according to the parameters just passed

648 public static void Main (String argv[]) {649 try {650//Start profiling the zygote initialization .651 Samplingprofilerintegration.start (); 652653 boolean startsystemserver = false;654 Str ing socketname = "zygote"; 655 String abilist = null;656 for (int i = 1; i < argv.length; i++) {65  7 if ("Start-system-server". Equals (Argv[i])) {658 Startsystemserver = true;  Startsystemserver is true659} else if (Argv[i].startswith (Abi_list_arg)) {660 abilist =                    Argv[i].substring (Abi_list_arg.length ()); 661} else if (Argv[i].startswith (Socket_name_arg)) {662 Socketname = argv[i].substring (Socket_name_arg.length ()); 663} else {664 thro            W New runtimeexception ("Unknown command line argument:" + argv[i]); 665}666}667668          if (abilist = = null) {669      throw new RuntimeException ("No ABI list supplied."); 670}671672 registerzygotesocket (socketname); A socket was registered to communicate with other applications in the system 673 eventlog.writeevent (log_boot_progress_preload_start,674 Syst Emclock.uptimemillis ()); 675 preload (); Pre-load some resources 676 eventlog.writeevent (log_boot_progress_preload_end,677 systemclock.uptimemillis ()); 678679//Finish profiling the zygote initialization.680 samplingprofilerintegration.writezygotesnap Shot (); 681682//do a initial GC to clean up after startup683 GC (); 684685//Disable tra Cing So, forked processes do not inherit stale tracing tags from686//zygote.687 Trace.settraci                Ngenabled (false); 688689 if (startsystemserver) {///If Startsystemserver is true, we will start systemServer690 Startsystemserver (Abilist, socketname); 691}692693 log.i (TAG, "Accepting command Socket connections "); 694 Runselectloop (Abilist);            A loop into Select, which responds to requests from other applications 695696 closeserversocket (); 697} catch (Methodandargscaller caller) {698 Caller.run (); 699} catch (RuntimeException ex) {LOG.E (TAG, "Zygote died with exception", ex) ; 701 Closeserversocket (); 702 Throw ex;703}704}
So, finally, let's summarize the zygote.

First zygote creates the Appruntime object and calls his start. Subsequent activities are controlled by Appruntime.

Then call STARTVM to create the virtual machine, call Startreg to register the JNI function

Zygoteinit into the world of Java through JNI calls

Call Registerzygotesocket to respond to future generations ' requests while calling the preload function to preload the resource

Call Startsystemserver for system-initiated work

Having completed the start-up of the Java world, it changed into a select loop to handle subsequent requests.







Android Start-Up Process Analysis (11) zygote Start-up

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.