blob: 3859b951ed457ac982e67c4b6bc1baec16ec82f4 [file] [log] [blame]
Narayan Kamath973b4662014-03-31 13:41:26 +01001/*
2 * Copyright (C) 2014 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
17package com.android.internal.os;
18
Chris Wailesc37ebe12019-01-11 17:04:41 -080019import static android.system.OsConstants.O_CLOEXEC;
20
Chris Wailes682b4792019-01-11 16:14:43 -080021import static com.android.internal.os.ZygoteConnectionConstants.MAX_ZYGOTE_ARGC;
22
23import android.net.Credentials;
Chris Wailesc37ebe12019-01-11 17:04:41 -080024import android.net.LocalServerSocket;
25import android.net.LocalSocket;
Chris Wailes682b4792019-01-11 16:14:43 -080026import android.os.FactoryTest;
Jeff Sharkeyace874b2017-09-07 15:27:33 -060027import android.os.IVold;
Chris Wailes682b4792019-01-11 16:14:43 -080028import android.os.Process;
29import android.os.SystemProperties;
Narayan Kamathfbb32f62015-06-12 15:34:35 +010030import android.os.Trace;
Elliott Hughes860c5912014-04-28 19:19:13 -070031import android.system.ErrnoException;
32import android.system.Os;
Chris Wailes682b4792019-01-11 16:14:43 -080033import android.util.Log;
Narayan Kamath973b4662014-03-31 13:41:26 +010034
Jeff Sharkeyace874b2017-09-07 15:27:33 -060035import dalvik.system.ZygoteHooks;
Tobias Sargeantb9679dc2016-01-19 16:34:54 +000036
Chris Wailesc37ebe12019-01-11 17:04:41 -080037import libcore.io.IoUtils;
38
Chris Wailes682b4792019-01-11 16:14:43 -080039import java.io.BufferedReader;
Chris Wailesc37ebe12019-01-11 17:04:41 -080040import java.io.ByteArrayOutputStream;
41import java.io.DataOutputStream;
42import java.io.FileDescriptor;
Chris Wailes682b4792019-01-11 16:14:43 -080043import java.io.IOException;
Chris Wailesc37ebe12019-01-11 17:04:41 -080044import java.io.InputStreamReader;
Chris Wailes682b4792019-01-11 16:14:43 -080045
Narayan Kamath973b4662014-03-31 13:41:26 +010046/** @hide */
47public final class Zygote {
48 /*
Nicolas Geoffray81edac42017-09-07 14:13:29 +010049 * Bit values for "runtimeFlags" argument. The definitions are duplicated
Narayan Kamath973b4662014-03-31 13:41:26 +010050 * in the native code.
51 */
52
53 /** enable debugging over JDWP */
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000054 public static final int DEBUG_ENABLE_JDWP = 1;
Narayan Kamath973b4662014-03-31 13:41:26 +010055 /** enable JNI checks */
56 public static final int DEBUG_ENABLE_CHECKJNI = 1 << 1;
57 /** enable Java programming language "assert" statements */
58 public static final int DEBUG_ENABLE_ASSERT = 1 << 2;
Mathieu Chartier7a490282015-03-17 09:51:36 -070059 /** disable the AOT compiler and JIT */
Narayan Kamath973b4662014-03-31 13:41:26 +010060 public static final int DEBUG_ENABLE_SAFEMODE = 1 << 3;
61 /** Enable logging of third-party JNI activity. */
62 public static final int DEBUG_ENABLE_JNI_LOGGING = 1 << 4;
David Srbecky065075e2015-05-28 17:16:09 +010063 /** Force generation of native debugging information. */
Nicolas Geoffray9abbf452015-11-05 11:29:42 +000064 public static final int DEBUG_GENERATE_DEBUG_INFO = 1 << 5;
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000065 /** Always use JIT-ed code. */
66 public static final int DEBUG_ALWAYS_JIT = 1 << 6;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000067 /** Make the code native debuggable by turning off some optimizations. */
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000068 public static final int DEBUG_NATIVE_DEBUGGABLE = 1 << 7;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000069 /** Make the code Java debuggable by turning off some optimizations. */
70 public static final int DEBUG_JAVA_DEBUGGABLE = 1 << 8;
Mathieu Chartier7a490282015-03-17 09:51:36 -070071
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010072 /** Turn off the verifier. */
73 public static final int DISABLE_VERIFIER = 1 << 9;
74 /** Only use oat files located in /system. Otherwise use dex/jar/apk . */
75 public static final int ONLY_USE_SYSTEM_OAT_FILES = 1 << 10;
David Srbecky156ed922018-01-30 14:37:37 +000076 /** Force generation of native debugging information for backtraces. */
Mathew Inwood16073b82018-03-23 10:05:01 +000077 public static final int DEBUG_GENERATE_MINI_DEBUG_INFO = 1 << 11;
78 /**
79 * Hidden API access restrictions. This is a mask for bits representing the API enforcement
80 * policy, defined by {@code @ApplicationInfo.HiddenApiEnforcementPolicy}.
81 */
82 public static final int API_ENFORCEMENT_POLICY_MASK = (1 << 12) | (1 << 13);
83 /**
84 * Bit shift for use with {@link #API_ENFORCEMENT_POLICY_MASK}.
85 *
86 * (flags & API_ENFORCEMENT_POLICY_MASK) >> API_ENFORCEMENT_POLICY_SHIFT gives
87 * @ApplicationInfo.ApiEnforcementPolicy values.
88 */
89 public static final int API_ENFORCEMENT_POLICY_SHIFT =
90 Integer.numberOfTrailingZeros(API_ENFORCEMENT_POLICY_MASK);
Calin Juravle8eb891b2018-05-03 19:51:18 -070091 /**
92 * Enable system server ART profiling.
93 */
94 public static final int PROFILE_SYSTEM_SERVER = 1 << 14;
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010095
Narayan Kamath973b4662014-03-31 13:41:26 +010096 /** No external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -060097 public static final int MOUNT_EXTERNAL_NONE = IVold.REMOUNT_MODE_NONE;
Jeff Sharkey9527b222015-06-24 15:24:48 -070098 /** Default external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -060099 public static final int MOUNT_EXTERNAL_DEFAULT = IVold.REMOUNT_MODE_DEFAULT;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700100 /** Read-only external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600101 public static final int MOUNT_EXTERNAL_READ = IVold.REMOUNT_MODE_READ;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700102 /** Read-write external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600103 public static final int MOUNT_EXTERNAL_WRITE = IVold.REMOUNT_MODE_WRITE;
Narayan Kamath973b4662014-03-31 13:41:26 +0100104
Chris Wailesc37ebe12019-01-11 17:04:41 -0800105 /** Number of bytes sent to the Zygote over blastula pipes or the pool event FD */
106 public static final int BLASTULA_MANAGEMENT_MESSAGE_BYTES = 8;
107
Chris Wailescffbf1c2019-01-11 17:13:00 -0800108 /**
109 * If the blastula pool should be created and used to start applications.
110 *
111 * Setting this value to false will disable the creation, maintenance, and use of the blastula
112 * pool. When the blastula pool is disabled the application lifecycle will be identical to
113 * previous versions of Android.
114 */
Chris Wailesc37ebe12019-01-11 17:04:41 -0800115 public static final boolean BLASTULA_POOL_ENABLED = false;
116
117 /**
118 * File descriptor used for communication between the signal handler and the ZygoteServer poll
119 * loop.
120 * */
121 protected static FileDescriptor sBlastulaPoolEventFD;
122
Narayan Kamath973b4662014-03-31 13:41:26 +0100123 private static final ZygoteHooks VM_HOOKS = new ZygoteHooks();
124
Robert Sesekd0a190df2018-02-12 18:46:01 -0500125 /**
126 * An extraArg passed when a zygote process is forking a child-zygote, specifying a name
127 * in the abstract socket namespace. This socket name is what the new child zygote
128 * should listen for connections on.
129 */
130 public static final String CHILD_ZYGOTE_SOCKET_NAME_ARG = "--zygote-socket=";
131
Chris Wailesc37ebe12019-01-11 17:04:41 -0800132 /** Prefix prepended to socket names created by init */
133 private static final String ANDROID_SOCKET_PREFIX = "ANDROID_SOCKET_";
134
135 /**
136 * The maximum value that the sBlastulaPoolMax variable may take. This value
137 * is a mirror of BLASTULA_POOL_MAX_LIMIT found in com_android_internal_os_Zygote.cpp.
138 */
139 static final int BLASTULA_POOL_MAX_LIMIT = 10;
140
141 /**
142 * The minimum value that the sBlastulaPoolMin variable may take.
143 */
144 static final int BLASTULA_POOL_MIN_LIMIT = 1;
145
146 /**
147 * The runtime-adjustable maximum Blastula pool size.
148 */
149 static int sBlastulaPoolMax = BLASTULA_POOL_MAX_LIMIT;
150
151 /**
152 * The runtime-adjustable minimum Blastula pool size.
153 */
154 static int sBlastulaPoolMin = BLASTULA_POOL_MIN_LIMIT;
155
156 /**
157 * The runtime-adjustable value used to determine when to re-fill the
158 * blastula pool. The pool will be re-filled when
159 * (sBlastulaPoolMax - gBlastulaPoolCount) >= sBlastulaPoolRefillThreshold.
160 */
161 // TODO (chriswailes): This must be updated at the same time as sBlastulaPoolMax.
162 static int sBlastulaPoolRefillThreshold = (sBlastulaPoolMax / 2);
163
Chris Wailescffbf1c2019-01-11 17:13:00 -0800164 /**
165 * @hide for internal use only
166 */
167 public static final int SOCKET_BUFFER_SIZE = 256;
168
Chris Wailesc37ebe12019-01-11 17:04:41 -0800169 private static LocalServerSocket sBlastulaPoolSocket = null;
170
Chris Wailes682b4792019-01-11 16:14:43 -0800171 /** a prototype instance for a future List.toArray() */
172 protected static final int[][] INT_ARRAY_2D = new int[0][0];
173
Narayan Kamath973b4662014-03-31 13:41:26 +0100174 private Zygote() {}
175
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800176 /** Called for some security initialization before any fork. */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800177 static native void nativeSecurityInit();
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800178
Narayan Kamath973b4662014-03-31 13:41:26 +0100179 /**
180 * Forks a new VM instance. The current VM must have been started
181 * with the -Xzygote flag. <b>NOTE: new instance keeps all
182 * root capabilities. The new process is expected to call capset()</b>.
183 *
184 * @param uid the UNIX uid that the new process should setuid() to after
185 * fork()ing and and before spawning any threads.
186 * @param gid the UNIX gid that the new process should setgid() to after
187 * fork()ing and and before spawning any threads.
188 * @param gids null-ok; a list of UNIX gids that the new process should
189 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100190 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100191 * @param rlimits null-ok an array of rlimit tuples, with the second
192 * dimension having a length of 3 and representing
193 * (resource, rlim_cur, rlim_max). These are set via the posix
194 * setrlimit(2) call.
195 * @param seInfo null-ok a string specifying SELinux information for
196 * the new process.
197 * @param niceName null-ok a string specifying the process name.
198 * @param fdsToClose an array of ints, holding one or more POSIX
199 * file descriptor numbers that are to be closed by the child
200 * (and replaced by /dev/null) after forking. An integer value
201 * of -1 in any entry in the array means "ignore this one".
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800202 * @param fdsToIgnore null-ok an array of ints, either null or holding
203 * one or more POSIX file descriptor numbers that are to be ignored
204 * in the file descriptor table check.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500205 * @param startChildZygote if true, the new child process will itself be a
206 * new zygote process.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700207 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400208 * @param appDataDir null-ok the data directory of the app.
Narayan Kamath973b4662014-03-31 13:41:26 +0100209 *
210 * @return 0 if this is the child, pid of the child
211 * if this is the parent, or -1 on error.
212 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100213 public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
Chris Wailes8b35ba22019-01-10 16:55:32 -0800214 int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
215 int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100216 VM_HOOKS.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800217 // Resets nice priority for zygote process.
218 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100219 int pid = nativeForkAndSpecialize(
Chris Wailes8b35ba22019-01-10 16:55:32 -0800220 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
221 fdsToIgnore, startChildZygote, instructionSet, appDataDir);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100222 // Enable tracing as soon as possible for the child process.
223 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700224 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100225
226 // Note that this event ends at the end of handleChildProc,
227 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
228 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100229 VM_HOOKS.postForkCommon();
230 return pid;
231 }
232
Chris Wailes8b35ba22019-01-10 16:55:32 -0800233 private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
234 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
235 int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
236 String appDataDir);
237
Chris Wailesc37ebe12019-01-11 17:04:41 -0800238 /**
239 * Specialize a Blastula instance. The current VM must have been started
240 * with the -Xzygote flag.
241 *
242 * @param uid The UNIX uid that the new process should setuid() to before spawning any threads
243 * @param gid The UNIX gid that the new process should setgid() to before spawning any threads
244 * @param gids null-ok; A list of UNIX gids that the new process should
245 * setgroups() to before spawning any threads
246 * @param runtimeFlags Bit flags that enable ART features
247 * @param rlimits null-ok An array of rlimit tuples, with the second
248 * dimension having a length of 3 and representing
249 * (resource, rlim_cur, rlim_max). These are set via the posix
250 * setrlimit(2) call.
251 * @param seInfo null-ok A string specifying SELinux information for
252 * the new process.
253 * @param niceName null-ok A string specifying the process name.
254 * @param startChildZygote If true, the new child process will itself be a
255 * new zygote process.
256 * @param instructionSet null-ok The instruction set to use.
257 * @param appDataDir null-ok The data directory of the app.
258 */
259 public static void specializeBlastula(int uid, int gid, int[] gids, int runtimeFlags,
260 int[][] rlimits, int mountExternal, String seInfo, String niceName,
261 boolean startChildZygote, String instructionSet, String appDataDir) {
262
263 nativeSpecializeBlastula(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
264 niceName, startChildZygote, instructionSet, appDataDir);
265
266 // Enable tracing as soon as possible for the child process.
267 Trace.setTracingEnabled(true, runtimeFlags);
268
269 // Note that this event ends at the end of handleChildProc.
270 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
271
272 /*
273 * This is called here (instead of after the fork but before the specialize) to maintain
274 * consistancy with the code paths for forkAndSpecialize.
275 *
276 * TODO (chriswailes): Look into moving this to immediately after the fork.
277 */
278 VM_HOOKS.postForkCommon();
279 }
280
Chris Wailes8b35ba22019-01-10 16:55:32 -0800281 private static native void nativeSpecializeBlastula(int uid, int gid, int[] gids,
282 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
283 boolean startChildZygote, String instructionSet, String appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100284
285 /**
Christopher Ferris2980de42017-06-20 16:13:40 -0700286 * Called to do any initialization before starting an application.
287 */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800288 static native void nativePreApplicationInit();
Christopher Ferris2980de42017-06-20 16:13:40 -0700289
290 /**
Narayan Kamath973b4662014-03-31 13:41:26 +0100291 * Special method to start the system server process. In addition to the
292 * common actions performed in forkAndSpecialize, the pid of the child
293 * process is recorded such that the death of the child process will cause
294 * zygote to exit.
295 *
296 * @param uid the UNIX uid that the new process should setuid() to after
297 * fork()ing and and before spawning any threads.
298 * @param gid the UNIX gid that the new process should setgid() to after
299 * fork()ing and and before spawning any threads.
300 * @param gids null-ok; a list of UNIX gids that the new process should
301 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100302 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100303 * @param rlimits null-ok an array of rlimit tuples, with the second
304 * dimension having a length of 3 and representing
305 * (resource, rlim_cur, rlim_max). These are set via the posix
306 * setrlimit(2) call.
307 * @param permittedCapabilities argument for setcap()
308 * @param effectiveCapabilities argument for setcap()
309 *
310 * @return 0 if this is the child, pid of the child
311 * if this is the parent, or -1 on error.
312 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100313 public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100314 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
315 VM_HOOKS.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800316 // Resets nice priority for zygote process.
317 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100318 int pid = nativeForkSystemServer(
Chris Wailes8b35ba22019-01-10 16:55:32 -0800319 uid, gid, gids, runtimeFlags, rlimits,
320 permittedCapabilities, effectiveCapabilities);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100321 // Enable tracing as soon as we enter the system_server.
322 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700323 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100324 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100325 VM_HOOKS.postForkCommon();
326 return pid;
327 }
328
Chris Wailes8b35ba22019-01-10 16:55:32 -0800329 private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100330 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
331
doheon1.lee885b7422016-01-20 13:07:27 +0900332 /**
Robert Sesek54e387d2016-12-02 17:27:50 -0500333 * Lets children of the zygote inherit open file descriptors to this path.
334 */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800335 protected static native void nativeAllowFileAcrossFork(String path);
Robert Sesek54e387d2016-12-02 17:27:50 -0500336
337 /**
doheon1.lee885b7422016-01-20 13:07:27 +0900338 * Zygote unmount storage space on initializing.
339 * This method is called once.
340 */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800341 protected static native void nativeUnmountStorageOnInit();
342
Chris Wailesc37ebe12019-01-11 17:04:41 -0800343 /**
344 * Get socket file descriptors (opened by init) from the environment and
345 * store them for access from native code later.
346 *
347 * @param isPrimary True if this is the zygote process, false if it is zygote_secondary
348 */
349 public static void getSocketFDs(boolean isPrimary) {
350 nativeGetSocketFDs(isPrimary);
351 }
352
Chris Wailes8b35ba22019-01-10 16:55:32 -0800353 protected static native void nativeGetSocketFDs(boolean isPrimary);
354
Chris Wailesc37ebe12019-01-11 17:04:41 -0800355 /**
356 * Initialize the blastula pool and fill it with the desired number of
357 * processes.
358 */
359 protected static Runnable initBlastulaPool() {
360 if (BLASTULA_POOL_ENABLED) {
361 sBlastulaPoolEventFD = getBlastulaPoolEventFD();
362
363 return fillBlastulaPool(null);
364 } else {
365 return null;
366 }
367 }
368
369 /**
370 * Checks to see if the current policy says that pool should be refilled, and spawns new
371 * blastulas if necessary.
372 *
373 * NOTE: This function doesn't need to be guarded with BLASTULA_POOL_ENABLED because it is
374 * only called from contexts that are only valid if the pool is enabled.
375 *
376 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
377 * @return In the Zygote process this function will always return null; in blastula processes
378 * this function will return a Runnable object representing the new application that is
379 * passed up from blastulaMain.
380 */
381 protected static Runnable fillBlastulaPool(int[] sessionSocketRawFDs) {
382 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Zygote:FillBlastulaPool");
383
384 int blastulaPoolCount = getBlastulaPoolCount();
385
386 int numBlastulasToSpawn = sBlastulaPoolMax - blastulaPoolCount;
387
388 if (blastulaPoolCount < sBlastulaPoolMin
389 || numBlastulasToSpawn >= sBlastulaPoolRefillThreshold) {
390
391 // Disable some VM functionality and reset some system values
392 // before forking.
393 VM_HOOKS.preFork();
394 resetNicePriority();
395
396 while (blastulaPoolCount++ < sBlastulaPoolMax) {
397 Runnable caller = forkBlastula(sessionSocketRawFDs);
398
399 if (caller != null) {
400 return caller;
401 }
402 }
403
404 // Re-enable runtime services for the Zygote. Blastula services
405 // are re-enabled in specializeBlastula.
406 VM_HOOKS.postForkCommon();
407
408 Log.i("zygote", "Filled the blastula pool. New blastulas: " + numBlastulasToSpawn);
409 }
410
411 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
412
413 return null;
414 }
415
416 /**
417 * @return Number of blastulas currently in the pool
418 */
419 private static int getBlastulaPoolCount() {
420 return nativeGetBlastulaPoolCount();
421 }
422
Chris Wailes8b35ba22019-01-10 16:55:32 -0800423 private static native int nativeGetBlastulaPoolCount();
424
Chris Wailesc37ebe12019-01-11 17:04:41 -0800425 /**
426 * @return The event FD used for communication between the signal handler and the ZygoteServer
427 * poll loop
428 */
429 private static FileDescriptor getBlastulaPoolEventFD() {
430 FileDescriptor fd = new FileDescriptor();
431 fd.setInt$(nativeGetBlastulaPoolEventFD());
432
433 return fd;
434 }
435
Chris Wailes8b35ba22019-01-10 16:55:32 -0800436 private static native int nativeGetBlastulaPoolEventFD();
437
Chris Wailesc37ebe12019-01-11 17:04:41 -0800438 /**
439 * Fork a new blastula process from the zygote
440 *
441 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
442 * @return In the Zygote process this function will always return null; in blastula processes
443 * this function will return a Runnable object representing the new application that is
444 * passed up from blastulaMain.
445 */
446 private static Runnable forkBlastula(int[] sessionSocketRawFDs) {
447 FileDescriptor[] pipeFDs = null;
448
449 try {
450 pipeFDs = Os.pipe2(O_CLOEXEC);
451 } catch (ErrnoException errnoEx) {
452 throw new IllegalStateException("Unable to create blastula pipe.", errnoEx);
453 }
454
455 int pid =
456 nativeForkBlastula(pipeFDs[0].getInt$(), pipeFDs[1].getInt$(), sessionSocketRawFDs);
457
458 if (pid == 0) {
459 IoUtils.closeQuietly(pipeFDs[0]);
460 return blastulaMain(pipeFDs[1]);
461 } else {
462 // The read-end of the pipe will be closed by the native code.
463 // See removeBlastulaTableEntry();
464 IoUtils.closeQuietly(pipeFDs[1]);
465 return null;
466 }
467 }
468
Chris Wailes8b35ba22019-01-10 16:55:32 -0800469 private static native int nativeForkBlastula(int readPipeFD,
470 int writePipeFD,
471 int[] sessionSocketRawFDs);
472
Chris Wailesc37ebe12019-01-11 17:04:41 -0800473 /**
474 * This function is used by blastulas to wait for specialization requests from the system
475 * server.
476 *
477 * @param writePipe The write end of the reporting pipe used to communicate with the poll loop
478 * of the ZygoteServer.
479 * @return A runnable oject representing the new application.
480 */
481 static Runnable blastulaMain(FileDescriptor writePipe) {
482 final int pid = Process.myPid();
483
484 LocalSocket sessionSocket = null;
485 DataOutputStream blastulaOutputStream = null;
486 Credentials peerCredentials = null;
487 String[] argStrings = null;
488
489 while (true) {
490 try {
491 sessionSocket = sBlastulaPoolSocket.accept();
492
493 BufferedReader blastulaReader =
494 new BufferedReader(new InputStreamReader(sessionSocket.getInputStream()));
495 blastulaOutputStream =
496 new DataOutputStream(sessionSocket.getOutputStream());
497
498 peerCredentials = sessionSocket.getPeerCredentials();
499
500 argStrings = readArgumentList(blastulaReader);
501
502 if (argStrings != null) {
503 break;
504 } else {
505 Log.e("Blastula", "Truncated command received.");
506 IoUtils.closeQuietly(sessionSocket);
507 }
508 } catch (IOException ioEx) {
509 Log.e("Blastula", "Failed to read command: " + ioEx.getMessage());
510 IoUtils.closeQuietly(sessionSocket);
511 }
512 }
513
514 ZygoteArguments args = new ZygoteArguments(argStrings);
515
516 // TODO (chriswailes): Should this only be run for debug builds?
517 validateBlastulaCommand(args);
518
519 applyUidSecurityPolicy(args, peerCredentials);
520 applyDebuggerSystemProperty(args);
521
522 int[][] rlimits = null;
523
524 if (args.mRLimits != null) {
525 rlimits = args.mRLimits.toArray(INT_ARRAY_2D);
526 }
527
528 // This must happen before the SELinux policy for this process is
529 // changed when specializing.
530 try {
531 // Used by ZygoteProcess.zygoteSendArgsAndGetResult to fill in a
532 // Process.ProcessStartResult object.
533 blastulaOutputStream.writeInt(pid);
534 } catch (IOException ioEx) {
535 Log.e("Blastula", "Failed to write response to session socket: " + ioEx.getMessage());
536 System.exit(-1);
537 } finally {
538 IoUtils.closeQuietly(sessionSocket);
539 IoUtils.closeQuietly(sBlastulaPoolSocket);
540 }
541
542 try {
543 ByteArrayOutputStream buffer =
544 new ByteArrayOutputStream(Zygote.BLASTULA_MANAGEMENT_MESSAGE_BYTES);
545 DataOutputStream outputStream = new DataOutputStream(buffer);
546
547 // This is written as a long so that the blastula reporting pipe and blastula pool
548 // event FD handlers in ZygoteServer.runSelectLoop can be unified. These two cases
549 // should both send/receive 8 bytes.
550 outputStream.writeLong(pid);
551 outputStream.flush();
552
553 Os.write(writePipe, buffer.toByteArray(), 0, buffer.size());
554 } catch (Exception ex) {
555 Log.e("Blastula",
556 String.format("Failed to write PID (%d) to pipe (%d): %s",
557 pid, writePipe.getInt$(), ex.getMessage()));
558 System.exit(-1);
559 } finally {
560 IoUtils.closeQuietly(writePipe);
561 }
562
563 specializeBlastula(args.mUid, args.mGid, args.mGids,
564 args.mRuntimeFlags, rlimits, args.mMountExternal,
565 args.mSeInfo, args.mNiceName, args.mStartChildZygote,
566 args.mInstructionSet, args.mAppDataDir);
567
568 if (args.mNiceName != null) {
569 Process.setArgV0(args.mNiceName);
570 }
571
572 // End of the postFork event.
573 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
574
575 return ZygoteInit.zygoteInit(args.mTargetSdkVersion,
576 args.mRemainingArgs,
577 null /* classLoader */);
578 }
579
580 private static final String BLASTULA_ERROR_PREFIX = "Invalid command to blastula: ";
581
582 /**
583 * Checks a set of zygote arguments to see if they can be handled by a blastula. Throws an
584 * exception if an invalid arugment is encountered.
585 * @param args The arguments to test
586 */
587 static void validateBlastulaCommand(ZygoteArguments args) {
588 if (args.mAbiListQuery) {
589 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--query-abi-list");
590 } else if (args.mPidQuery) {
591 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--get-pid");
592 } else if (args.mPreloadDefault) {
593 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-default");
594 } else if (args.mPreloadPackage != null) {
595 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-package");
596 } else if (args.mStartChildZygote) {
597 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--start-child-zygote");
598 } else if (args.mApiBlacklistExemptions != null) {
599 throw new IllegalArgumentException(
600 BLASTULA_ERROR_PREFIX + "--set-api-blacklist-exemptions");
601 } else if (args.mHiddenApiAccessLogSampleRate != -1) {
602 throw new IllegalArgumentException(
603 BLASTULA_ERROR_PREFIX + "--hidden-api-log-sampling-rate=");
604 } else if (args.mInvokeWith != null) {
605 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--invoke-with");
606 } else if (args.mPermittedCapabilities != 0 || args.mEffectiveCapabilities != 0) {
607 throw new ZygoteSecurityException("Client may not specify capabilities: "
608 + "permitted=0x" + Long.toHexString(args.mPermittedCapabilities)
609 + ", effective=0x" + Long.toHexString(args.mEffectiveCapabilities));
610 }
611 }
612
613 /**
614 * @return Raw file descriptors for the read-end of blastula reporting pipes.
615 */
616 protected static int[] getBlastulaPipeFDs() {
617 return nativeGetBlastulaPipeFDs();
618 }
619
Chris Wailes8b35ba22019-01-10 16:55:32 -0800620 private static native int[] nativeGetBlastulaPipeFDs();
621
Chris Wailesc37ebe12019-01-11 17:04:41 -0800622 /**
623 * Remove the blastula table entry for the provided process ID.
624 *
625 * @param blastulaPID Process ID of the entry to remove
626 * @return True if the entry was removed; false if it doesn't exist
627 */
628 protected static boolean removeBlastulaTableEntry(int blastulaPID) {
629 return nativeRemoveBlastulaTableEntry(blastulaPID);
630 }
631
Chris Wailes8b35ba22019-01-10 16:55:32 -0800632 private static native boolean nativeRemoveBlastulaTableEntry(int blastulaPID);
633
Chris Wailes682b4792019-01-11 16:14:43 -0800634 /**
635 * uid 1000 (Process.SYSTEM_UID) may specify any uid &gt; 1000 in normal
636 * operation. It may also specify any gid and setgroups() list it chooses.
637 * In factory test mode, it may specify any UID.
638 *
639 * @param args non-null; zygote spawner arguments
640 * @param peer non-null; peer credentials
641 * @throws ZygoteSecurityException
642 */
643 protected static void applyUidSecurityPolicy(ZygoteArguments args, Credentials peer)
644 throws ZygoteSecurityException {
645
646 if (peer.getUid() == Process.SYSTEM_UID) {
647 /* In normal operation, SYSTEM_UID can only specify a restricted
648 * set of UIDs. In factory test mode, SYSTEM_UID may specify any uid.
649 */
650 boolean uidRestricted = FactoryTest.getMode() == FactoryTest.FACTORY_TEST_OFF;
651
652 if (uidRestricted && args.mUidSpecified && (args.mUid < Process.SYSTEM_UID)) {
653 throw new ZygoteSecurityException(
654 "System UID may not launch process with UID < "
655 + Process.SYSTEM_UID);
656 }
657 }
658
659 // If not otherwise specified, uid and gid are inherited from peer
660 if (!args.mUidSpecified) {
661 args.mUid = peer.getUid();
662 args.mUidSpecified = true;
663 }
664 if (!args.mGidSpecified) {
665 args.mGid = peer.getGid();
666 args.mGidSpecified = true;
667 }
668 }
669
670 /**
671 * Applies debugger system properties to the zygote arguments.
672 *
673 * If "ro.debuggable" is "1", all apps are debuggable. Otherwise,
674 * the debugger state is specified via the "--enable-jdwp" flag
675 * in the spawn request.
676 *
677 * @param args non-null; zygote spawner args
678 */
679 protected static void applyDebuggerSystemProperty(ZygoteArguments args) {
680 if (RoSystemProperties.DEBUGGABLE) {
681 args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
682 }
683 }
684
685 /**
686 * Applies zygote security policy.
687 * Based on the credentials of the process issuing a zygote command:
688 * <ol>
689 * <li> uid 0 (root) may specify --invoke-with to launch Zygote with a
690 * wrapper command.
691 * <li> Any other uid may not specify any invoke-with argument.
692 * </ul>
693 *
694 * @param args non-null; zygote spawner arguments
695 * @param peer non-null; peer credentials
696 * @throws ZygoteSecurityException
697 */
698 protected static void applyInvokeWithSecurityPolicy(ZygoteArguments args, Credentials peer)
699 throws ZygoteSecurityException {
700 int peerUid = peer.getUid();
701
702 if (args.mInvokeWith != null && peerUid != 0
703 && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
704 throw new ZygoteSecurityException("Peer is permitted to specify an"
705 + "explicit invoke-with wrapper command only for debuggable"
706 + "applications.");
707 }
708 }
709
710 /**
711 * Applies invoke-with system properties to the zygote arguments.
712 *
713 * @param args non-null; zygote args
714 */
715 protected static void applyInvokeWithSystemProperty(ZygoteArguments args) {
716 if (args.mInvokeWith == null && args.mNiceName != null) {
717 String property = "wrap." + args.mNiceName;
718 args.mInvokeWith = SystemProperties.get(property);
719 if (args.mInvokeWith != null && args.mInvokeWith.length() == 0) {
720 args.mInvokeWith = null;
721 }
722 }
723 }
724
725 /**
726 * Reads an argument list from the provided socket
727 * @return Argument list or null if EOF is reached
728 * @throws IOException passed straight through
729 */
730 static String[] readArgumentList(BufferedReader socketReader) throws IOException {
731
732 /**
733 * See android.os.Process.zygoteSendArgsAndGetPid()
734 * Presently the wire format to the zygote process is:
735 * a) a count of arguments (argc, in essence)
736 * b) a number of newline-separated argument strings equal to count
737 *
738 * After the zygote process reads these it will write the pid of
739 * the child or -1 on failure.
740 */
741
742 int argc;
743
744 try {
745 String argc_string = socketReader.readLine();
746
747 if (argc_string == null) {
748 // EOF reached.
749 return null;
750 }
751 argc = Integer.parseInt(argc_string);
752
753 } catch (NumberFormatException ex) {
754 Log.e("Zygote", "Invalid Zygote wire format: non-int at argc");
755 throw new IOException("Invalid wire format");
756 }
757
758 // See bug 1092107: large argc can be used for a DOS attack
759 if (argc > MAX_ZYGOTE_ARGC) {
760 throw new IOException("Max arg count exceeded");
761 }
762
763 String[] args = new String[argc];
764 for (int arg_index = 0; arg_index < argc; arg_index++) {
765 args[arg_index] = socketReader.readLine();
766 if (args[arg_index] == null) {
767 // We got an unexpected EOF.
768 throw new IOException("Truncated request");
769 }
770 }
771
772 return args;
773 }
774
Chris Wailesc37ebe12019-01-11 17:04:41 -0800775 /**
776 * Creates a managed object representing the Blastula pool socket that has
777 * already been initialized and bound by init.
778 *
779 * TODO (chriswailes): Move the name selection logic into this function.
780 *
781 * @throws RuntimeException when open fails
782 */
783 static void createBlastulaSocket(String socketName) {
784 if (BLASTULA_POOL_ENABLED && sBlastulaPoolSocket == null) {
785 sBlastulaPoolSocket = createManagedSocketFromInitSocket(socketName);
786 }
787 }
788
789 /**
790 * Creates a managed LocalServerSocket object using a file descriptor
791 * created by an init.rc script. The init scripts that specify the
792 * sockets name can be found in system/core/rootdir. The socket is bound
793 * to the file system in the /dev/sockets/ directory, and the file
794 * descriptor is shared via the ANDROID_SOCKET_<socketName> environment
795 * variable.
796 */
797 static LocalServerSocket createManagedSocketFromInitSocket(String socketName) {
798 int fileDesc;
799 final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
800
801 try {
802 String env = System.getenv(fullSocketName);
803 fileDesc = Integer.parseInt(env);
804 } catch (RuntimeException ex) {
805 throw new RuntimeException("Socket unset or invalid: " + fullSocketName, ex);
806 }
807
808 try {
809 FileDescriptor fd = new FileDescriptor();
810 fd.setInt$(fileDesc);
811 return new LocalServerSocket(fd);
812 } catch (IOException ex) {
813 throw new RuntimeException(
814 "Error building socket from file descriptor: " + fileDesc, ex);
815 }
816 }
doheon1.lee885b7422016-01-20 13:07:27 +0900817
Orion Hodson46724e72018-10-19 13:05:33 +0100818 private static void callPostForkSystemServerHooks() {
819 // SystemServer specific post fork hooks run before child post fork hooks.
820 VM_HOOKS.postForkSystemServer();
821 }
822
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100823 private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500824 boolean isZygote, String instructionSet) {
825 VM_HOOKS.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100826 }
827
Narayan Kamathb49996d2017-02-06 20:24:08 +0000828 /**
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800829 * Resets the calling thread priority to the default value (Thread.NORM_PRIORITY
830 * or nice value 0). This updates both the priority value in java.lang.Thread and
831 * the nice value (setpriority).
Narayan Kamathb49996d2017-02-06 20:24:08 +0000832 */
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800833 static void resetNicePriority() {
834 Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
835 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100836
837 /**
838 * Executes "/system/bin/sh -c &lt;command&gt;" using the exec() system call.
839 * This method throws a runtime exception if exec() failed, otherwise, this
840 * method never returns.
841 *
842 * @param command The shell command to execute.
843 */
844 public static void execShell(String command) {
845 String[] args = { "/system/bin/sh", "-c", command };
846 try {
Elliott Hughes860c5912014-04-28 19:19:13 -0700847 Os.execv(args[0], args);
Narayan Kamath973b4662014-03-31 13:41:26 +0100848 } catch (ErrnoException e) {
849 throw new RuntimeException(e);
850 }
851 }
852
853 /**
854 * Appends quotes shell arguments to the specified string builder.
855 * The arguments are quoted using single-quotes, escaped if necessary,
856 * prefixed with a space, and appended to the command.
857 *
858 * @param command A string builder for the shell command being constructed.
859 * @param args An array of argument strings to be quoted and appended to the command.
860 * @see #execShell(String)
861 */
862 public static void appendQuotedShellArgs(StringBuilder command, String[] args) {
863 for (String arg : args) {
864 command.append(" '").append(arg.replace("'", "'\\''")).append("'");
865 }
866 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100867}