• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.os;
18 
19 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
20 import static android.os.Process.ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS;
21 
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.compat.annotation.UnsupportedAppUsage;
25 import android.content.pm.ApplicationInfo;
26 import android.net.LocalSocket;
27 import android.net.LocalSocketAddress;
28 import android.util.Log;
29 import android.util.Pair;
30 import android.util.Slog;
31 
32 import com.android.internal.annotations.GuardedBy;
33 import com.android.internal.os.Zygote;
34 import com.android.internal.os.ZygoteConfig;
35 
36 import java.io.BufferedWriter;
37 import java.io.DataInputStream;
38 import java.io.IOException;
39 import java.io.OutputStreamWriter;
40 import java.nio.charset.StandardCharsets;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Base64;
44 import java.util.Collections;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.UUID;
48 
49 /*package*/ class ZygoteStartFailedEx extends Exception {
50     @UnsupportedAppUsage
ZygoteStartFailedEx(String s)51     ZygoteStartFailedEx(String s) {
52         super(s);
53     }
54 
55     @UnsupportedAppUsage
ZygoteStartFailedEx(Throwable cause)56     ZygoteStartFailedEx(Throwable cause) {
57         super(cause);
58     }
59 
ZygoteStartFailedEx(String s, Throwable cause)60     ZygoteStartFailedEx(String s, Throwable cause) {
61         super(s, cause);
62     }
63 }
64 
65 /**
66  * Maintains communication state with the zygote processes. This class is responsible
67  * for the sockets opened to the zygotes and for starting processes on behalf of the
68  * {@link android.os.Process} class.
69  *
70  * {@hide}
71  */
72 public class ZygoteProcess {
73 
74     private static final int ZYGOTE_CONNECT_TIMEOUT_MS = 20000;
75 
76     /**
77      * Use a relatively short delay, because for app zygote, this is in the critical path of
78      * service launch.
79      */
80     private static final int ZYGOTE_CONNECT_RETRY_DELAY_MS = 50;
81 
82     private static final String LOG_TAG = "ZygoteProcess";
83 
84     /**
85      * The default value for enabling the unspecialized app process (USAP) pool.  This value will
86      * not be used if the devices has a DeviceConfig profile pushed to it that contains a value for
87      * this key.
88      */
89     private static final String USAP_POOL_ENABLED_DEFAULT = "false";
90 
91     /**
92      * The name of the socket used to communicate with the primary zygote.
93      */
94     private final LocalSocketAddress mZygoteSocketAddress;
95 
96     /**
97      * The name of the secondary (alternate ABI) zygote socket.
98      */
99     private final LocalSocketAddress mZygoteSecondarySocketAddress;
100 
101     /**
102      * The name of the socket used to communicate with the primary USAP pool.
103      */
104     private final LocalSocketAddress mUsapPoolSocketAddress;
105 
106     /**
107      * The name of the socket used to communicate with the secondary (alternate ABI) USAP pool.
108      */
109     private final LocalSocketAddress mUsapPoolSecondarySocketAddress;
110 
ZygoteProcess()111     public ZygoteProcess() {
112         mZygoteSocketAddress =
113                 new LocalSocketAddress(Zygote.PRIMARY_SOCKET_NAME,
114                                        LocalSocketAddress.Namespace.RESERVED);
115         mZygoteSecondarySocketAddress =
116                 new LocalSocketAddress(Zygote.SECONDARY_SOCKET_NAME,
117                                        LocalSocketAddress.Namespace.RESERVED);
118 
119         mUsapPoolSocketAddress =
120                 new LocalSocketAddress(Zygote.USAP_POOL_PRIMARY_SOCKET_NAME,
121                                        LocalSocketAddress.Namespace.RESERVED);
122         mUsapPoolSecondarySocketAddress =
123                 new LocalSocketAddress(Zygote.USAP_POOL_SECONDARY_SOCKET_NAME,
124                                        LocalSocketAddress.Namespace.RESERVED);
125 
126         // This constructor is used to create the primary and secondary Zygotes, which can support
127         // Unspecialized App Process Pools.
128         mUsapPoolSupported = true;
129     }
130 
ZygoteProcess(LocalSocketAddress primarySocketAddress, LocalSocketAddress secondarySocketAddress)131     public ZygoteProcess(LocalSocketAddress primarySocketAddress,
132                          LocalSocketAddress secondarySocketAddress) {
133         mZygoteSocketAddress = primarySocketAddress;
134         mZygoteSecondarySocketAddress = secondarySocketAddress;
135 
136         mUsapPoolSocketAddress = null;
137         mUsapPoolSecondarySocketAddress = null;
138 
139         // This constructor is used to create the primary and secondary Zygotes, which CAN NOT
140         // support Unspecialized App Process Pools.
141         mUsapPoolSupported = false;
142     }
143 
getPrimarySocketAddress()144     public LocalSocketAddress getPrimarySocketAddress() {
145         return mZygoteSocketAddress;
146     }
147 
148     /**
149      * State for communicating with the zygote process.
150      */
151     private static class ZygoteState implements AutoCloseable {
152         final LocalSocketAddress mZygoteSocketAddress;
153         final LocalSocketAddress mUsapSocketAddress;
154 
155         private final LocalSocket mZygoteSessionSocket;
156 
157         final DataInputStream mZygoteInputStream;
158         final BufferedWriter mZygoteOutputWriter;
159 
160         private final List<String> mAbiList;
161 
162         private boolean mClosed;
163 
ZygoteState(LocalSocketAddress zygoteSocketAddress, LocalSocketAddress usapSocketAddress, LocalSocket zygoteSessionSocket, DataInputStream zygoteInputStream, BufferedWriter zygoteOutputWriter, List<String> abiList)164         private ZygoteState(LocalSocketAddress zygoteSocketAddress,
165                             LocalSocketAddress usapSocketAddress,
166                             LocalSocket zygoteSessionSocket,
167                             DataInputStream zygoteInputStream,
168                             BufferedWriter zygoteOutputWriter,
169                             List<String> abiList) {
170             this.mZygoteSocketAddress = zygoteSocketAddress;
171             this.mUsapSocketAddress = usapSocketAddress;
172             this.mZygoteSessionSocket = zygoteSessionSocket;
173             this.mZygoteInputStream = zygoteInputStream;
174             this.mZygoteOutputWriter = zygoteOutputWriter;
175             this.mAbiList = abiList;
176         }
177 
178         /**
179          * Create a new ZygoteState object by connecting to the given Zygote socket and saving the
180          * given USAP socket address.
181          *
182          * @param zygoteSocketAddress  Zygote socket to connect to
183          * @param usapSocketAddress  USAP socket address to save for later
184          * @return  A new ZygoteState object containing a session socket for the given Zygote socket
185          * address
186          * @throws IOException
187          */
connect(@onNull LocalSocketAddress zygoteSocketAddress, @Nullable LocalSocketAddress usapSocketAddress)188         static ZygoteState connect(@NonNull LocalSocketAddress zygoteSocketAddress,
189                 @Nullable LocalSocketAddress usapSocketAddress)
190                 throws IOException {
191 
192             DataInputStream zygoteInputStream;
193             BufferedWriter zygoteOutputWriter;
194             final LocalSocket zygoteSessionSocket = new LocalSocket();
195 
196             if (zygoteSocketAddress == null) {
197                 throw new IllegalArgumentException("zygoteSocketAddress can't be null");
198             }
199 
200             try {
201                 zygoteSessionSocket.connect(zygoteSocketAddress);
202                 zygoteInputStream = new DataInputStream(zygoteSessionSocket.getInputStream());
203                 zygoteOutputWriter =
204                         new BufferedWriter(
205                                 new OutputStreamWriter(zygoteSessionSocket.getOutputStream()),
206                                 Zygote.SOCKET_BUFFER_SIZE);
207             } catch (IOException ex) {
208                 try {
209                     zygoteSessionSocket.close();
210                 } catch (IOException ignore) { }
211 
212                 throw ex;
213             }
214 
215             return new ZygoteState(zygoteSocketAddress, usapSocketAddress,
216                                    zygoteSessionSocket, zygoteInputStream, zygoteOutputWriter,
217                                    getAbiList(zygoteOutputWriter, zygoteInputStream));
218         }
219 
getUsapSessionSocket()220         LocalSocket getUsapSessionSocket() throws IOException {
221             final LocalSocket usapSessionSocket = new LocalSocket();
222             usapSessionSocket.connect(this.mUsapSocketAddress);
223 
224             return usapSessionSocket;
225         }
226 
matches(String abi)227         boolean matches(String abi) {
228             return mAbiList.contains(abi);
229         }
230 
close()231         public void close() {
232             try {
233                 mZygoteSessionSocket.close();
234             } catch (IOException ex) {
235                 Log.e(LOG_TAG,"I/O exception on routine close", ex);
236             }
237 
238             mClosed = true;
239         }
240 
isClosed()241         boolean isClosed() {
242             return mClosed;
243         }
244     }
245 
246     /**
247      * Lock object to protect access to the two ZygoteStates below. This lock must be
248      * acquired while communicating over the ZygoteState's socket, to prevent
249      * interleaved access.
250      */
251     private final Object mLock = new Object();
252 
253     /**
254      * List of exemptions to the API deny list. These are prefix matches on the runtime format
255      * symbol signature. Any matching symbol is treated by the runtime as being on the light grey
256      * list.
257      */
258     private List<String> mApiDenylistExemptions = Collections.emptyList();
259 
260     /**
261      * Proportion of hidden API accesses that should be logged to the event log; 0 - 0x10000.
262      */
263     private int mHiddenApiAccessLogSampleRate;
264 
265     /**
266      * Proportion of hidden API accesses that should be logged to statslog; 0 - 0x10000.
267      */
268     private int mHiddenApiAccessStatslogSampleRate;
269 
270     /**
271      * The state of the connection to the primary zygote.
272      */
273     private ZygoteState primaryZygoteState;
274 
275     /**
276      * The state of the connection to the secondary zygote.
277      */
278     private ZygoteState secondaryZygoteState;
279 
280     /**
281      * If this Zygote supports the creation and maintenance of a USAP pool.
282      *
283      * Currently only the primary and secondary Zygotes support USAP pools. Any
284      * child Zygotes will be unable to create or use a USAP pool.
285      */
286     private final boolean mUsapPoolSupported;
287 
288     /**
289      * If the USAP pool should be created and used to start applications.
290      *
291      * Setting this value to false will disable the creation, maintenance, and use of the USAP
292      * pool.  When the USAP pool is disabled the application lifecycle will be identical to
293      * previous versions of Android.
294      */
295     private boolean mUsapPoolEnabled = false;
296 
297     /**
298      * Start a new process.
299      *
300      * <p>If processes are enabled, a new process is created and the
301      * static main() function of a <var>processClass</var> is executed there.
302      * The process will continue running after this function returns.
303      *
304      * <p>If processes are not enabled, a new thread in the caller's
305      * process is created and main() of <var>processclass</var> called there.
306      *
307      * <p>The niceName parameter, if not an empty string, is a custom name to
308      * give to the process instead of using processClass.  This allows you to
309      * make easily identifyable processes even if you are using the same base
310      * <var>processClass</var> to start them.
311      *
312      * When invokeWith is not null, the process will be started as a fresh app
313      * and not a zygote fork. Note that this is only allowed for uid 0 or when
314      * runtimeFlags contains DEBUG_ENABLE_DEBUGGER.
315      *
316      * @param processClass The class to use as the process's main entry
317      *                     point.
318      * @param niceName A more readable name to use for the process.
319      * @param uid The user-id under which the process will run.
320      * @param gid The group-id under which the process will run.
321      * @param gids Additional group-ids associated with the process.
322      * @param runtimeFlags Additional flags.
323      * @param targetSdkVersion The target SDK version for the app.
324      * @param seInfo null-ok SELinux information for the new process.
325      * @param abi non-null the ABI this app should be started with.
326      * @param instructionSet null-ok the instruction set to use.
327      * @param appDataDir null-ok the data directory of the app.
328      * @param invokeWith null-ok the command to invoke with.
329      * @param packageName null-ok the name of the package this process belongs to.
330      * @param zygotePolicyFlags Flags used to determine how to launch the application.
331      * @param isTopApp Whether the process starts for high priority application.
332      * @param disabledCompatChanges null-ok list of disabled compat changes for the process being
333      *                             started.
334      * @param pkgDataInfoMap Map from related package names to private data directory
335      *                       volume UUID and inode number.
336      * @param allowlistedDataInfoList Map from allowlisted package names to private data directory
337      *                       volume UUID and inode number.
338      * @param bindMountAppsData whether zygote needs to mount CE and DE data.
339      * @param bindMountAppStorageDirs whether zygote needs to mount Android/obb and Android/data.
340      *
341      * @param zygoteArgs Additional arguments to supply to the Zygote process.
342      * @return An object that describes the result of the attempt to start the process.
343      * @throws RuntimeException on fatal start failure
344      */
start(@onNull final String processClass, final String niceName, int uid, int gid, @Nullable int[] gids, int runtimeFlags, int mountExternal, int targetSdkVersion, @Nullable String seInfo, @NonNull String abi, @Nullable String instructionSet, @Nullable String appDataDir, @Nullable String invokeWith, @Nullable String packageName, int zygotePolicyFlags, boolean isTopApp, @Nullable long[] disabledCompatChanges, @Nullable Map<String, Pair<String, Long>> pkgDataInfoMap, @Nullable Map<String, Pair<String, Long>> allowlistedDataInfoList, boolean bindMountAppsData, boolean bindMountAppStorageDirs, @Nullable String[] zygoteArgs)345     public final Process.ProcessStartResult start(@NonNull final String processClass,
346                                                   final String niceName,
347                                                   int uid, int gid, @Nullable int[] gids,
348                                                   int runtimeFlags, int mountExternal,
349                                                   int targetSdkVersion,
350                                                   @Nullable String seInfo,
351                                                   @NonNull String abi,
352                                                   @Nullable String instructionSet,
353                                                   @Nullable String appDataDir,
354                                                   @Nullable String invokeWith,
355                                                   @Nullable String packageName,
356                                                   int zygotePolicyFlags,
357                                                   boolean isTopApp,
358                                                   @Nullable long[] disabledCompatChanges,
359                                                   @Nullable Map<String, Pair<String, Long>>
360                                                           pkgDataInfoMap,
361                                                   @Nullable Map<String, Pair<String, Long>>
362                                                           allowlistedDataInfoList,
363                                                   boolean bindMountAppsData,
364                                                   boolean bindMountAppStorageDirs,
365                                                   @Nullable String[] zygoteArgs) {
366         // TODO (chriswailes): Is there a better place to check this value?
367         if (fetchUsapPoolEnabledPropWithMinInterval()) {
368             informZygotesOfUsapPoolStatus();
369         }
370 
371         try {
372             return startViaZygote(processClass, niceName, uid, gid, gids,
373                     runtimeFlags, mountExternal, targetSdkVersion, seInfo,
374                     abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
375                     packageName, zygotePolicyFlags, isTopApp, disabledCompatChanges,
376                     pkgDataInfoMap, allowlistedDataInfoList, bindMountAppsData,
377                     bindMountAppStorageDirs, zygoteArgs);
378         } catch (ZygoteStartFailedEx ex) {
379             Log.e(LOG_TAG,
380                     "Starting VM process through Zygote failed");
381             throw new RuntimeException(
382                     "Starting VM process through Zygote failed", ex);
383         }
384     }
385 
386     /** retry interval for opening a zygote socket */
387     static final int ZYGOTE_RETRY_MILLIS = 500;
388 
389     /**
390      * Queries the zygote for the list of ABIS it supports.
391      */
392     @GuardedBy("mLock")
getAbiList(BufferedWriter writer, DataInputStream inputStream)393     private static List<String> getAbiList(BufferedWriter writer, DataInputStream inputStream)
394             throws IOException {
395         // Each query starts with the argument count (1 in this case)
396         writer.write("1");
397         // ... followed by a new-line.
398         writer.newLine();
399         // ... followed by our only argument.
400         writer.write("--query-abi-list");
401         writer.newLine();
402         writer.flush();
403 
404         // The response is a length prefixed stream of ASCII bytes.
405         int numBytes = inputStream.readInt();
406         byte[] bytes = new byte[numBytes];
407         inputStream.readFully(bytes);
408 
409         final String rawList = new String(bytes, StandardCharsets.US_ASCII);
410 
411         return Arrays.asList(rawList.split(","));
412     }
413 
414     /**
415      * Sends an argument list to the zygote process, which starts a new child
416      * and returns the child's pid. Please note: the present implementation
417      * replaces newlines in the argument list with spaces.
418      *
419      * @throws ZygoteStartFailedEx if process start failed for any reason
420      */
421     @GuardedBy("mLock")
zygoteSendArgsAndGetResult( ZygoteState zygoteState, int zygotePolicyFlags, @NonNull ArrayList<String> args)422     private Process.ProcessStartResult zygoteSendArgsAndGetResult(
423             ZygoteState zygoteState, int zygotePolicyFlags, @NonNull ArrayList<String> args)
424             throws ZygoteStartFailedEx {
425         // Throw early if any of the arguments are malformed. This means we can
426         // avoid writing a partial response to the zygote.
427         for (String arg : args) {
428             // Making two indexOf calls here is faster than running a manually fused loop due
429             // to the fact that indexOf is an optimized intrinsic.
430             if (arg.indexOf('\n') >= 0) {
431                 throw new ZygoteStartFailedEx("Embedded newlines not allowed");
432             } else if (arg.indexOf('\r') >= 0) {
433                 throw new ZygoteStartFailedEx("Embedded carriage returns not allowed");
434             }
435         }
436 
437         /*
438          * See com.android.internal.os.ZygoteArguments.parseArgs()
439          * Presently the wire format to the zygote process is:
440          * a) a count of arguments (argc, in essence)
441          * b) a number of newline-separated argument strings equal to count
442          *
443          * After the zygote process reads these it will write the pid of
444          * the child or -1 on failure, followed by boolean to
445          * indicate whether a wrapper process was used.
446          */
447         String msgStr = args.size() + "\n" + String.join("\n", args) + "\n";
448 
449         if (shouldAttemptUsapLaunch(zygotePolicyFlags, args)) {
450             try {
451                 return attemptUsapSendArgsAndGetResult(zygoteState, msgStr);
452             } catch (IOException ex) {
453                 // If there was an IOException using the USAP pool we will log the error and
454                 // attempt to start the process through the Zygote.
455                 Log.e(LOG_TAG, "IO Exception while communicating with USAP pool - "
456                         + ex.getMessage());
457             }
458         }
459 
460         return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);
461     }
462 
attemptZygoteSendArgsAndGetResult( ZygoteState zygoteState, String msgStr)463     private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(
464             ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {
465         try {
466             final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
467             final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;
468 
469             zygoteWriter.write(msgStr);
470             zygoteWriter.flush();
471 
472             // Always read the entire result from the input stream to avoid leaving
473             // bytes in the stream for future process starts to accidentally stumble
474             // upon.
475             Process.ProcessStartResult result = new Process.ProcessStartResult();
476             result.pid = zygoteInputStream.readInt();
477             result.usingWrapper = zygoteInputStream.readBoolean();
478 
479             if (result.pid < 0) {
480                 throw new ZygoteStartFailedEx("fork() failed");
481             }
482 
483             return result;
484         } catch (IOException ex) {
485             zygoteState.close();
486             Log.e(LOG_TAG, "IO Exception while communicating with Zygote - "
487                     + ex.toString());
488             throw new ZygoteStartFailedEx(ex);
489         }
490     }
491 
attemptUsapSendArgsAndGetResult( ZygoteState zygoteState, String msgStr)492     private Process.ProcessStartResult attemptUsapSendArgsAndGetResult(
493             ZygoteState zygoteState, String msgStr)
494             throws ZygoteStartFailedEx, IOException {
495         try (LocalSocket usapSessionSocket = zygoteState.getUsapSessionSocket()) {
496             final BufferedWriter usapWriter =
497                     new BufferedWriter(
498                             new OutputStreamWriter(usapSessionSocket.getOutputStream()),
499                             Zygote.SOCKET_BUFFER_SIZE);
500             final DataInputStream usapReader =
501                     new DataInputStream(usapSessionSocket.getInputStream());
502 
503             usapWriter.write(msgStr);
504             usapWriter.flush();
505 
506             Process.ProcessStartResult result = new Process.ProcessStartResult();
507             result.pid = usapReader.readInt();
508             // USAPs can't be used to spawn processes that need wrappers.
509             result.usingWrapper = false;
510 
511             if (result.pid >= 0) {
512                 return result;
513             } else {
514                 throw new ZygoteStartFailedEx("USAP specialization failed");
515             }
516         }
517     }
518 
519     /**
520      * Test various member properties and parameters to determine if a launch event should be
521      * handled using an Unspecialized App Process Pool or not.
522      *
523      * @param zygotePolicyFlags Policy flags indicating special behavioral observations about the
524      *                          Zygote command
525      * @param args Arguments that will be passed to the Zygote
526      * @return If the command should be sent to a USAP Pool member or an actual Zygote
527      */
shouldAttemptUsapLaunch(int zygotePolicyFlags, ArrayList<String> args)528     private boolean shouldAttemptUsapLaunch(int zygotePolicyFlags, ArrayList<String> args) {
529         return mUsapPoolSupported
530                 && mUsapPoolEnabled
531                 && policySpecifiesUsapPoolLaunch(zygotePolicyFlags)
532                 && commandSupportedByUsap(args);
533     }
534 
535     /**
536      * Tests a Zygote policy flag set for various properties that determine if it is eligible for
537      * being handled by an Unspecialized App Process Pool.
538      *
539      * @param zygotePolicyFlags Policy flags indicating special behavioral observations about the
540      *                          Zygote command
541      * @return If the policy allows for use of a USAP pool
542      */
policySpecifiesUsapPoolLaunch(int zygotePolicyFlags)543     private static boolean policySpecifiesUsapPoolLaunch(int zygotePolicyFlags) {
544         /*
545          * Zygote USAP Pool Policy: Launch the new process from the USAP Pool iff the launch event
546          * is latency sensitive but *NOT* a system process.  All system processes are equally
547          * important so we don't want to prioritize one over another.
548          */
549         return (zygotePolicyFlags
550                 & (ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS | ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE))
551                 == ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
552     }
553 
554     /**
555      * Flags that may not be passed to a USAP.  These may appear as prefixes to individual Zygote
556      * arguments.
557      */
558     private static final String[] INVALID_USAP_FLAGS = {
559         "--query-abi-list",
560         "--get-pid",
561         "--preload-default",
562         "--preload-package",
563         "--preload-app",
564         "--start-child-zygote",
565         "--set-api-denylist-exemptions",
566         "--hidden-api-log-sampling-rate",
567         "--hidden-api-statslog-sampling-rate",
568         "--invoke-with"
569     };
570 
571     /**
572      * Tests a command list to see if it is valid to send to a USAP.
573      *
574      * @param args  Zygote/USAP command arguments
575      * @return  True if the command can be passed to a USAP; false otherwise
576      */
commandSupportedByUsap(ArrayList<String> args)577     private static boolean commandSupportedByUsap(ArrayList<String> args) {
578         for (String flag : args) {
579             for (String badFlag : INVALID_USAP_FLAGS) {
580                 if (flag.startsWith(badFlag)) {
581                     return false;
582                 }
583             }
584             if (flag.startsWith("--nice-name=")) {
585                 // Check if the wrap property is set, usap would ignore it.
586                 if (Zygote.getWrapProperty(flag.substring(12)) != null) {
587                     return false;
588                 }
589             }
590         }
591 
592         return true;
593     }
594 
595     /**
596      * Starts a new process via the zygote mechanism.
597      *
598      * @param processClass Class name whose static main() to run
599      * @param niceName 'nice' process name to appear in ps
600      * @param uid a POSIX uid that the new process should setuid() to
601      * @param gid a POSIX gid that the new process shuold setgid() to
602      * @param gids null-ok; a list of supplementary group IDs that the
603      * new process should setgroup() to.
604      * @param runtimeFlags Additional flags for the runtime.
605      * @param targetSdkVersion The target SDK version for the app.
606      * @param seInfo null-ok SELinux information for the new process.
607      * @param abi the ABI the process should use.
608      * @param instructionSet null-ok the instruction set to use.
609      * @param appDataDir null-ok the data directory of the app.
610      * @param startChildZygote Start a sub-zygote. This creates a new zygote process
611      * that has its state cloned from this zygote process.
612      * @param packageName null-ok the name of the package this process belongs to.
613      * @param zygotePolicyFlags Flags used to determine how to launch the application.
614      * @param isTopApp Whether the process starts for high priority application.
615      * @param disabledCompatChanges a list of disabled compat changes for the process being started.
616      * @param pkgDataInfoMap Map from related package names to private data directory volume UUID
617      *                       and inode number.
618      * @param allowlistedDataInfoList Map from allowlisted package names to private data directory
619      *                       volume UUID and inode number.
620      * @param bindMountAppsData whether zygote needs to mount CE and DE data.
621      * @param bindMountAppStorageDirs whether zygote needs to mount Android/obb and Android/data.
622      * @param extraArgs Additional arguments to supply to the zygote process.
623      * @return An object that describes the result of the attempt to start the process.
624      * @throws ZygoteStartFailedEx if process start failed for any reason
625      */
startViaZygote(@onNull final String processClass, @Nullable final String niceName, final int uid, final int gid, @Nullable final int[] gids, int runtimeFlags, int mountExternal, int targetSdkVersion, @Nullable String seInfo, @NonNull String abi, @Nullable String instructionSet, @Nullable String appDataDir, @Nullable String invokeWith, boolean startChildZygote, @Nullable String packageName, int zygotePolicyFlags, boolean isTopApp, @Nullable long[] disabledCompatChanges, @Nullable Map<String, Pair<String, Long>> pkgDataInfoMap, @Nullable Map<String, Pair<String, Long>> allowlistedDataInfoList, boolean bindMountAppsData, boolean bindMountAppStorageDirs, @Nullable String[] extraArgs)626     private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
627                                                       @Nullable final String niceName,
628                                                       final int uid, final int gid,
629                                                       @Nullable final int[] gids,
630                                                       int runtimeFlags, int mountExternal,
631                                                       int targetSdkVersion,
632                                                       @Nullable String seInfo,
633                                                       @NonNull String abi,
634                                                       @Nullable String instructionSet,
635                                                       @Nullable String appDataDir,
636                                                       @Nullable String invokeWith,
637                                                       boolean startChildZygote,
638                                                       @Nullable String packageName,
639                                                       int zygotePolicyFlags,
640                                                       boolean isTopApp,
641                                                       @Nullable long[] disabledCompatChanges,
642                                                       @Nullable Map<String, Pair<String, Long>>
643                                                               pkgDataInfoMap,
644                                                       @Nullable Map<String, Pair<String, Long>>
645                                                               allowlistedDataInfoList,
646                                                       boolean bindMountAppsData,
647                                                       boolean bindMountAppStorageDirs,
648                                                       @Nullable String[] extraArgs)
649                                                       throws ZygoteStartFailedEx {
650         ArrayList<String> argsForZygote = new ArrayList<>();
651 
652         // --runtime-args, --setuid=, --setgid=,
653         // and --setgroups= must go first
654         argsForZygote.add("--runtime-args");
655         argsForZygote.add("--setuid=" + uid);
656         argsForZygote.add("--setgid=" + gid);
657         argsForZygote.add("--runtime-flags=" + runtimeFlags);
658         if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
659             argsForZygote.add("--mount-external-default");
660         } else if (mountExternal == Zygote.MOUNT_EXTERNAL_INSTALLER) {
661             argsForZygote.add("--mount-external-installer");
662         } else if (mountExternal == Zygote.MOUNT_EXTERNAL_PASS_THROUGH) {
663             argsForZygote.add("--mount-external-pass-through");
664         } else if (mountExternal == Zygote.MOUNT_EXTERNAL_ANDROID_WRITABLE) {
665             argsForZygote.add("--mount-external-android-writable");
666         }
667 
668         argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
669 
670         // --setgroups is a comma-separated list
671         if (gids != null && gids.length > 0) {
672             final StringBuilder sb = new StringBuilder();
673             sb.append("--setgroups=");
674 
675             final int sz = gids.length;
676             for (int i = 0; i < sz; i++) {
677                 if (i != 0) {
678                     sb.append(',');
679                 }
680                 sb.append(gids[i]);
681             }
682 
683             argsForZygote.add(sb.toString());
684         }
685 
686         if (niceName != null) {
687             argsForZygote.add("--nice-name=" + niceName);
688         }
689 
690         if (seInfo != null) {
691             argsForZygote.add("--seinfo=" + seInfo);
692         }
693 
694         if (instructionSet != null) {
695             argsForZygote.add("--instruction-set=" + instructionSet);
696         }
697 
698         if (appDataDir != null) {
699             argsForZygote.add("--app-data-dir=" + appDataDir);
700         }
701 
702         if (invokeWith != null) {
703             argsForZygote.add("--invoke-with");
704             argsForZygote.add(invokeWith);
705         }
706 
707         if (startChildZygote) {
708             argsForZygote.add("--start-child-zygote");
709         }
710 
711         if (packageName != null) {
712             argsForZygote.add("--package-name=" + packageName);
713         }
714 
715         if (isTopApp) {
716             argsForZygote.add(Zygote.START_AS_TOP_APP_ARG);
717         }
718         if (pkgDataInfoMap != null && pkgDataInfoMap.size() > 0) {
719             StringBuilder sb = new StringBuilder();
720             sb.append(Zygote.PKG_DATA_INFO_MAP);
721             sb.append("=");
722             boolean started = false;
723             for (Map.Entry<String, Pair<String, Long>> entry : pkgDataInfoMap.entrySet()) {
724                 if (started) {
725                     sb.append(',');
726                 }
727                 started = true;
728                 sb.append(entry.getKey());
729                 sb.append(',');
730                 sb.append(entry.getValue().first);
731                 sb.append(',');
732                 sb.append(entry.getValue().second);
733             }
734             argsForZygote.add(sb.toString());
735         }
736         if (allowlistedDataInfoList != null && allowlistedDataInfoList.size() > 0) {
737             StringBuilder sb = new StringBuilder();
738             sb.append(Zygote.ALLOWLISTED_DATA_INFO_MAP);
739             sb.append("=");
740             boolean started = false;
741             for (Map.Entry<String, Pair<String, Long>> entry : allowlistedDataInfoList.entrySet()) {
742                 if (started) {
743                     sb.append(',');
744                 }
745                 started = true;
746                 sb.append(entry.getKey());
747                 sb.append(',');
748                 sb.append(entry.getValue().first);
749                 sb.append(',');
750                 sb.append(entry.getValue().second);
751             }
752             argsForZygote.add(sb.toString());
753         }
754 
755         if (bindMountAppStorageDirs) {
756             argsForZygote.add(Zygote.BIND_MOUNT_APP_STORAGE_DIRS);
757         }
758 
759         if (bindMountAppsData) {
760             argsForZygote.add(Zygote.BIND_MOUNT_APP_DATA_DIRS);
761         }
762 
763         if (disabledCompatChanges != null && disabledCompatChanges.length > 0) {
764             StringBuilder sb = new StringBuilder();
765             sb.append("--disabled-compat-changes=");
766 
767             int sz = disabledCompatChanges.length;
768             for (int i = 0; i < sz; i++) {
769                 if (i != 0) {
770                     sb.append(',');
771                 }
772                 sb.append(disabledCompatChanges[i]);
773             }
774 
775             argsForZygote.add(sb.toString());
776         }
777 
778         argsForZygote.add(processClass);
779 
780         if (extraArgs != null) {
781             Collections.addAll(argsForZygote, extraArgs);
782         }
783 
784         synchronized(mLock) {
785             // The USAP pool can not be used if the application will not use the systems graphics
786             // driver.  If that driver is requested use the Zygote application start path.
787             return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
788                                               zygotePolicyFlags,
789                                               argsForZygote);
790         }
791     }
792 
fetchUsapPoolEnabledProp()793     private boolean fetchUsapPoolEnabledProp() {
794         boolean origVal = mUsapPoolEnabled;
795 
796         final String propertyString = Zygote.getConfigurationProperty(
797                 ZygoteConfig.USAP_POOL_ENABLED, USAP_POOL_ENABLED_DEFAULT);
798 
799         if (!propertyString.isEmpty()) {
800             mUsapPoolEnabled = Zygote.getConfigurationPropertyBoolean(
801                   ZygoteConfig.USAP_POOL_ENABLED,
802                   Boolean.parseBoolean(USAP_POOL_ENABLED_DEFAULT));
803         }
804 
805         boolean valueChanged = origVal != mUsapPoolEnabled;
806 
807         if (valueChanged) {
808             Log.i(LOG_TAG, "usapPoolEnabled = " + mUsapPoolEnabled);
809         }
810 
811         return valueChanged;
812     }
813 
814     private boolean mIsFirstPropCheck = true;
815     private long mLastPropCheckTimestamp = 0;
816 
fetchUsapPoolEnabledPropWithMinInterval()817     private boolean fetchUsapPoolEnabledPropWithMinInterval() {
818         // If this Zygote doesn't support USAPs there is no need to fetch any
819         // properties.
820         if (!mUsapPoolSupported) return false;
821 
822         final long currentTimestamp = SystemClock.elapsedRealtime();
823 
824         if (mIsFirstPropCheck
825                 || (currentTimestamp - mLastPropCheckTimestamp >= Zygote.PROPERTY_CHECK_INTERVAL)) {
826             mIsFirstPropCheck = false;
827             mLastPropCheckTimestamp = currentTimestamp;
828             return fetchUsapPoolEnabledProp();
829         }
830 
831         return false;
832     }
833 
834     /**
835      * Closes the connections to the zygote, if they exist.
836      */
close()837     public void close() {
838         if (primaryZygoteState != null) {
839             primaryZygoteState.close();
840         }
841         if (secondaryZygoteState != null) {
842             secondaryZygoteState.close();
843         }
844     }
845 
846     /**
847      * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block
848      * and retry if the zygote is unresponsive. This method is a no-op if a connection is
849      * already open.
850      */
establishZygoteConnectionForAbi(String abi)851     public void establishZygoteConnectionForAbi(String abi) {
852         try {
853             synchronized(mLock) {
854                 openZygoteSocketIfNeeded(abi);
855             }
856         } catch (ZygoteStartFailedEx ex) {
857             throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
858         }
859     }
860 
861     /**
862      * Attempt to retrieve the PID of the zygote serving the given abi.
863      */
getZygotePid(String abi)864     public int getZygotePid(String abi) {
865         try {
866             synchronized (mLock) {
867                 ZygoteState state = openZygoteSocketIfNeeded(abi);
868 
869                 // Each query starts with the argument count (1 in this case)
870                 state.mZygoteOutputWriter.write("1");
871                 // ... followed by a new-line.
872                 state.mZygoteOutputWriter.newLine();
873                 // ... followed by our only argument.
874                 state.mZygoteOutputWriter.write("--get-pid");
875                 state.mZygoteOutputWriter.newLine();
876                 state.mZygoteOutputWriter.flush();
877 
878                 // The response is a length prefixed stream of ASCII bytes.
879                 int numBytes = state.mZygoteInputStream.readInt();
880                 byte[] bytes = new byte[numBytes];
881                 state.mZygoteInputStream.readFully(bytes);
882 
883                 return Integer.parseInt(new String(bytes, StandardCharsets.US_ASCII));
884             }
885         } catch (Exception ex) {
886             throw new RuntimeException("Failure retrieving pid", ex);
887         }
888     }
889 
890     /**
891      * Notify the Zygote processes that boot completed.
892      */
bootCompleted()893     public void bootCompleted() {
894         // Notify both the 32-bit and 64-bit zygote.
895         if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
896             bootCompleted(Build.SUPPORTED_32_BIT_ABIS[0]);
897         }
898         if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
899             bootCompleted(Build.SUPPORTED_64_BIT_ABIS[0]);
900         }
901     }
902 
bootCompleted(String abi)903     private void bootCompleted(String abi) {
904         try {
905             synchronized (mLock) {
906                 ZygoteState state = openZygoteSocketIfNeeded(abi);
907                 state.mZygoteOutputWriter.write("1\n--boot-completed\n");
908                 state.mZygoteOutputWriter.flush();
909                 state.mZygoteInputStream.readInt();
910             }
911         } catch (Exception ex) {
912             throw new RuntimeException("Failed to inform zygote of boot_completed", ex);
913         }
914     }
915 
916     /**
917      * Push hidden API deny-listing exemptions into the zygote process(es).
918      *
919      * <p>The list of exemptions will take affect for all new processes forked from the zygote after
920      * this call.
921      *
922      * @param exemptions List of hidden API exemption prefixes. Any matching members are treated as
923      *        allowed/public APIs (i.e. allowed, no logging of usage).
924      */
setApiDenylistExemptions(List<String> exemptions)925     public boolean setApiDenylistExemptions(List<String> exemptions) {
926         synchronized (mLock) {
927             mApiDenylistExemptions = exemptions;
928             boolean ok = maybeSetApiDenylistExemptions(primaryZygoteState, true);
929             if (ok) {
930                 ok = maybeSetApiDenylistExemptions(secondaryZygoteState, true);
931             }
932             return ok;
933         }
934     }
935 
936     /**
937      * Set the precentage of detected hidden API accesses that are logged to the event log.
938      *
939      * <p>This rate will take affect for all new processes forked from the zygote after this call.
940      *
941      * @param rate An integer between 0 and 0x10000 inclusive. 0 means no event logging.
942      */
setHiddenApiAccessLogSampleRate(int rate)943     public void setHiddenApiAccessLogSampleRate(int rate) {
944         synchronized (mLock) {
945             mHiddenApiAccessLogSampleRate = rate;
946             maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
947             maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
948         }
949     }
950 
951     /**
952      * Set the precentage of detected hidden API accesses that are logged to the new event log.
953      *
954      * <p>This rate will take affect for all new processes forked from the zygote after this call.
955      *
956      * @param rate An integer between 0 and 0x10000 inclusive. 0 means no event logging.
957      */
setHiddenApiAccessStatslogSampleRate(int rate)958     public void setHiddenApiAccessStatslogSampleRate(int rate) {
959         synchronized (mLock) {
960             mHiddenApiAccessStatslogSampleRate = rate;
961             maybeSetHiddenApiAccessStatslogSampleRate(primaryZygoteState);
962             maybeSetHiddenApiAccessStatslogSampleRate(secondaryZygoteState);
963         }
964     }
965 
966     @GuardedBy("mLock")
maybeSetApiDenylistExemptions(ZygoteState state, boolean sendIfEmpty)967     private boolean maybeSetApiDenylistExemptions(ZygoteState state, boolean sendIfEmpty) {
968         if (state == null || state.isClosed()) {
969             Slog.e(LOG_TAG, "Can't set API denylist exemptions: no zygote connection");
970             return false;
971         } else if (!sendIfEmpty && mApiDenylistExemptions.isEmpty()) {
972             return true;
973         }
974 
975         try {
976             state.mZygoteOutputWriter.write(Integer.toString(mApiDenylistExemptions.size() + 1));
977             state.mZygoteOutputWriter.newLine();
978             state.mZygoteOutputWriter.write("--set-api-denylist-exemptions");
979             state.mZygoteOutputWriter.newLine();
980             for (int i = 0; i < mApiDenylistExemptions.size(); ++i) {
981                 state.mZygoteOutputWriter.write(mApiDenylistExemptions.get(i));
982                 state.mZygoteOutputWriter.newLine();
983             }
984             state.mZygoteOutputWriter.flush();
985             int status = state.mZygoteInputStream.readInt();
986             if (status != 0) {
987                 Slog.e(LOG_TAG, "Failed to set API denylist exemptions; status " + status);
988             }
989             return true;
990         } catch (IOException ioe) {
991             Slog.e(LOG_TAG, "Failed to set API denylist exemptions", ioe);
992             mApiDenylistExemptions = Collections.emptyList();
993             return false;
994         }
995     }
996 
maybeSetHiddenApiAccessLogSampleRate(ZygoteState state)997     private void maybeSetHiddenApiAccessLogSampleRate(ZygoteState state) {
998         if (state == null || state.isClosed() || mHiddenApiAccessLogSampleRate == -1) {
999             return;
1000         }
1001 
1002         try {
1003             state.mZygoteOutputWriter.write(Integer.toString(1));
1004             state.mZygoteOutputWriter.newLine();
1005             state.mZygoteOutputWriter.write("--hidden-api-log-sampling-rate="
1006                     + mHiddenApiAccessLogSampleRate);
1007             state.mZygoteOutputWriter.newLine();
1008             state.mZygoteOutputWriter.flush();
1009             int status = state.mZygoteInputStream.readInt();
1010             if (status != 0) {
1011                 Slog.e(LOG_TAG, "Failed to set hidden API log sampling rate; status " + status);
1012             }
1013         } catch (IOException ioe) {
1014             Slog.e(LOG_TAG, "Failed to set hidden API log sampling rate", ioe);
1015         }
1016     }
1017 
maybeSetHiddenApiAccessStatslogSampleRate(ZygoteState state)1018     private void maybeSetHiddenApiAccessStatslogSampleRate(ZygoteState state) {
1019         if (state == null || state.isClosed() || mHiddenApiAccessStatslogSampleRate == -1) {
1020             return;
1021         }
1022 
1023         try {
1024             state.mZygoteOutputWriter.write(Integer.toString(1));
1025             state.mZygoteOutputWriter.newLine();
1026             state.mZygoteOutputWriter.write("--hidden-api-statslog-sampling-rate="
1027                     + mHiddenApiAccessStatslogSampleRate);
1028             state.mZygoteOutputWriter.newLine();
1029             state.mZygoteOutputWriter.flush();
1030             int status = state.mZygoteInputStream.readInt();
1031             if (status != 0) {
1032                 Slog.e(LOG_TAG, "Failed to set hidden API statslog sampling rate; status "
1033                         + status);
1034             }
1035         } catch (IOException ioe) {
1036             Slog.e(LOG_TAG, "Failed to set hidden API statslog sampling rate", ioe);
1037         }
1038     }
1039 
1040     /**
1041      * Creates a ZygoteState for the primary zygote if it doesn't exist or has been disconnected.
1042      */
1043     @GuardedBy("mLock")
attemptConnectionToPrimaryZygote()1044     private void attemptConnectionToPrimaryZygote() throws IOException {
1045         if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
1046             primaryZygoteState =
1047                     ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress);
1048 
1049             maybeSetApiDenylistExemptions(primaryZygoteState, false);
1050             maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
1051         }
1052     }
1053 
1054     /**
1055      * Creates a ZygoteState for the secondary zygote if it doesn't exist or has been disconnected.
1056      */
1057     @GuardedBy("mLock")
attemptConnectionToSecondaryZygote()1058     private void attemptConnectionToSecondaryZygote() throws IOException {
1059         if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
1060             secondaryZygoteState =
1061                     ZygoteState.connect(mZygoteSecondarySocketAddress,
1062                             mUsapPoolSecondarySocketAddress);
1063 
1064             maybeSetApiDenylistExemptions(secondaryZygoteState, false);
1065             maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
1066         }
1067     }
1068 
1069     /**
1070      * Tries to open a session socket to a Zygote process with a compatible ABI if one is not
1071      * already open. If a compatible session socket is already open that session socket is returned.
1072      * This function may block and may have to try connecting to multiple Zygotes to find the
1073      * appropriate one.  Requires that mLock be held.
1074      */
1075     @GuardedBy("mLock")
openZygoteSocketIfNeeded(String abi)1076     private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
1077         try {
1078             attemptConnectionToPrimaryZygote();
1079 
1080             if (primaryZygoteState.matches(abi)) {
1081                 return primaryZygoteState;
1082             }
1083 
1084             if (mZygoteSecondarySocketAddress != null) {
1085                 // The primary zygote didn't match. Try the secondary.
1086                 attemptConnectionToSecondaryZygote();
1087 
1088                 if (secondaryZygoteState.matches(abi)) {
1089                     return secondaryZygoteState;
1090                 }
1091             }
1092         } catch (IOException ioe) {
1093             throw new ZygoteStartFailedEx("Error connecting to zygote", ioe);
1094         }
1095 
1096         throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
1097     }
1098 
1099     /**
1100      * Instructs the zygote to pre-load the application code for the given Application.
1101      * Only the app zygote supports this function.
1102      * TODO preloadPackageForAbi() can probably be removed and the callers an use this instead.
1103      */
preloadApp(ApplicationInfo appInfo, String abi)1104     public boolean preloadApp(ApplicationInfo appInfo, String abi)
1105             throws ZygoteStartFailedEx, IOException {
1106         synchronized (mLock) {
1107             ZygoteState state = openZygoteSocketIfNeeded(abi);
1108             state.mZygoteOutputWriter.write("2");
1109             state.mZygoteOutputWriter.newLine();
1110 
1111             state.mZygoteOutputWriter.write("--preload-app");
1112             state.mZygoteOutputWriter.newLine();
1113 
1114             // Zygote args needs to be strings, so in order to pass ApplicationInfo,
1115             // write it to a Parcel, and base64 the raw Parcel bytes to the other side.
1116             Parcel parcel = Parcel.obtain();
1117             appInfo.writeToParcel(parcel, 0 /* flags */);
1118             String encodedParcelData = Base64.getEncoder().encodeToString(parcel.marshall());
1119             parcel.recycle();
1120             state.mZygoteOutputWriter.write(encodedParcelData);
1121             state.mZygoteOutputWriter.newLine();
1122 
1123             state.mZygoteOutputWriter.flush();
1124 
1125             return (state.mZygoteInputStream.readInt() == 0);
1126         }
1127     }
1128 
1129     /**
1130      * Instructs the zygote to pre-load the classes and native libraries at the given paths
1131      * for the specified abi. Not all zygotes support this function.
1132      */
preloadPackageForAbi( String packagePath, String libsPath, String libFileName, String cacheKey, String abi)1133     public boolean preloadPackageForAbi(
1134             String packagePath, String libsPath, String libFileName, String cacheKey, String abi)
1135             throws ZygoteStartFailedEx, IOException {
1136         synchronized (mLock) {
1137             ZygoteState state = openZygoteSocketIfNeeded(abi);
1138             state.mZygoteOutputWriter.write("5");
1139             state.mZygoteOutputWriter.newLine();
1140 
1141             state.mZygoteOutputWriter.write("--preload-package");
1142             state.mZygoteOutputWriter.newLine();
1143 
1144             state.mZygoteOutputWriter.write(packagePath);
1145             state.mZygoteOutputWriter.newLine();
1146 
1147             state.mZygoteOutputWriter.write(libsPath);
1148             state.mZygoteOutputWriter.newLine();
1149 
1150             state.mZygoteOutputWriter.write(libFileName);
1151             state.mZygoteOutputWriter.newLine();
1152 
1153             state.mZygoteOutputWriter.write(cacheKey);
1154             state.mZygoteOutputWriter.newLine();
1155 
1156             state.mZygoteOutputWriter.flush();
1157 
1158             return (state.mZygoteInputStream.readInt() == 0);
1159         }
1160     }
1161 
1162     /**
1163      * Instructs the zygote to preload the default set of classes and resources. Returns
1164      * {@code true} if a preload was performed as a result of this call, and {@code false}
1165      * otherwise. The latter usually means that the zygote eagerly preloaded at startup
1166      * or due to a previous call to {@code preloadDefault}. Note that this call is synchronous.
1167      */
preloadDefault(String abi)1168     public boolean preloadDefault(String abi) throws ZygoteStartFailedEx, IOException {
1169         synchronized (mLock) {
1170             ZygoteState state = openZygoteSocketIfNeeded(abi);
1171             // Each query starts with the argument count (1 in this case)
1172             state.mZygoteOutputWriter.write("1");
1173             state.mZygoteOutputWriter.newLine();
1174             state.mZygoteOutputWriter.write("--preload-default");
1175             state.mZygoteOutputWriter.newLine();
1176             state.mZygoteOutputWriter.flush();
1177 
1178             return (state.mZygoteInputStream.readInt() == 0);
1179         }
1180     }
1181 
1182     /**
1183      * Try connecting to the Zygote over and over again until we hit a time-out.
1184      * @param zygoteSocketName The name of the socket to connect to.
1185      */
waitForConnectionToZygote(String zygoteSocketName)1186     public static void waitForConnectionToZygote(String zygoteSocketName) {
1187         final LocalSocketAddress zygoteSocketAddress =
1188                 new LocalSocketAddress(zygoteSocketName, LocalSocketAddress.Namespace.RESERVED);
1189         waitForConnectionToZygote(zygoteSocketAddress);
1190     }
1191 
1192     /**
1193      * Try connecting to the Zygote over and over again until we hit a time-out.
1194      * @param zygoteSocketAddress The name of the socket to connect to.
1195      */
waitForConnectionToZygote(LocalSocketAddress zygoteSocketAddress)1196     public static void waitForConnectionToZygote(LocalSocketAddress zygoteSocketAddress) {
1197         int numRetries = ZYGOTE_CONNECT_TIMEOUT_MS / ZYGOTE_CONNECT_RETRY_DELAY_MS;
1198         for (int n = numRetries; n >= 0; n--) {
1199             try {
1200                 final ZygoteState zs =
1201                         ZygoteState.connect(zygoteSocketAddress, null);
1202                 zs.close();
1203                 return;
1204             } catch (IOException ioe) {
1205                 Log.w(LOG_TAG,
1206                         "Got error connecting to zygote, retrying. msg= " + ioe.getMessage());
1207             }
1208 
1209             try {
1210                 Thread.sleep(ZYGOTE_CONNECT_RETRY_DELAY_MS);
1211             } catch (InterruptedException ignored) { }
1212         }
1213         Slog.wtf(LOG_TAG, "Failed to connect to Zygote through socket "
1214                 + zygoteSocketAddress.getName());
1215     }
1216 
1217     /**
1218      * Sends messages to the zygotes telling them to change the status of their USAP pools.  If
1219      * this notification fails the ZygoteProcess will fall back to the previous behavior.
1220      */
informZygotesOfUsapPoolStatus()1221     private void informZygotesOfUsapPoolStatus() {
1222         final String command = "1\n--usap-pool-enabled=" + mUsapPoolEnabled + "\n";
1223 
1224         synchronized (mLock) {
1225             try {
1226                 attemptConnectionToPrimaryZygote();
1227 
1228                 primaryZygoteState.mZygoteOutputWriter.write(command);
1229                 primaryZygoteState.mZygoteOutputWriter.flush();
1230             } catch (IOException ioe) {
1231                 mUsapPoolEnabled = !mUsapPoolEnabled;
1232                 Log.w(LOG_TAG, "Failed to inform zygotes of USAP pool status: "
1233                         + ioe.getMessage());
1234                 return;
1235             }
1236 
1237             if (mZygoteSecondarySocketAddress != null) {
1238                 try {
1239                     attemptConnectionToSecondaryZygote();
1240 
1241                     try {
1242                         secondaryZygoteState.mZygoteOutputWriter.write(command);
1243                         secondaryZygoteState.mZygoteOutputWriter.flush();
1244 
1245                         // Wait for the secondary Zygote to finish its work.
1246                         secondaryZygoteState.mZygoteInputStream.readInt();
1247                     } catch (IOException ioe) {
1248                         throw new IllegalStateException(
1249                                 "USAP pool state change cause an irrecoverable error",
1250                                 ioe);
1251                     }
1252                 } catch (IOException ioe) {
1253                     // No secondary zygote present.  This is expected on some devices.
1254                 }
1255             }
1256 
1257             // Wait for the response from the primary zygote here so the primary/secondary zygotes
1258             // can work concurrently.
1259             try {
1260                 // Wait for the primary zygote to finish its work.
1261                 primaryZygoteState.mZygoteInputStream.readInt();
1262             } catch (IOException ioe) {
1263                 throw new IllegalStateException(
1264                         "USAP pool state change cause an irrecoverable error",
1265                         ioe);
1266             }
1267         }
1268     }
1269 
1270     /**
1271      * Starts a new zygote process as a child of this zygote. This is used to create
1272      * secondary zygotes that inherit data from the zygote that this object
1273      * communicates with. This returns a new ZygoteProcess representing a connection
1274      * to the newly created zygote. Throws an exception if the zygote cannot be started.
1275      *
1276      * @param processClass The class to use as the child zygote's main entry
1277      *                     point.
1278      * @param niceName A more readable name to use for the process.
1279      * @param uid The user-id under which the child zygote will run.
1280      * @param gid The group-id under which the child zygote will run.
1281      * @param gids Additional group-ids associated with the child zygote process.
1282      * @param runtimeFlags Additional flags.
1283      * @param seInfo null-ok SELinux information for the child zygote process.
1284      * @param abi non-null the ABI of the child zygote
1285      * @param acceptedAbiList ABIs this child zygote will accept connections for; this
1286      *                        may be different from <code>abi</code> in case the children
1287      *                        spawned from this Zygote only communicate using ABI-safe methods.
1288      * @param instructionSet null-ok the instruction set to use.
1289      * @param uidRangeStart The first UID in the range the child zygote may setuid()/setgid() to
1290      * @param uidRangeEnd The last UID in the range the child zygote may setuid()/setgid() to
1291      */
startChildZygote(final String processClass, final String niceName, int uid, int gid, int[] gids, int runtimeFlags, String seInfo, String abi, String acceptedAbiList, String instructionSet, int uidRangeStart, int uidRangeEnd)1292     public ChildZygoteProcess startChildZygote(final String processClass,
1293                                                final String niceName,
1294                                                int uid, int gid, int[] gids,
1295                                                int runtimeFlags,
1296                                                String seInfo,
1297                                                String abi,
1298                                                String acceptedAbiList,
1299                                                String instructionSet,
1300                                                int uidRangeStart,
1301                                                int uidRangeEnd) {
1302         // Create an unguessable address in the global abstract namespace.
1303         final LocalSocketAddress serverAddress = new LocalSocketAddress(
1304                 processClass + "/" + UUID.randomUUID().toString());
1305 
1306         final String[] extraArgs = {Zygote.CHILD_ZYGOTE_SOCKET_NAME_ARG + serverAddress.getName(),
1307                                     Zygote.CHILD_ZYGOTE_ABI_LIST_ARG + acceptedAbiList,
1308                                     Zygote.CHILD_ZYGOTE_UID_RANGE_START + uidRangeStart,
1309                                     Zygote.CHILD_ZYGOTE_UID_RANGE_END + uidRangeEnd};
1310 
1311         Process.ProcessStartResult result;
1312         try {
1313             // We will bind mount app data dirs so app zygote can't access /data/data, while
1314             // we don't need to bind mount storage dirs as /storage won't be mounted.
1315             result = startViaZygote(processClass, niceName, uid, gid,
1316                     gids, runtimeFlags, 0 /* mountExternal */, 0 /* targetSdkVersion */, seInfo,
1317                     abi, instructionSet, null /* appDataDir */, null /* invokeWith */,
1318                     true /* startChildZygote */, null /* packageName */,
1319                     ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS /* zygotePolicyFlags */, false /* isTopApp */,
1320                     null /* disabledCompatChanges */, null /* pkgDataInfoMap */,
1321                     null /* allowlistedDataInfoList */, true /* bindMountAppsData*/,
1322                     /* bindMountAppStorageDirs */ false, extraArgs);
1323 
1324         } catch (ZygoteStartFailedEx ex) {
1325             throw new RuntimeException("Starting child-zygote through Zygote failed", ex);
1326         }
1327 
1328         return new ChildZygoteProcess(serverAddress, result.pid);
1329     }
1330 }
1331