Reprint please indicate source: a maple leaf column

We all know that the Android system Zygote process is the parent process of all Android processes, including SystemServer and various application processes are fork out through Zygote process. The Zygote process is the root process of the Android system. All subsequent processes are fork out from the Zygote process, while the Zygote process is started by the Linux init process

– > Zygote – > SystemServer – > various application processes

  • Init: the root process of Linux. Android is based on Linux, so it can be counted as the first process of the entire Android operating system.

  • Zygote: the root process of the Android system. It can fork the SystemServer process and various application processes.

  • SystemService process: mainly in this process to start the system services, such as ActivityManagerService, PackageManagerService, WindowManagerService and so on;

  • Application processes: To start a self-written client application, an application process is generally restarted and has its own VM and running environment.

This article mainly introduces the startup process of the Zygote process. The startup methods of the SystenServer process and various application processes will be introduced in the future articles.

The ZygoteInit process usually calls the ZygoteInit class main method when starting Zygote process, so let’s look at the concrete implementation of this method (based on android23 source code);

public static void main(String argv[]) { try { RuntimeInit.enableDdms(); SamplingProfilerIntegration.start(); boolean startSystemServer = false; String socketName = "zygote"; String abiList = null; for (int i = 1; i < argv.length; i++) { if ("start-system-server".equals(argv[i])) { startSystemServer = true; } else if (argv[i].startsWith(ABI_LIST_ARG)) { abiList = argv[i].substring(ABI_LIST_ARG.length()); } else if (argv[i].startsWith(SOCKET_NAME_ARG)) { socketName = argv[i].substring(SOCKET_NAME_ARG.length()); } else { throw new RuntimeException("Unknown command line argument: " + argv[i]); } } if (abiList == null) { throw new RuntimeException("No ABI list supplied."); } registerZygoteSocket(socketName); EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START, SystemClock.uptimeMillis()); preload(); EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END, SystemClock.uptimeMillis()); SamplingProfilerIntegration.writeZygoteSnapshot(); gcAndFinalize(); Trace.setTracingEnabled(false); if (startSystemServer) { startSystemServer(abiList, socketName); } Log.i(TAG, "Accepting command socket connections"); runSelectLoop(abiList); closeServerSocket(); } catch (MethodAndArgsCaller caller) { caller.run(); } catch (RuntimeException ex) { Log.e(TAG, "Zygote died with exception", ex); closeServerSocket(); throw ex; }}Copy the code
  • The first line is to call enableDdms() and set DDMS to be available. You can see that the DDMS start time is relatively early, just as the entire Zygote process is about to start.

  • The following loop resolves whether to start the SystemService process, get the list of ABI’s, and get the name of the scoket connection. Binder android processes communicate with each other, with the exception of SystemService and Zygote processes that use sockets.)

  • Then call registerZygoteSocket (String socketName) to register the socket for the Zygote process:

private static void registerZygoteSocket(String socketName) { if (sServerSocket == null) { int fileDesc; final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName; try { String env = System.getenv(fullSocketName); fileDesc = Integer.parseInt(env); } catch (RuntimeException ex) { throw new RuntimeException(fullSocketName + " unset or invalid", ex); } try { FileDescriptor fd = new FileDescriptor(); fd.setInt$(fileDesc); sServerSocket = new LocalServerSocket(fd); } catch (IOException ex) { throw new RuntimeException( "Error binding to local socket '" + fileDesc + "'", ex); }}}Copy the code
static void preload() {
        Log.d(TAG, "begin preload");
        preloadClasses();
        preloadResources();
        preloadOpenGL();
        preloadSharedLibraries();
        preloadTextResources();
        
        
        WebViewFactory.prepareWebViewInZygote();
        Log.d(TAG, "end preload");
    }Copy the code

PreloadClasses () is used to initialize classes needed in Zygote. PreloadResources () is used to initialize system resources; PreloadOpenGL () initializes OpenGL; PreloadSharedLibraries () is used to initialize system libraries; PreloadTextResources () is used to initialize text resources; PrepareWebViewInZygote () is used to initialize the WebView;

  • Then call startSystemServer(abiList, socket);
private static boolean startSystemServer(String abiList, String socketName) throws MethodAndArgsCaller, RuntimeException { long capabilities = posixCapabilitiesAsBits( OsConstants.CAP_BLOCK_SUSPEND, OsConstants.CAP_KILL, OsConstants.CAP_NET_ADMIN, OsConstants.CAP_NET_BIND_SERVICE, OsConstants.CAP_NET_BROADCAST, OsConstants.CAP_NET_RAW, OsConstants.CAP_SYS_MODULE, OsConstants.CAP_SYS_NICE, OsConstants.CAP_SYS_RESOURCE, OsConstants.CAP_SYS_TIME, OsConstants.CAP_SYS_TTY_CONFIG ) String args[] = { "--setuid=1000", "--setgid=1000", "-- setgroups = 1001100 2100 3100 4100 5100 6100 7100 8100 9101 0101 8102 1103 2300 1300 2300 3300 6300 7", "--capabilities=" + capabilities + "," + capabilities, "--nice-name=system_server", "--runtime-args", "com.android.server.SystemServer", } ZygoteConnection.Arguments parsedArgs = null int pid try { parsedArgs = new ZygoteConnection.Arguments(args) ZygoteConnection.applyDebuggerSystemProperty(parsedArgs) ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs) pid = Zygote.forkSystemServer( parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities) } catch (IllegalArgumentException ex) { throw new RuntimeException(ex) } if (pid == 0)  { if (hasSecondZygote(abiList)) { waitForSecondaryZygote(socketName) } handleSystemServerProcess(parsedArgs) } return true }Copy the code

Zygote forks the SystemServer process.

The mian method of Zygote executes the following logic:

  • Initialize DDMS;

  • Registered Zygote process socket communication;

  • Initialize Zygote classes, resource files, OpenGL, libraries, Text resources, etc.

  • After initialization, fork the SystemServer process.

  • Fork Out the SystemServer process and close the socket connection.

In addition to the Android source code parsing method of interest can refer to my: Android project construction process android source code parsing (2) – > Asynchronous message mechanism android source code parsing (3) – > asynchronous task AsyncTask Android source code parsing (4) – >HandlerThread IntentService android source code 解 决 (6) — >Log Android source code 解 决 (7) — >LruCache

This article is synchronized to Github:Github.com/yipianfengy…Welcome star and Follow