blob: 1048cb4e6e3a5454f256d10a5f83be7a78ea5bb4 [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
Robert Sesekd0a190df2018-02-12 18:46:01 -0500123 /**
124 * An extraArg passed when a zygote process is forking a child-zygote, specifying a name
125 * in the abstract socket namespace. This socket name is what the new child zygote
126 * should listen for connections on.
127 */
128 public static final String CHILD_ZYGOTE_SOCKET_NAME_ARG = "--zygote-socket=";
129
Chris Wailesc37ebe12019-01-11 17:04:41 -0800130 /** Prefix prepended to socket names created by init */
131 private static final String ANDROID_SOCKET_PREFIX = "ANDROID_SOCKET_";
132
133 /**
134 * The maximum value that the sBlastulaPoolMax variable may take. This value
135 * is a mirror of BLASTULA_POOL_MAX_LIMIT found in com_android_internal_os_Zygote.cpp.
136 */
137 static final int BLASTULA_POOL_MAX_LIMIT = 10;
138
139 /**
140 * The minimum value that the sBlastulaPoolMin variable may take.
141 */
142 static final int BLASTULA_POOL_MIN_LIMIT = 1;
143
144 /**
145 * The runtime-adjustable maximum Blastula pool size.
146 */
147 static int sBlastulaPoolMax = BLASTULA_POOL_MAX_LIMIT;
148
149 /**
150 * The runtime-adjustable minimum Blastula pool size.
151 */
152 static int sBlastulaPoolMin = BLASTULA_POOL_MIN_LIMIT;
153
154 /**
155 * The runtime-adjustable value used to determine when to re-fill the
156 * blastula pool. The pool will be re-filled when
157 * (sBlastulaPoolMax - gBlastulaPoolCount) >= sBlastulaPoolRefillThreshold.
158 */
159 // TODO (chriswailes): This must be updated at the same time as sBlastulaPoolMax.
160 static int sBlastulaPoolRefillThreshold = (sBlastulaPoolMax / 2);
161
Chris Wailescffbf1c2019-01-11 17:13:00 -0800162 /**
163 * @hide for internal use only
164 */
165 public static final int SOCKET_BUFFER_SIZE = 256;
166
Chris Wailesc37ebe12019-01-11 17:04:41 -0800167 private static LocalServerSocket sBlastulaPoolSocket = null;
168
Chris Wailes682b4792019-01-11 16:14:43 -0800169 /** a prototype instance for a future List.toArray() */
170 protected static final int[][] INT_ARRAY_2D = new int[0][0];
171
Narayan Kamath973b4662014-03-31 13:41:26 +0100172 private Zygote() {}
173
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800174 /** Called for some security initialization before any fork. */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800175 static native void nativeSecurityInit();
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800176
Narayan Kamath973b4662014-03-31 13:41:26 +0100177 /**
178 * Forks a new VM instance. The current VM must have been started
179 * with the -Xzygote flag. <b>NOTE: new instance keeps all
180 * root capabilities. The new process is expected to call capset()</b>.
181 *
182 * @param uid the UNIX uid that the new process should setuid() to after
183 * fork()ing and and before spawning any threads.
184 * @param gid the UNIX gid that the new process should setgid() to after
185 * fork()ing and and before spawning any threads.
186 * @param gids null-ok; a list of UNIX gids that the new process should
187 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100188 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100189 * @param rlimits null-ok an array of rlimit tuples, with the second
190 * dimension having a length of 3 and representing
191 * (resource, rlim_cur, rlim_max). These are set via the posix
192 * setrlimit(2) call.
193 * @param seInfo null-ok a string specifying SELinux information for
194 * the new process.
195 * @param niceName null-ok a string specifying the process name.
196 * @param fdsToClose an array of ints, holding one or more POSIX
197 * file descriptor numbers that are to be closed by the child
198 * (and replaced by /dev/null) after forking. An integer value
199 * of -1 in any entry in the array means "ignore this one".
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800200 * @param fdsToIgnore null-ok an array of ints, either null or holding
201 * one or more POSIX file descriptor numbers that are to be ignored
202 * in the file descriptor table check.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500203 * @param startChildZygote if true, the new child process will itself be a
204 * new zygote process.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700205 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400206 * @param appDataDir null-ok the data directory of the app.
Narayan Kamath973b4662014-03-31 13:41:26 +0100207 *
208 * @return 0 if this is the child, pid of the child
209 * if this is the parent, or -1 on error.
210 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100211 public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
Chris Wailes8b35ba22019-01-10 16:55:32 -0800212 int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
213 int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir) {
Neil Fuller927c15c2019-01-28 18:29:20 +0000214 ZygoteHooks.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800215 // Resets nice priority for zygote process.
216 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100217 int pid = nativeForkAndSpecialize(
Chris Wailes8b35ba22019-01-10 16:55:32 -0800218 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
219 fdsToIgnore, startChildZygote, instructionSet, appDataDir);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100220 // Enable tracing as soon as possible for the child process.
221 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700222 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100223
224 // Note that this event ends at the end of handleChildProc,
225 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
226 }
Neil Fuller927c15c2019-01-28 18:29:20 +0000227 ZygoteHooks.postForkCommon();
Narayan Kamath973b4662014-03-31 13:41:26 +0100228 return pid;
229 }
230
Chris Wailes8b35ba22019-01-10 16:55:32 -0800231 private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
232 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
233 int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
234 String appDataDir);
235
Chris Wailesc37ebe12019-01-11 17:04:41 -0800236 /**
237 * Specialize a Blastula instance. The current VM must have been started
238 * with the -Xzygote flag.
239 *
240 * @param uid The UNIX uid that the new process should setuid() to before spawning any threads
241 * @param gid The UNIX gid that the new process should setgid() to before spawning any threads
242 * @param gids null-ok; A list of UNIX gids that the new process should
243 * setgroups() to before spawning any threads
244 * @param runtimeFlags Bit flags that enable ART features
245 * @param rlimits null-ok An array of rlimit tuples, with the second
246 * dimension having a length of 3 and representing
247 * (resource, rlim_cur, rlim_max). These are set via the posix
248 * setrlimit(2) call.
249 * @param seInfo null-ok A string specifying SELinux information for
250 * the new process.
251 * @param niceName null-ok A string specifying the process name.
252 * @param startChildZygote If true, the new child process will itself be a
253 * new zygote process.
254 * @param instructionSet null-ok The instruction set to use.
255 * @param appDataDir null-ok The data directory of the app.
256 */
257 public static void specializeBlastula(int uid, int gid, int[] gids, int runtimeFlags,
258 int[][] rlimits, int mountExternal, String seInfo, String niceName,
259 boolean startChildZygote, String instructionSet, String appDataDir) {
260
261 nativeSpecializeBlastula(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
262 niceName, startChildZygote, instructionSet, appDataDir);
263
264 // Enable tracing as soon as possible for the child process.
265 Trace.setTracingEnabled(true, runtimeFlags);
266
267 // Note that this event ends at the end of handleChildProc.
268 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
269
270 /*
271 * This is called here (instead of after the fork but before the specialize) to maintain
272 * consistancy with the code paths for forkAndSpecialize.
273 *
274 * TODO (chriswailes): Look into moving this to immediately after the fork.
275 */
Neil Fuller927c15c2019-01-28 18:29:20 +0000276 ZygoteHooks.postForkCommon();
Chris Wailesc37ebe12019-01-11 17:04:41 -0800277 }
278
Chris Wailes8b35ba22019-01-10 16:55:32 -0800279 private static native void nativeSpecializeBlastula(int uid, int gid, int[] gids,
280 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
281 boolean startChildZygote, String instructionSet, String appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100282
283 /**
Christopher Ferris2980de42017-06-20 16:13:40 -0700284 * Called to do any initialization before starting an application.
285 */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800286 static native void nativePreApplicationInit();
Christopher Ferris2980de42017-06-20 16:13:40 -0700287
288 /**
Narayan Kamath973b4662014-03-31 13:41:26 +0100289 * Special method to start the system server process. In addition to the
290 * common actions performed in forkAndSpecialize, the pid of the child
291 * process is recorded such that the death of the child process will cause
292 * zygote to exit.
293 *
294 * @param uid the UNIX uid that the new process should setuid() to after
295 * fork()ing and and before spawning any threads.
296 * @param gid the UNIX gid that the new process should setgid() to after
297 * fork()ing and and before spawning any threads.
298 * @param gids null-ok; a list of UNIX gids that the new process should
299 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100300 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100301 * @param rlimits null-ok an array of rlimit tuples, with the second
302 * dimension having a length of 3 and representing
303 * (resource, rlim_cur, rlim_max). These are set via the posix
304 * setrlimit(2) call.
305 * @param permittedCapabilities argument for setcap()
306 * @param effectiveCapabilities argument for setcap()
307 *
308 * @return 0 if this is the child, pid of the child
309 * if this is the parent, or -1 on error.
310 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100311 public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100312 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
Neil Fuller927c15c2019-01-28 18:29:20 +0000313 ZygoteHooks.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800314 // Resets nice priority for zygote process.
315 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100316 int pid = nativeForkSystemServer(
Chris Wailes8b35ba22019-01-10 16:55:32 -0800317 uid, gid, gids, runtimeFlags, rlimits,
318 permittedCapabilities, effectiveCapabilities);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100319 // Enable tracing as soon as we enter the system_server.
320 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700321 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100322 }
Neil Fuller927c15c2019-01-28 18:29:20 +0000323 ZygoteHooks.postForkCommon();
Narayan Kamath973b4662014-03-31 13:41:26 +0100324 return pid;
325 }
326
Chris Wailes8b35ba22019-01-10 16:55:32 -0800327 private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100328 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
329
doheon1.lee885b7422016-01-20 13:07:27 +0900330 /**
Robert Sesek54e387d2016-12-02 17:27:50 -0500331 * Lets children of the zygote inherit open file descriptors to this path.
332 */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800333 protected static native void nativeAllowFileAcrossFork(String path);
Robert Sesek54e387d2016-12-02 17:27:50 -0500334
335 /**
doheon1.lee885b7422016-01-20 13:07:27 +0900336 * Zygote unmount storage space on initializing.
337 * This method is called once.
338 */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800339 protected static native void nativeUnmountStorageOnInit();
340
Chris Wailesc37ebe12019-01-11 17:04:41 -0800341 /**
342 * Get socket file descriptors (opened by init) from the environment and
343 * store them for access from native code later.
344 *
345 * @param isPrimary True if this is the zygote process, false if it is zygote_secondary
346 */
347 public static void getSocketFDs(boolean isPrimary) {
348 nativeGetSocketFDs(isPrimary);
349 }
350
Chris Wailes8b35ba22019-01-10 16:55:32 -0800351 protected static native void nativeGetSocketFDs(boolean isPrimary);
352
Chris Wailesc37ebe12019-01-11 17:04:41 -0800353 /**
354 * Initialize the blastula pool and fill it with the desired number of
355 * processes.
356 */
357 protected static Runnable initBlastulaPool() {
358 if (BLASTULA_POOL_ENABLED) {
359 sBlastulaPoolEventFD = getBlastulaPoolEventFD();
360
361 return fillBlastulaPool(null);
362 } else {
363 return null;
364 }
365 }
366
367 /**
368 * Checks to see if the current policy says that pool should be refilled, and spawns new
369 * blastulas if necessary.
370 *
371 * NOTE: This function doesn't need to be guarded with BLASTULA_POOL_ENABLED because it is
372 * only called from contexts that are only valid if the pool is enabled.
373 *
374 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
375 * @return In the Zygote process this function will always return null; in blastula processes
376 * this function will return a Runnable object representing the new application that is
377 * passed up from blastulaMain.
378 */
379 protected static Runnable fillBlastulaPool(int[] sessionSocketRawFDs) {
380 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Zygote:FillBlastulaPool");
381
382 int blastulaPoolCount = getBlastulaPoolCount();
383
384 int numBlastulasToSpawn = sBlastulaPoolMax - blastulaPoolCount;
385
386 if (blastulaPoolCount < sBlastulaPoolMin
387 || numBlastulasToSpawn >= sBlastulaPoolRefillThreshold) {
388
389 // Disable some VM functionality and reset some system values
390 // before forking.
Neil Fuller927c15c2019-01-28 18:29:20 +0000391 ZygoteHooks.preFork();
Chris Wailesc37ebe12019-01-11 17:04:41 -0800392 resetNicePriority();
393
394 while (blastulaPoolCount++ < sBlastulaPoolMax) {
395 Runnable caller = forkBlastula(sessionSocketRawFDs);
396
397 if (caller != null) {
398 return caller;
399 }
400 }
401
402 // Re-enable runtime services for the Zygote. Blastula services
403 // are re-enabled in specializeBlastula.
Neil Fuller927c15c2019-01-28 18:29:20 +0000404 ZygoteHooks.postForkCommon();
Chris Wailesc37ebe12019-01-11 17:04:41 -0800405
406 Log.i("zygote", "Filled the blastula pool. New blastulas: " + numBlastulasToSpawn);
407 }
408
409 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
410
411 return null;
412 }
413
414 /**
415 * @return Number of blastulas currently in the pool
416 */
417 private static int getBlastulaPoolCount() {
418 return nativeGetBlastulaPoolCount();
419 }
420
Chris Wailes8b35ba22019-01-10 16:55:32 -0800421 private static native int nativeGetBlastulaPoolCount();
422
Chris Wailesc37ebe12019-01-11 17:04:41 -0800423 /**
424 * @return The event FD used for communication between the signal handler and the ZygoteServer
425 * poll loop
426 */
427 private static FileDescriptor getBlastulaPoolEventFD() {
428 FileDescriptor fd = new FileDescriptor();
429 fd.setInt$(nativeGetBlastulaPoolEventFD());
430
431 return fd;
432 }
433
Chris Wailes8b35ba22019-01-10 16:55:32 -0800434 private static native int nativeGetBlastulaPoolEventFD();
435
Chris Wailesc37ebe12019-01-11 17:04:41 -0800436 /**
437 * Fork a new blastula process from the zygote
438 *
439 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
440 * @return In the Zygote process this function will always return null; in blastula processes
441 * this function will return a Runnable object representing the new application that is
442 * passed up from blastulaMain.
443 */
444 private static Runnable forkBlastula(int[] sessionSocketRawFDs) {
445 FileDescriptor[] pipeFDs = null;
446
447 try {
448 pipeFDs = Os.pipe2(O_CLOEXEC);
449 } catch (ErrnoException errnoEx) {
450 throw new IllegalStateException("Unable to create blastula pipe.", errnoEx);
451 }
452
453 int pid =
454 nativeForkBlastula(pipeFDs[0].getInt$(), pipeFDs[1].getInt$(), sessionSocketRawFDs);
455
456 if (pid == 0) {
457 IoUtils.closeQuietly(pipeFDs[0]);
458 return blastulaMain(pipeFDs[1]);
459 } else {
460 // The read-end of the pipe will be closed by the native code.
461 // See removeBlastulaTableEntry();
462 IoUtils.closeQuietly(pipeFDs[1]);
463 return null;
464 }
465 }
466
Chris Wailes8b35ba22019-01-10 16:55:32 -0800467 private static native int nativeForkBlastula(int readPipeFD,
468 int writePipeFD,
469 int[] sessionSocketRawFDs);
470
Chris Wailesc37ebe12019-01-11 17:04:41 -0800471 /**
472 * This function is used by blastulas to wait for specialization requests from the system
473 * server.
474 *
475 * @param writePipe The write end of the reporting pipe used to communicate with the poll loop
476 * of the ZygoteServer.
477 * @return A runnable oject representing the new application.
478 */
479 static Runnable blastulaMain(FileDescriptor writePipe) {
480 final int pid = Process.myPid();
481
482 LocalSocket sessionSocket = null;
483 DataOutputStream blastulaOutputStream = null;
484 Credentials peerCredentials = null;
485 String[] argStrings = null;
486
487 while (true) {
488 try {
489 sessionSocket = sBlastulaPoolSocket.accept();
490
491 BufferedReader blastulaReader =
492 new BufferedReader(new InputStreamReader(sessionSocket.getInputStream()));
493 blastulaOutputStream =
494 new DataOutputStream(sessionSocket.getOutputStream());
495
496 peerCredentials = sessionSocket.getPeerCredentials();
497
498 argStrings = readArgumentList(blastulaReader);
499
500 if (argStrings != null) {
501 break;
502 } else {
503 Log.e("Blastula", "Truncated command received.");
504 IoUtils.closeQuietly(sessionSocket);
505 }
506 } catch (IOException ioEx) {
507 Log.e("Blastula", "Failed to read command: " + ioEx.getMessage());
508 IoUtils.closeQuietly(sessionSocket);
509 }
510 }
511
512 ZygoteArguments args = new ZygoteArguments(argStrings);
513
514 // TODO (chriswailes): Should this only be run for debug builds?
515 validateBlastulaCommand(args);
516
517 applyUidSecurityPolicy(args, peerCredentials);
518 applyDebuggerSystemProperty(args);
519
520 int[][] rlimits = null;
521
522 if (args.mRLimits != null) {
523 rlimits = args.mRLimits.toArray(INT_ARRAY_2D);
524 }
525
526 // This must happen before the SELinux policy for this process is
527 // changed when specializing.
528 try {
529 // Used by ZygoteProcess.zygoteSendArgsAndGetResult to fill in a
530 // Process.ProcessStartResult object.
531 blastulaOutputStream.writeInt(pid);
532 } catch (IOException ioEx) {
533 Log.e("Blastula", "Failed to write response to session socket: " + ioEx.getMessage());
534 System.exit(-1);
535 } finally {
536 IoUtils.closeQuietly(sessionSocket);
537 IoUtils.closeQuietly(sBlastulaPoolSocket);
538 }
539
540 try {
541 ByteArrayOutputStream buffer =
542 new ByteArrayOutputStream(Zygote.BLASTULA_MANAGEMENT_MESSAGE_BYTES);
543 DataOutputStream outputStream = new DataOutputStream(buffer);
544
545 // This is written as a long so that the blastula reporting pipe and blastula pool
546 // event FD handlers in ZygoteServer.runSelectLoop can be unified. These two cases
547 // should both send/receive 8 bytes.
548 outputStream.writeLong(pid);
549 outputStream.flush();
550
551 Os.write(writePipe, buffer.toByteArray(), 0, buffer.size());
552 } catch (Exception ex) {
553 Log.e("Blastula",
554 String.format("Failed to write PID (%d) to pipe (%d): %s",
555 pid, writePipe.getInt$(), ex.getMessage()));
556 System.exit(-1);
557 } finally {
558 IoUtils.closeQuietly(writePipe);
559 }
560
561 specializeBlastula(args.mUid, args.mGid, args.mGids,
562 args.mRuntimeFlags, rlimits, args.mMountExternal,
563 args.mSeInfo, args.mNiceName, args.mStartChildZygote,
564 args.mInstructionSet, args.mAppDataDir);
565
566 if (args.mNiceName != null) {
567 Process.setArgV0(args.mNiceName);
568 }
569
570 // End of the postFork event.
571 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
572
573 return ZygoteInit.zygoteInit(args.mTargetSdkVersion,
574 args.mRemainingArgs,
575 null /* classLoader */);
576 }
577
578 private static final String BLASTULA_ERROR_PREFIX = "Invalid command to blastula: ";
579
580 /**
581 * Checks a set of zygote arguments to see if they can be handled by a blastula. Throws an
582 * exception if an invalid arugment is encountered.
583 * @param args The arguments to test
584 */
585 static void validateBlastulaCommand(ZygoteArguments args) {
586 if (args.mAbiListQuery) {
587 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--query-abi-list");
588 } else if (args.mPidQuery) {
589 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--get-pid");
590 } else if (args.mPreloadDefault) {
591 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-default");
592 } else if (args.mPreloadPackage != null) {
593 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-package");
594 } else if (args.mStartChildZygote) {
595 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--start-child-zygote");
596 } else if (args.mApiBlacklistExemptions != null) {
597 throw new IllegalArgumentException(
598 BLASTULA_ERROR_PREFIX + "--set-api-blacklist-exemptions");
599 } else if (args.mHiddenApiAccessLogSampleRate != -1) {
600 throw new IllegalArgumentException(
601 BLASTULA_ERROR_PREFIX + "--hidden-api-log-sampling-rate=");
602 } else if (args.mInvokeWith != null) {
603 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--invoke-with");
604 } else if (args.mPermittedCapabilities != 0 || args.mEffectiveCapabilities != 0) {
605 throw new ZygoteSecurityException("Client may not specify capabilities: "
606 + "permitted=0x" + Long.toHexString(args.mPermittedCapabilities)
607 + ", effective=0x" + Long.toHexString(args.mEffectiveCapabilities));
608 }
609 }
610
611 /**
612 * @return Raw file descriptors for the read-end of blastula reporting pipes.
613 */
614 protected static int[] getBlastulaPipeFDs() {
615 return nativeGetBlastulaPipeFDs();
616 }
617
Chris Wailes8b35ba22019-01-10 16:55:32 -0800618 private static native int[] nativeGetBlastulaPipeFDs();
619
Chris Wailesc37ebe12019-01-11 17:04:41 -0800620 /**
621 * Remove the blastula table entry for the provided process ID.
622 *
623 * @param blastulaPID Process ID of the entry to remove
624 * @return True if the entry was removed; false if it doesn't exist
625 */
626 protected static boolean removeBlastulaTableEntry(int blastulaPID) {
627 return nativeRemoveBlastulaTableEntry(blastulaPID);
628 }
629
Chris Wailes8b35ba22019-01-10 16:55:32 -0800630 private static native boolean nativeRemoveBlastulaTableEntry(int blastulaPID);
631
Chris Wailes682b4792019-01-11 16:14:43 -0800632 /**
633 * uid 1000 (Process.SYSTEM_UID) may specify any uid &gt; 1000 in normal
634 * operation. It may also specify any gid and setgroups() list it chooses.
635 * In factory test mode, it may specify any UID.
636 *
637 * @param args non-null; zygote spawner arguments
638 * @param peer non-null; peer credentials
639 * @throws ZygoteSecurityException
640 */
641 protected static void applyUidSecurityPolicy(ZygoteArguments args, Credentials peer)
642 throws ZygoteSecurityException {
643
644 if (peer.getUid() == Process.SYSTEM_UID) {
645 /* In normal operation, SYSTEM_UID can only specify a restricted
646 * set of UIDs. In factory test mode, SYSTEM_UID may specify any uid.
647 */
648 boolean uidRestricted = FactoryTest.getMode() == FactoryTest.FACTORY_TEST_OFF;
649
650 if (uidRestricted && args.mUidSpecified && (args.mUid < Process.SYSTEM_UID)) {
651 throw new ZygoteSecurityException(
652 "System UID may not launch process with UID < "
653 + Process.SYSTEM_UID);
654 }
655 }
656
657 // If not otherwise specified, uid and gid are inherited from peer
658 if (!args.mUidSpecified) {
659 args.mUid = peer.getUid();
660 args.mUidSpecified = true;
661 }
662 if (!args.mGidSpecified) {
663 args.mGid = peer.getGid();
664 args.mGidSpecified = true;
665 }
666 }
667
668 /**
669 * Applies debugger system properties to the zygote arguments.
670 *
671 * If "ro.debuggable" is "1", all apps are debuggable. Otherwise,
672 * the debugger state is specified via the "--enable-jdwp" flag
673 * in the spawn request.
674 *
675 * @param args non-null; zygote spawner args
676 */
677 protected static void applyDebuggerSystemProperty(ZygoteArguments args) {
678 if (RoSystemProperties.DEBUGGABLE) {
679 args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
680 }
681 }
682
683 /**
684 * Applies zygote security policy.
685 * Based on the credentials of the process issuing a zygote command:
686 * <ol>
687 * <li> uid 0 (root) may specify --invoke-with to launch Zygote with a
688 * wrapper command.
689 * <li> Any other uid may not specify any invoke-with argument.
690 * </ul>
691 *
692 * @param args non-null; zygote spawner arguments
693 * @param peer non-null; peer credentials
694 * @throws ZygoteSecurityException
695 */
696 protected static void applyInvokeWithSecurityPolicy(ZygoteArguments args, Credentials peer)
697 throws ZygoteSecurityException {
698 int peerUid = peer.getUid();
699
700 if (args.mInvokeWith != null && peerUid != 0
701 && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
702 throw new ZygoteSecurityException("Peer is permitted to specify an"
703 + "explicit invoke-with wrapper command only for debuggable"
704 + "applications.");
705 }
706 }
707
708 /**
709 * Applies invoke-with system properties to the zygote arguments.
710 *
711 * @param args non-null; zygote args
712 */
713 protected static void applyInvokeWithSystemProperty(ZygoteArguments args) {
714 if (args.mInvokeWith == null && args.mNiceName != null) {
715 String property = "wrap." + args.mNiceName;
716 args.mInvokeWith = SystemProperties.get(property);
717 if (args.mInvokeWith != null && args.mInvokeWith.length() == 0) {
718 args.mInvokeWith = null;
719 }
720 }
721 }
722
723 /**
724 * Reads an argument list from the provided socket
725 * @return Argument list or null if EOF is reached
726 * @throws IOException passed straight through
727 */
728 static String[] readArgumentList(BufferedReader socketReader) throws IOException {
729
730 /**
731 * See android.os.Process.zygoteSendArgsAndGetPid()
732 * Presently the wire format to the zygote process is:
733 * a) a count of arguments (argc, in essence)
734 * b) a number of newline-separated argument strings equal to count
735 *
736 * After the zygote process reads these it will write the pid of
737 * the child or -1 on failure.
738 */
739
740 int argc;
741
742 try {
743 String argc_string = socketReader.readLine();
744
745 if (argc_string == null) {
746 // EOF reached.
747 return null;
748 }
749 argc = Integer.parseInt(argc_string);
750
751 } catch (NumberFormatException ex) {
752 Log.e("Zygote", "Invalid Zygote wire format: non-int at argc");
753 throw new IOException("Invalid wire format");
754 }
755
756 // See bug 1092107: large argc can be used for a DOS attack
757 if (argc > MAX_ZYGOTE_ARGC) {
758 throw new IOException("Max arg count exceeded");
759 }
760
761 String[] args = new String[argc];
762 for (int arg_index = 0; arg_index < argc; arg_index++) {
763 args[arg_index] = socketReader.readLine();
764 if (args[arg_index] == null) {
765 // We got an unexpected EOF.
766 throw new IOException("Truncated request");
767 }
768 }
769
770 return args;
771 }
772
Chris Wailesc37ebe12019-01-11 17:04:41 -0800773 /**
774 * Creates a managed object representing the Blastula pool socket that has
775 * already been initialized and bound by init.
776 *
777 * TODO (chriswailes): Move the name selection logic into this function.
778 *
779 * @throws RuntimeException when open fails
780 */
781 static void createBlastulaSocket(String socketName) {
782 if (BLASTULA_POOL_ENABLED && sBlastulaPoolSocket == null) {
783 sBlastulaPoolSocket = createManagedSocketFromInitSocket(socketName);
784 }
785 }
786
787 /**
788 * Creates a managed LocalServerSocket object using a file descriptor
789 * created by an init.rc script. The init scripts that specify the
790 * sockets name can be found in system/core/rootdir. The socket is bound
791 * to the file system in the /dev/sockets/ directory, and the file
792 * descriptor is shared via the ANDROID_SOCKET_<socketName> environment
793 * variable.
794 */
795 static LocalServerSocket createManagedSocketFromInitSocket(String socketName) {
796 int fileDesc;
797 final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
798
799 try {
800 String env = System.getenv(fullSocketName);
801 fileDesc = Integer.parseInt(env);
802 } catch (RuntimeException ex) {
803 throw new RuntimeException("Socket unset or invalid: " + fullSocketName, ex);
804 }
805
806 try {
807 FileDescriptor fd = new FileDescriptor();
808 fd.setInt$(fileDesc);
809 return new LocalServerSocket(fd);
810 } catch (IOException ex) {
811 throw new RuntimeException(
812 "Error building socket from file descriptor: " + fileDesc, ex);
813 }
814 }
doheon1.lee885b7422016-01-20 13:07:27 +0900815
Orion Hodson46724e72018-10-19 13:05:33 +0100816 private static void callPostForkSystemServerHooks() {
817 // SystemServer specific post fork hooks run before child post fork hooks.
Neil Fuller927c15c2019-01-28 18:29:20 +0000818 ZygoteHooks.postForkSystemServer();
Orion Hodson46724e72018-10-19 13:05:33 +0100819 }
820
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100821 private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500822 boolean isZygote, String instructionSet) {
Neil Fuller927c15c2019-01-28 18:29:20 +0000823 ZygoteHooks.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100824 }
825
Narayan Kamathb49996d2017-02-06 20:24:08 +0000826 /**
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800827 * Resets the calling thread priority to the default value (Thread.NORM_PRIORITY
828 * or nice value 0). This updates both the priority value in java.lang.Thread and
829 * the nice value (setpriority).
Narayan Kamathb49996d2017-02-06 20:24:08 +0000830 */
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800831 static void resetNicePriority() {
832 Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
833 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100834
835 /**
836 * Executes "/system/bin/sh -c &lt;command&gt;" using the exec() system call.
837 * This method throws a runtime exception if exec() failed, otherwise, this
838 * method never returns.
839 *
840 * @param command The shell command to execute.
841 */
842 public static void execShell(String command) {
843 String[] args = { "/system/bin/sh", "-c", command };
844 try {
Elliott Hughes860c5912014-04-28 19:19:13 -0700845 Os.execv(args[0], args);
Narayan Kamath973b4662014-03-31 13:41:26 +0100846 } catch (ErrnoException e) {
847 throw new RuntimeException(e);
848 }
849 }
850
851 /**
852 * Appends quotes shell arguments to the specified string builder.
853 * The arguments are quoted using single-quotes, escaped if necessary,
854 * prefixed with a space, and appended to the command.
855 *
856 * @param command A string builder for the shell command being constructed.
857 * @param args An array of argument strings to be quoted and appended to the command.
858 * @see #execShell(String)
859 */
860 public static void appendQuotedShellArgs(StringBuilder command, String[] args) {
861 for (String arg : args) {
862 command.append(" '").append(arg.replace("'", "'\\''")).append("'");
863 }
864 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100865}