Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 7e6fa672 authored by Martijn Coenen's avatar Martijn Coenen
Browse files

Initial support for application Zygote.

When an application has requested isolated services to be spawned
from an app zygote, we need to spawn the app zygote itself, and then
ask it to fork an isolated service.

The application zygote currently only creates the class loader, and
doesn't do much else. We keep track of the isolated services that
use the app zygote, and when the last isolated service goes away,
we stop the app zygote itself (after a timeout).

The app zygote itself runs with the app's UID and under the app
seccomp filter. That last one is too restricted, so this currently
only works with SELinux disabled.

Future CLs will add an application callback for preloading.

Test: start multiple isolated services with useAppZygote="true",
      verify app_zygote starts, services start as a child of
      app_zygote. Stopping all services stops app_zygote as well.

Bug: 111434506

Change-Id: I10ee1d4bd148c9298974d434fbc5e5eccbec16cb
parent caa6519f
Loading
Loading
Loading
Loading
+116 −0
Original line number Original line Diff line number Diff line
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.os;

import android.content.pm.ApplicationInfo;
import android.util.Log;

import com.android.internal.annotations.GuardedBy;

/**
 * AppZygote is responsible for interfacing with an application-specific zygote.
 *
 * Application zygotes can pre-load app-specific code and data, and this interface can
 * be used to spawn isolated services from such an application zygote.
 *
 * Note that we'll have only one instance of this per application / uid combination.
 *
 * @hide
 */
public class AppZygote {
    private static final String LOG_TAG = "AppZygote";

    private final Object mLock = new Object();

    /**
     * Instance that maintains the socket connection to the zygote. This is {@code null} if the
     * zygote is not running or is not connected.
     */
    @GuardedBy("mLock")
    private ChildZygoteProcess mZygote;

    private final ApplicationInfo mAppInfo;

    public AppZygote(ApplicationInfo appInfo) {
        mAppInfo = appInfo;
    }

    /**
     * Returns the zygote process associated with this app zygote.
     * Creates the process if it's not already running.
     */
    public ChildZygoteProcess getProcess() {
        synchronized (mLock) {
            if (mZygote != null) return mZygote;

            connectToZygoteIfNeededLocked();
            return mZygote;
        }
    }

    /**
     * Stops the Zygote and kills the zygote process.
     */
    public void stopZygote() {
        synchronized (mLock) {
            stopZygoteLocked();
        }
    }

    public ApplicationInfo getAppInfo() {
        return mAppInfo;
    }

    @GuardedBy("mLock")
    private void stopZygoteLocked() {
        if (mZygote != null) {
            // Close the connection and kill the zygote process. This will not cause
            // child processes to be killed by itself.
            mZygote.close();
            Process.killProcess(mZygote.getPid());
            mZygote = null;
        }
    }

    @GuardedBy("mLock")
    private void connectToZygoteIfNeededLocked() {
        String abi = mAppInfo.primaryCpuAbi != null ? mAppInfo.primaryCpuAbi :
                Build.SUPPORTED_ABIS[0];
        try {
            mZygote = Process.zygoteProcess.startChildZygote(
                    "com.android.internal.os.AppZygoteInit",
                    mAppInfo.processName + "_zygote",
                    mAppInfo.uid,
                    mAppInfo.uid,
                    null,  // gids
                    0,  // runtimeFlags
                    "app_zygote",  // seInfo
                    abi,  // abi
                    abi, // acceptedAbiList
                    null);  // instructionSet

            ZygoteProcess.waitForConnectionToZygote(mZygote.getPrimarySocketAddress());
            // preload application code in the zygote
            Log.i(LOG_TAG, "Starting application preload.");
            mZygote.preloadApp(mAppInfo, abi);
            Log.i(LOG_TAG, "Application preload done.");
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error connecting to app zygote", e);
            stopZygoteLocked();
        }
    }
}
+49 −1
Original line number Original line Diff line number Diff line
@@ -18,6 +18,7 @@ package android.os;


