Android System Startup Research 1

Source: Internet
Author: User
Tags strcmp

The Android system is huge, and it takes a long time to figure out how the system works. The system startup section looked several times but did not summarize, today briefly summarizes.

The first focus of Android is to start the zygote process, which originates from Init.rc's read, zygote process is primarily used to hatch new apps and also includes a large number of services to start Android Systemservice

I study the source code is 4.1, the other version may be slightly different.


The init.rc file is an important entry for the boot configuration, and init.c will read the file, and the core related process will open.

/android41/system/core/init/init.c

The point is to parse the Init.rc file and start processing the relevant instructions. Find the main entrance and post some code

    mkdir ("/dev", 0755);    mkdir ("/proc", 0755);    mkdir ("/sys", 0755);    Mount ("Tmpfs", "/dev", "Tmpfs", Ms_nosuid, "mode=0755");    mkdir ("/dev/pts", 0755);    mkdir ("/dev/socket", 0755);    Mount ("Devpts", "/dev/pts", "Devpts", 0, NULL);    Mount ("proc", "/proc", "Proc", 0, NULL);        Mount ("Sysfs", "/sys", "Sysfs", 0, NULL); /* indicate that booting are in progress to background FW loaders, etc */close (open ("/dev/.booting", O_wronly |        o_creat, 0000));         /* We must has some place other than/to create the * device nodes for kmsg and NULL, otherwise we won ' t         * Be able to remount/read-only later on.         * Now that Tmpfs are mounted on/dev, we can actually * talk to the outside world.    */Open_devnull_stdio ();    Klog_init ();    Property_init ();    Get_hardware_name (Hardware, &revision);    Process_kernel_cmdline (); #ifdef have_selinux INFO ("Loading SELINUX policy\n"); Selinux_load_policy (); #endif Is_charger =!strcMP (Bootmode, "charger");    INFO ("Property init\n");    if (!is_charger) property_load_boot_defaults ();    INFO ("reading config file\n"); Init_parse_config_file ("/init.rc"); Read RC file

The front is the initialization of the critical directory and Mount file system, System hardware devices, system properties and so on.

Find android41/system/core/rootdir/init.rc

This file also includes, ServiceManager IPC Service Manager launch, Surfaceflinger Image service, Bootanim start animation, media media services, etc.

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

App_process includes 2 things zygote and system server startup

