Android 9.0 Zygo Startup Process

This article mainly introduces Android Zygo Start Analysis Knowledge Points. By reading this article, you will gain the following contents:

I. Basic Services of Android System
2. Virtual Machine Creation and First Java Program Boot
3. Basic configuration of Dalvik virtual machine
IV. Zygote Startup Process
V. Zygote Startup Analysis
6. The main method of creating system_server by Zygo
7. Zygo Creating System_server Analysis
VIII. Zygote Creation and Application
9. Zygo Create Application Flow
10. Zygote preload resources
XI. Purpose of Zygote preloading
12. Optimizing Zygo Startup Method: Thread Pool
Fork System Server

Zygote Service through init.rcThe process starts.Zygote Of classname bymain .
init.rc The file configuration code is as follows:

... ... 
on nonencrypted
    class_start main
    class_start late_start

on property:sys.init_log_level=*
    loglevel ${sys.init_log_level}

... ...

You can refer to init.rc for startup analysis in detail.
Android 9.0 init startup process

main function of Zygote process

app_main.cpp is the main function of the Zygo process, frameworksbasecmdsapp_processapp_main.cpp

I. Basic Services of Android System

Android system includes netd, service manager, surfaceflinger, zygote, media, installd, bootanimation and other basic services. See the figure below.

Android

2. Virtual Machine Creation and First Java Program Boot

In order to make APK run in different virtual machines, Google adopts the adapter mode. It executes dexopt before running the virtual machine. It optimizes dex files into odex files, which can make the execution of the virtual machine more optimized.

In ART virtual machine, dexopt optimizes the DEX file into binary format, so that ART virtual machine can execute. Dexopt calls dex2oat to optimize. dex2oat's task is to pre-translate the original DEX file, which can speed up the running time of app, but because some apps are more complex, the optimization time is longer.
The optimization is based on the Method in dex file. When dex2oat is optimized, it will optimize a certain number of methods according to the demand. That is to say, not all methods are translated back into oat mode.

Java

3. Basic configuration of Dalvik virtual machine

In Android systems, the Dalvik virtual machine and ART, application processes, and the key service SystemServer processes running the system are created and incubated by the Zygote process.

The basic configuration of the Dalvik virtual machine is as follows:

Dalvik

IV. Zygote Startup Process

Zygote is started by the init.rc script. In the init script, we can see that the import/init. ${ro.zygote}.rc script will be imported.

# Copyright (C) 2012 The Android Open Source Project
#
# IMPORTANT: Do not create world writable files or directories.
# This is a common source of Android security bugs.
#

import /init.environ.rc
import /init.usb.rc
import /init.${ro.hardware}.rc
import /vendor/etc/init/hw/init.${ro.hardware}.rc
import /init.usb.configfs.rc
... ...
import /init.${ro.zygote}.rc

... ...

In the system/core/rootdir directory, different scripts will be launched according to the value of the ro.zygote attribute, mainly including the following four zygote scripts.

  • 1.init.zygote32.rc supports 32 as a system
  • 2.init.zygote32_64.rc
  • 3.init.zygote64.rc
  • 4.init.zygote64_32.rc

V. Zygote Startup Analysis

6. The main method of creating system_server by Zygo

7. Zygo Creating System_server Analysis

VIII. Zygote Creation and Application

9. Zygo Create Application Flow

10. Zygote preload resources

XI. Purpose of Zygote preloading

12. Optimizing Zygo Startup Method: Thread Pool

Zygote startup optimization premise:

  • 1: Loading classes and resources are reentrant operations, so there is no mutually exclusive scenario in parallel mode
  • 2: Android provides Executors and ExecutorService multithreaded classes, so you can use multithreading to load classes and resources.
  • 3: The hardware platform should be multi-core, otherwise the acceleration is not obvious.

The essence of Zygote startup optimization is:

Making our processes maximize CPU preemption

Fork System Server

After a series of initializations, forkSystemServer in the ZygoteInit class is ready to start SystemServer. The ZygoteInit.java code path is as follows: alps frameworks base core java com android internal os ZygoteInit.java


    /**
     * Prepare the arguments and forks for the system server process.
     *
     * Returns an {@code Runnable} that provides an entrypoint into system_server code in the
     * child process, and {@code null} in the parent.
     */
    private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
        long capabilities = posixCapabilitiesAsBits(
            OsConstants.CAP_IPC_LOCK,
            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_PTRACE,
            OsConstants.CAP_SYS_TIME,
            OsConstants.CAP_SYS_TTY_CONFIG,
            OsConstants.CAP_WAKE_ALARM,
            OsConstants.CAP_BLOCK_SUSPEND
        );
        /* Containers run without some capabilities, so drop any caps that are not available. */
        StructCapUserHeader header = new StructCapUserHeader(
                OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
        StructCapUserData[] data;
        try {
            data = Os.capget(header);
        } catch (ErrnoException ex) {
            throw new RuntimeException("Failed to capget()", ex);
        }
        capabilities &= ((long) data[0].effective) | (((long) data[1].effective) << 32);

        /* Hardcoded command line to start the system server */
        String args[] = {
            "--setuid=1000",
            "--setgid=1000",
            /// M: [Wi-Fi Hotspot Manager] system_server add dhcp (1014) group to access
            /// "/data/misc/dhcp/dnsmasq.leases"
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1014,1018,1021,1023," +
                        "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
            "--capabilities=" + capabilities + "," + capabilities,
            "--nice-name=system_server",
            "--runtime-args",
            "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
            "com.android.server.SystemServer",
        };
        ZygoteConnection.Arguments parsedArgs = null;

        int pid;

        try {
            parsedArgs = new ZygoteConnection.Arguments(args);
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

            boolean profileSystemServer = SystemProperties.getBoolean(
                    "dalvik.vm.profilesystemserver", false);
            if (profileSystemServer) {
                parsedArgs.runtimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
            }

            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.runtimeFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }

        /* For child process */
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }

            zygoteServer.closeServerSocket();
            return handleSystemServerProcess(parsedArgs);
        }

        return null;
    }

So far, this article is over. If there are any mistakes, you are welcome to make suggestions and corrections. At the same time look forward to your attention, thank you for reading, thank you!

Tags: Android Java Google Attribute

Posted on Tue, 03 Sep 2019 01:34:14 -0700 by anushka