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