App_process boot code in frameworks/base/cmds/app_process/app_main.cpp
The main code in main.

    while (I < ARGC) {const char* arg = argv[i++];        if (!parentdir) {parentdir = arg;            } else if (strcmp (ARG, "--zygote") = = 0) {zygote = true;        Nicename = "Zygote";        } else if (strcmp (ARG, "--start-system-server") = = 0) {Startsystemserver = true;        } else if (strcmp (ARG, "--application") = = 0) {application = true;        } else if (strncmp (ARG, "--nice-name=", "n") = = 0) {nicename = arg + 12;            } else {className = arg;        Break        }} if (Nicename && *nicename) {setArgv0 (argv0, nicename);    Set_process_name (Nicename);    } Runtime.mparentdir = Parentdir; if (zygote) {<strong>runtime.start ("Com.android.internal.os.ZygoteInit", Startsystemserver? "Start-system-server": "");</strong>} else if (className) {//remainder of args get passed to startup C Lass Main () RUNTIME.MClassName = ClassName;        RUNTIME.MARGC = Argc-i;        RUNTIME.MARGV = argv + i; Runtime.start ("Com.android.internal.os.RuntimeInit", application?)    "Application": "Tool");        } 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; }

The front is to parse the incoming parameters to determine whether to start zygote and Runtimeinit,appruntime is the Android DVM Launcher object,

The startup of the virtual machine in/android41/frameworks/base/core/jni/androidruntime.cpp contains a lot of initialization such as heap size memory allocation, and so on, here for the time being.

First look at the Zygoteinit code

/android41/frameworks/base/core/java/com/android/internal/os/Zygoteinit.java

    public static void Main (String argv[]) {try {//Start profiling the zygote initialization.            Samplingprofilerintegration.start ();            Registerzygotesocket ();            Eventlog.writeevent (Log_boot_progress_preload_start, Systemclock.uptimemillis ());            Preload ();            Eventlog.writeevent (Log_boot_progress_preload_end, Systemclock.uptimemillis ());            Finish profiling the zygote initialization.            Samplingprofilerintegration.writezygotesnapshot ();            Do a initial GC to clean up after startup GC (); If requested, start system server directly from Zygote if (argv.length! = 2) {throw new Runt            Imeexception (Argv[0] + usage_string);            } if (Argv[1].equals ("Start-system-server")) {startsystemserver (); } else if (!argv[1].equals ("")) {throw new RuntimeException (Argv[0] + usage_string);            } log.i (TAG, "accepting command socket connections");            if (Zygote_fork_mode) {runforkmode ();            } else {runselectloopmode ();        } closeserversocket ();        } catch (Methodandargscaller caller) {Caller.run ();            } catch (RuntimeException ex) {LOG.E (TAG, "Zygote died with exception", ex);            Closeserversocket ();        Throw ex; }    }

Zygote is mainly hatching app, by starting a socketserver to accept the app launch request, the app is launched by Activitymanagerservice to send socket communications.

Here's a look at the boot Systemservice

    private static Boolean Startsystemserver () throws Methodandargscaller, RuntimeException {/* hardcod Ed command line to start the system server */String args[] = {"--setuid=1000", "--setgid=10            XX ","--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007 ", "--capabilities=130104352,130104352", "--runtime-init", "--nice-name=system_server", "com        . Android.server.SystemServer ",};        Zygoteconnection.arguments Parsedargs = null;        int pid;            try {Parsedargs = new zygoteconnection.arguments (args);            Zygoteconnection.applydebuggersystemproperty (Parsedargs);            Zygoteconnection.applyinvokewithsystemproperty (Parsedargs); /* Request to fork the system server process */pid = Zygote.forksystemserver (Parsedargs.ui D, Parsedargs.gid, Parsedargs.gids,                    Parsedargs.debugflags, NULL, Parsedargs.permittedcapabilities,        Parsedargs.effectivecapabilities);        } catch (IllegalArgumentException ex) {throw new RuntimeException (ex);        }/* for child process */if (PID = = 0) {handlesystemserverprocess (Parsedargs);    } return true; }

This place needs to call the static method of Zygote

/android41/libcore/dalvik/src/main/java/dalvik/system/zygote.java actually needs to call the corresponding native method.

Forksystemserver Fork A standalone process for systemserver

Native method in/android41/dalvik/vm/native/dalvik_system_zygote.cpp

After the fork succeeds, the incoming parameter is called Com.android.server.SystemServer.java


Systemserver opens most of the Android application layer services, including power management, battery, network AMS WMS, etc.

The Frameworks/base/services/java/com/android/server/systemserver directory also contains a large number of corresponding service codes.


    public static final void Init2 () {        slog.i (TAG, "entered the Android system server!");        Thread thr = new Serverthread ();        Thr.setname ("Android.server.ServerThread");        Thr.start ();    }

The Init2 function is the native method

have native Public Static void init1 (string[] args);

Find the corresponding underlying code.

/androidsource/android41/frameworks/base/services/jni/com_android_server_systemserver.cpp

Namespace Android {extern "C" int system_init (); static void Android_server_systemserver_init1 (jnienv* env, Jobject clazz ) {    system_init ();} /* JNI registration. */static Jninativemethod gmethods[] = {/    * name, signature, Funcptr */    {"Init1", "([ljava/lang/string;) V", (void *) android_server_systemserver_init1},//registered Init1 method};int Register_android_server_systemserver (JNIEnv* env) {    Return Jniregisternativemethods (env, "Com/android/server/systemserver",            gmethods, Nelem (Gmethods));}}; Namespace Android


System_init () is an external function, where do you find the body of the function?

Add a static library to the /androidsource/android41/frameworks/base/services/jni/android.mk file

Local_shared_libraries: =     libandroid_runtime     libandroidfw     libcutils     libhardware     libhardware _legacy     libnativehelper     libsystem_server     libutils     libui     libinput     Libskia     Libgui     libusbhost     Libsuspend

System_server and Android_runtime are a key.

System_server can be found in /androidsource/android41/frameworks/base/cmds/system_server , You can look at the Android.mk file and know that the module compiles those files.

See System_init.cpp Code method

extern "C" status_t system_init () {Alogi ("entered System_init ()");    sp<processstate> proc (processstate::self ());    sp<iservicemanager> sm = Defaultservicemanager ();    Alogi ("ServiceManager:%p\n", Sm.get ());    Sp<grimreaper> grim = new Grimreaper ();    Sm->asbinder ()->linktodeath (Grim, Grim.get (), 0);    Char Propbuf[property_value_max];    Property_get ("System_init.startsurfaceflinger", Propbuf, "1");    if (strcmp (Propbuf, "1") = = 0) {//Start the Surfaceflinger surfaceflinger::instantiate ();    } property_get ("System_init.startsensorservice", Propbuf, "1");    if (strcmp (Propbuf, "1") = = 0) {//Start the Sensor service sensorservice::instantiate ();  }//And now start the Android runtime. We have to do this bit//of nastiness because the Android runtime initialization requires//some of the core syste    M services to already is started. All other servers should just start the Android runtime at//THe beginning of their processes ' s main (), before calling//the INIT function.    Alogi ("System server:starting Android runtime.\n");    androidruntime* runtime = Androidruntime::getruntime ();    Alogi ("System server:starting Android services.\n");    jnienv* env = runtime->getjnienv ();    if (env = = NULL) {return unknown_error;    } Jclass clazz = Env->findclass ("Com/android/server/systemserver");    if (clazz = = NULL) {return unknown_error;    } Jmethodid Methodid = Env->getstaticmethodid (Clazz, "Init2", "() V");    if (Methodid = = NULL) {return unknown_error;    } env->callstaticvoidmethod (Clazz, Methodid);    Alogi ("System server:entering thread pool.\n");    Processstate::self ()->startthreadpool ();    Ipcthreadstate::self ()->jointhreadpool ();    Alogi ("System server:exiting thread pool.\n"); return no_error;}

The above is a JNI-related operation that is not difficult to understand. Find the Com.android.server.SystemServer class and execute the Init2 method

The Init2 method initiates a thread that starts the loading and startup of the Android service.


The basic process is to start the zygote process, create the virtual machine, then the Systemserver load service, and of course start other services including the Servicemanager,surfaceflinger program.

The next section analyzes Systemserver startup and Activitymanagerservice startup applications in detail.


Drawing a picture is easy to remember.




This article briefly introduced the Android start-up process, if there is a problem, please indicate thank you.




Android System Startup Research 1

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.