import android.annotation.NonNull;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.Nullable;
import android.content.pm.ApplicationInfo;
import android.net.LocalSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.net.LocalSocketAddress;
import android.util.Log;
import android.util.Log;
@@ -34,6 +35,7 @@ import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.Collections;
import java.util.List;
import java.util.List;
import java.util.UUID;
import java.util.UUID;
@@ -672,6 +674,36 @@ public class ZygoteProcess {
        throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
        throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
    }
    }


    /**
     * Instructs the zygote to pre-load the application code for the given Application.
     * Only the app zygote supports this function.
     * TODO preloadPackageForAbi() can probably be removed and the callers an use this instead.
     */
    public boolean preloadApp(ApplicationInfo appInfo, String abi) throws ZygoteStartFailedEx,
                                                                          IOException {
        synchronized (mLock) {
            ZygoteState state = openZygoteSocketIfNeeded(abi);
            state.writer.write("2");
            state.writer.newLine();

            state.writer.write("--preload-app");
            state.writer.newLine();

            // Zygote args needs to be strings, so in order to pass ApplicationInfo,
            // write it to a Parcel, and base64 the raw Parcel bytes to the other side.
            Parcel parcel = Parcel.obtain();
            appInfo.writeToParcel(parcel, 0 /* flags */);
            String encodedParcelData = Base64.getEncoder().encodeToString(parcel.marshall());
            parcel.recycle();
            state.writer.write(encodedParcelData);
            state.writer.newLine();

            state.writer.flush();

            return (state.inputStream.readInt() == 0);
        }
    }

    /**
    /**
     * Instructs the zygote to pre-load the classes and native libraries at the given paths
     * Instructs the zygote to pre-load the classes and native libraries at the given paths
     * for the specified abi. Not all zygotes support this function.
     * for the specified abi. Not all zygotes support this function.
@@ -763,6 +795,20 @@ public class ZygoteProcess {
     * secondary zygotes that inherit data from the zygote that this object
     * secondary zygotes that inherit data from the zygote that this object
     * communicates with. This returns a new ZygoteProcess representing a connection
     * communicates with. This returns a new ZygoteProcess representing a connection
     * to the newly created zygote. Throws an exception if the zygote cannot be started.
     * to the newly created zygote. Throws an exception if the zygote cannot be started.
     *
     * @param processClass The class to use as the child zygote's main entry
     *                     point.
     * @param niceName A more readable name to use for the process.
     * @param uid The user-id under which the child zygote will run.
     * @param gid The group-id under which the child zygote will run.
     * @param gids Additional group-ids associated with the child zygote process.
     * @param runtimeFlags Additional flags.
     * @param seInfo null-ok SELinux information for the child zygote process.
     * @param abi non-null the ABI of the child zygote
     * @param acceptedAbiList ABIs this child zygote will accept connections for; this
     *                        may be different from <code>abi</code> in case the children
     *                        spawned from this Zygote only communicate using ABI-safe methods.
     * @param instructionSet null-ok the instruction set to use.
     */
     */
    public ChildZygoteProcess startChildZygote(final String processClass,
    public ChildZygoteProcess startChildZygote(final String processClass,
                                               final String niceName,
                                               final String niceName,
@@ -770,12 +816,14 @@ public class ZygoteProcess {
                                               int runtimeFlags,
                                               int runtimeFlags,
                                               String seInfo,
                                               String seInfo,
                                               String abi,
                                               String abi,
                                               String acceptedAbiList,
                                               String instructionSet) {
                                               String instructionSet) {
        // Create an unguessable address in the global abstract namespace.
        // Create an unguessable address in the global abstract namespace.
        final LocalSocketAddress serverAddress = new LocalSocketAddress(
        final LocalSocketAddress serverAddress = new LocalSocketAddress(
                processClass + "/" + UUID.randomUUID().toString());
                processClass + "/" + UUID.randomUUID().toString());


        final String[] extraArgs = {Zygote.CHILD_ZYGOTE_SOCKET_NAME_ARG + serverAddress.getName()};
        final String[] extraArgs = {Zygote.CHILD_ZYGOTE_SOCKET_NAME_ARG + serverAddress.getName(),
                                    Zygote.CHILD_ZYGOTE_ABI_LIST_ARG + acceptedAbiList};


        Process.ProcessStartResult result;
        Process.ProcessStartResult result;
        try {
        try {
+1 −0
Original line number Original line Diff line number Diff line
@@ -159,6 +159,7 @@ public class WebViewZygote {
                    0,  // runtimeFlags
                    0,  // runtimeFlags
                    "webview_zygote",  // seInfo
                    "webview_zygote",  // seInfo
                    sPackage.applicationInfo.primaryCpuAbi,  // abi
                    sPackage.applicationInfo.primaryCpuAbi,  // abi
                    TextUtils.join(",", Build.SUPPORTED_ABIS),
                    null);  // instructionSet
                    null);  // instructionSet


            // All the work below is usually done by LoadedApk, but the zygote can't talk to
            // All the work below is usually done by LoadedApk, but the zygote can't talk to
+91 −0
Original line number Original line Diff line number Diff line
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.os;

import android.app.LoadedApk;
import android.content.pm.ApplicationInfo;
import android.net.LocalSocket;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;

/**
 * Startup class for an Application zygote process.
 *
 * See {@link ZygoteInit} for generic zygote startup documentation.
 *
 * @hide
 */
class AppZygoteInit {
    public static final String TAG = "AppZygoteInit";

    private static ZygoteServer sServer;

    private static class AppZygoteServer extends ZygoteServer {
        @Override
        protected ZygoteConnection createNewConnection(LocalSocket socket, String abiList)
                throws IOException {
            return new AppZygoteConnection(socket, abiList);
        }
    }

    private static class AppZygoteConnection extends ZygoteConnection {
        AppZygoteConnection(LocalSocket socket, String abiList) throws IOException {
            super(socket, abiList);
        }

        @Override
        protected void preload() {
            // Nothing to preload by default.
        }

        @Override
        protected boolean isPreloadComplete() {
            // App zygotes don't preload any classes or resources or defaults, all of their
            // preloading is package specific.
            return true;
        }

        @Override
        protected boolean canPreloadApp() {
            return true;
        }

        @Override
        protected void handlePreloadApp(ApplicationInfo appInfo) {
            Log.i(TAG, "Beginning application preload for " + appInfo.packageName);
            LoadedApk loadedApk = new LoadedApk(null, appInfo, null, null, false, true, false);
            // Initialize the classLoader
            ClassLoader loader = loadedApk.getClassLoader();

            try {
                DataOutputStream socketOut = getSocketOutputStream();
                socketOut.writeInt(loader != null ? 1 : 0);
            } catch (IOException e) {
                throw new IllegalStateException("Error writing to command socket", e);
            }

            Log.i(TAG, "Application preload done");
        }
    }

    public static void main(String[] argv) {
        AppZygoteServer server = new AppZygoteServer();
        ChildZygoteInit.runZygoteServer(server, argv);
    }
}
+99 −0
Original line number Original line Diff line number Diff line
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.internal.os;

import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import android.util.Log;

/**
 * ChildZygoteInit is shared by both the Application and WebView zygote to initialize
 * and run a (child) Zygote server.
 *
 * @hide
 */
public class ChildZygoteInit {
    private static final String TAG = "ChildZygoteInit";

    static String parseSocketNameFromArgs(String[] argv) {
        for (String arg : argv) {
            if (arg.startsWith(Zygote.CHILD_ZYGOTE_SOCKET_NAME_ARG)) {
                return arg.substring(Zygote.CHILD_ZYGOTE_SOCKET_NAME_ARG.length());
            }
        }

        return null;
    }

    static String parseAbiListFromArgs(String[] argv) {
        for (String arg : argv) {
            if (arg.startsWith(Zygote.CHILD_ZYGOTE_ABI_LIST_ARG)) {
                return arg.substring(Zygote.CHILD_ZYGOTE_ABI_LIST_ARG.length());
            }
        }

        return null;
    }

    /**
     * Starts a ZygoteServer and listens for requests
     *
     * @param server An instance of a ZygoteServer to listen on
     * @param args Passed in arguments for this ZygoteServer
     */
    static void runZygoteServer(ZygoteServer server, String[] args) {
        String socketName = parseSocketNameFromArgs(args);
        if (socketName == null) {
            throw new NullPointerException("No socketName specified");
        }

        String abiList = parseAbiListFromArgs(args);
        if (abiList == null) {
            throw new NullPointerException("No abiList specified");
        }

        try {
            Os.prctl(OsConstants.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
        } catch (ErrnoException ex) {
            throw new RuntimeException("Failed to set PR_SET_NO_NEW_PRIVS", ex);
        }

        final Runnable caller;
        try {
            server.registerServerSocketAtAbstractName(socketName);

            // Add the abstract socket to the FD whitelist so that the native zygote code
            // can properly detach it after forking.
            Zygote.nativeAllowFileAcrossFork("ABSTRACT/" + socketName);

            // The select loop returns early in the child process after a fork and
            // loops forever in the zygote.
            caller = server.runSelectLoop(abiList);
        } catch (RuntimeException e) {
            Log.e(TAG, "Fatal exception:", e);
            throw e;
        } finally {
            server.closeServerSocket();
        }

        // We're in the child process and have exited the select loop. Proceed to execute the
        // command.
        if (caller != null) {
            caller.run();
        }
    }
}
Loading