Android startup Research 1
The Android system is relatively large. It takes a long time to figure out the operating principle of the system. I have read the system startup several times but have not summarized it. Today I will briefly summarize it.
Android first focuses on starting the zygote process, which is derived from the reading of init. rc. The zygote process is mainly used to hatch new apps and starts a large number of android services SystemService.
The source code I studied is 4.1, and other versions may be slightly different.
The init. rc file is an important entry for startup configuration. init. c will read this file and the core processes will also be enabled.
/Android41/system/core/init. c
The focus is to parse the init. rc file and start to process related commands. Find the main entry and paste 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 is in progress to background fw loaders, etc */close (open (/dev /. booting, O_WRONLY | O_CREAT, 0000);/* We Must have 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 is mounted on/dev, we can actually * talk to the outside world. */loads (); klog_init (); property_init (); get_hardware_name (hardware, & revision); process_kernel_cmdline (); # ifdef HAVE_SELINUX INFO (loading selinux policy); sel Inux_load_policy (); # endif is_charger =! Strcmp (bootmode, charger); INFO (property init); if (! Is_charger) property_load_boot_defaults (); INFO (reading config file); init_parse_config_file (/init. rc); // read the rc file
The previous steps were to initialize key directories and mount file systems, system hardware devices, and system properties.
FindAndroid41/system/core/rootdir/init. rc
This file also contains ServiceManager IPC Service Manager startup, surfaceflinger image service, bootanim startup animation, and media Service.
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 two things: startup of zygote and system server.
App_process startup code inFrameworks/base/cmds/app_process/app_main.cpp
Main code.
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=, 12) == 0) { niceName = arg + 12; } else { className = arg; break; } } if (niceName && *niceName) { setArgv0(argv0, niceName); set_process_name(niceName); } runtime.mParentDir = parentDir; if (zygote) { runtime.start(com.android.internal.os.ZygoteInit, startSystemServer ? start-system-server : ); } else if (className) { // Remainder of args get passed to startup class 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.); app_usage(); LOG_ALWAYS_FATAL(app_process: no class name or --zygote supplied.); return 10; }
First, parse the input parameters to determine whether to start zygote and RuntimeInit. AppRuntime is the Android dvm startup object,
Start the VM/Android41/frameworks/base/core/jni/AndroidRuntime. cpp contains a large number of initialization tasks, such as heap memory allocation.
Check the ZygoteInit code first.
/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 an initial gc to clean up after startup gc(); // If requested, start system server directly from Zygote if (argv.length != 2) { throw new RuntimeException(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 used to incubate an app. By starting a socketServer to receive requests initiated by the app, ActivityManagerService is used to send Socket communication.
Let's take a look at starting SystemService
private static boolean startSystemServer() throws MethodAndArgsCaller, RuntimeException { /* 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,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.uid, 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; }
In this case, the static method of Zygote needs to be called.
/Android41/libcore/dalvik/src/main/java/dalvik/system/Zygote. javaActually, the corresponding native method needs to be called.
ForkSystemServer fork an independent process is used for SystemServer
Native method in/Android41/dalvik/vm/native/dalvik_system_zygote.cpp
After fork is successful, the passed parameters are called.Com. android. server. SystemServer. java
SystemServer enables most services at the Android Application Layer, including power management, battery, and network ams wms.
The frameworks/base/services/java/com/android/server/SystemServer directory also contains a large number of corresponding service code.
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.
There is native public static void init1 (String [] args); call.
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 methods (env, com/android/server/SystemServer, gMethods, NELEM (gMethods ));}}; // namespace android
System_init () is an external function. Where can I find the function body?
/AndroidSource/Android41/frameworks/base/services/jni/Android. mkAdd static Library in the 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 critical.
System_server in/AndroidSource/Android41/frameworks/base/cmds/system_serverYou can find it. You can see that the Android. mk file knows which files are compiled by the module.
View the System_init.cpp code method
extern C status_t system_init(){ ALOGI(Entered system_init()); sp
proc(ProcessState::self()); sp
sm = defaultServiceManager(); ALOGI(ServiceManager: %p, sm.get()); sp
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 system services to already be 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.); AndroidRuntime* runtime = AndroidRuntime::getRuntime(); ALOGI(System server: starting Android services.); 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.); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); ALOGI(System server: exiting thread pool.); return NO_ERROR;}
The preceding operations are related to jni, which is not difficult to understand. Find the com. android. server. SystemServer class and execute the init2 method.
The init2 method starts the thread to load and start the Android service.
The basic process is to start the Zygote process, create a virtual machine, and then load the SystemServer service. Of course, other services including ServiceManager and SurfaceFlinger are also started.
The next section details how to start the SystemServer and ActivityManagerService.
It is easy to remember to draw a chart.