blob: f609f2fc22b679148ff21aebdfb9407dc7ca0f90 [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 Wailescb0b37f2019-01-11 17:04:41 -080019import static android.system.OsConstants.O_CLOEXEC;
20
Chris Wailes2be26262019-01-11 16:14:43 -080021import static com.android.internal.os.ZygoteConnectionConstants.MAX_ZYGOTE_ARGC;
22
23import android.net.Credentials;
Chris Wailescb0b37f2019-01-11 17:04:41 -080024import android.net.LocalServerSocket;
25import android.net.LocalSocket;
Chris Wailes2be26262019-01-11 16:14:43 -080026import android.os.FactoryTest;
Jeff Sharkeyace874b2017-09-07 15:27:33 -060027import android.os.IVold;
Chris Wailes2be26262019-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 Wailes2be26262019-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 Wailescb0b37f2019-01-11 17:04:41 -080037import libcore.io.IoUtils;
38
Chris Wailes2be26262019-01-11 16:14:43 -080039import java.io.BufferedReader;
Chris Wailescb0b37f2019-01-11 17:04:41 -080040import java.io.ByteArrayOutputStream;
41import java.io.DataOutputStream;
42import java.io.FileDescriptor;
Chris Wailes2be26262019-01-11 16:14:43 -080043import java.io.IOException;
Chris Wailescb0b37f2019-01-11 17:04:41 -080044import java.io.InputStreamReader;
Chris Wailes2be26262019-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;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800104 /**
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800105 * Mount mode for apps that are already installed on the device before the isolated_storage
106 * feature is enabled.
107 */
108 public static final int MOUNT_EXTERNAL_LEGACY = IVold.REMOUNT_MODE_LEGACY;
109 /**
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800110 * Mount mode for package installers which should give them access to
111 * all obb dirs in addition to their package sandboxes
112 */
113 public static final int MOUNT_EXTERNAL_INSTALLER = IVold.REMOUNT_MODE_INSTALLER;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700114 /** Read-write external storage should be mounted instead of package sandbox */
115 public static final int MOUNT_EXTERNAL_FULL = IVold.REMOUNT_MODE_FULL;
Narayan Kamath973b4662014-03-31 13:41:26 +0100116
Chris Wailescb0b37f2019-01-11 17:04:41 -0800117 /** Number of bytes sent to the Zygote over blastula pipes or the pool event FD */
118 public static final int BLASTULA_MANAGEMENT_MESSAGE_BYTES = 8;
119
120 /** If the blastula pool should be created and used to start applications */
121 public static final boolean BLASTULA_POOL_ENABLED = false;
122
123 /**
124 * File descriptor used for communication between the signal handler and the ZygoteServer poll
125 * loop.
126 * */
127 protected static FileDescriptor sBlastulaPoolEventFD;
128
Narayan Kamath973b4662014-03-31 13:41:26 +0100129 private static final ZygoteHooks VM_HOOKS = new ZygoteHooks();
130
Robert Sesekd0a190df2018-02-12 18:46:01 -0500131 /**
132 * An extraArg passed when a zygote process is forking a child-zygote, specifying a name
133 * in the abstract socket namespace. This socket name is what the new child zygote
134 * should listen for connections on.
135 */
136 public static final String CHILD_ZYGOTE_SOCKET_NAME_ARG = "--zygote-socket=";
137
Martijn Coenen7e6fa672018-11-05 11:45:26 +0100138 /**
139 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
140 * requested ABI for the child Zygote.
141 */
142 public static final String CHILD_ZYGOTE_ABI_LIST_ARG = "--abi-list=";
143
Martijn Coenen86f08a52019-01-03 16:23:01 +0100144 /**
145 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
146 * start of the UID range the children of the Zygote may setuid()/setgid() to. This
147 * will be enforced with a seccomp filter.
148 */
149 public static final String CHILD_ZYGOTE_UID_RANGE_START = "--uid-range-start=";
150
151 /**
152 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
153 * end of the UID range the children of the Zygote may setuid()/setgid() to. This
154 * will be enforced with a seccomp filter.
155 */
156 public static final String CHILD_ZYGOTE_UID_RANGE_END = "--uid-range-end=";
157
Chris Wailescb0b37f2019-01-11 17:04:41 -0800158 /** Prefix prepended to socket names created by init */
159 private static final String ANDROID_SOCKET_PREFIX = "ANDROID_SOCKET_";
160
161 /**
162 * The maximum value that the sBlastulaPoolMax variable may take. This value
163 * is a mirror of BLASTULA_POOL_MAX_LIMIT found in com_android_internal_os_Zygote.cpp.
164 */
165 static final int BLASTULA_POOL_MAX_LIMIT = 10;
166
167 /**
168 * The minimum value that the sBlastulaPoolMin variable may take.
169 */
170 static final int BLASTULA_POOL_MIN_LIMIT = 1;
171
172 /**
173 * The runtime-adjustable maximum Blastula pool size.
174 */
175 static int sBlastulaPoolMax = BLASTULA_POOL_MAX_LIMIT;
176
177 /**
178 * The runtime-adjustable minimum Blastula pool size.
179 */
180 static int sBlastulaPoolMin = BLASTULA_POOL_MIN_LIMIT;
181
182 /**
183 * The runtime-adjustable value used to determine when to re-fill the
184 * blastula pool. The pool will be re-filled when
185 * (sBlastulaPoolMax - gBlastulaPoolCount) >= sBlastulaPoolRefillThreshold.
186 */
187 // TODO (chriswailes): This must be updated at the same time as sBlastulaPoolMax.
188 static int sBlastulaPoolRefillThreshold = (sBlastulaPoolMax / 2);
189
190 private static LocalServerSocket sBlastulaPoolSocket = null;
191
Chris Wailes2be26262019-01-11 16:14:43 -0800192 /** a prototype instance for a future List.toArray() */
193 protected static final int[][] INT_ARRAY_2D = new int[0][0];
194
Narayan Kamath973b4662014-03-31 13:41:26 +0100195 private Zygote() {}
196
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800197 /** Called for some security initialization before any fork. */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800198 static native void nativeSecurityInit();
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800199
Narayan Kamath973b4662014-03-31 13:41:26 +0100200 /**
201 * Forks a new VM instance. The current VM must have been started
202 * with the -Xzygote flag. <b>NOTE: new instance keeps all
203 * root capabilities. The new process is expected to call capset()</b>.
204 *
205 * @param uid the UNIX uid that the new process should setuid() to after
206 * fork()ing and and before spawning any threads.
207 * @param gid the UNIX gid that the new process should setgid() to after
208 * fork()ing and and before spawning any threads.
209 * @param gids null-ok; a list of UNIX gids that the new process should
210 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100211 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100212 * @param rlimits null-ok an array of rlimit tuples, with the second
213 * dimension having a length of 3 and representing
214 * (resource, rlim_cur, rlim_max). These are set via the posix
215 * setrlimit(2) call.
216 * @param seInfo null-ok a string specifying SELinux information for
217 * the new process.
218 * @param niceName null-ok a string specifying the process name.
219 * @param fdsToClose an array of ints, holding one or more POSIX
220 * file descriptor numbers that are to be closed by the child
221 * (and replaced by /dev/null) after forking. An integer value
222 * of -1 in any entry in the array means "ignore this one".
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800223 * @param fdsToIgnore null-ok an array of ints, either null or holding
224 * one or more POSIX file descriptor numbers that are to be ignored
225 * in the file descriptor table check.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500226 * @param startChildZygote if true, the new child process will itself be a
227 * new zygote process.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700228 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400229 * @param appDataDir null-ok the data directory of the app.
Narayan Kamath973b4662014-03-31 13:41:26 +0100230 *
231 * @return 0 if this is the child, pid of the child
232 * if this is the parent, or -1 on error.
233 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100234 public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700235 int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
236 int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
237 String packageName, String[] packagesForUid, String[] visibleVolIds) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100238 VM_HOOKS.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800239 // Resets nice priority for zygote process.
240 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100241 int pid = nativeForkAndSpecialize(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800242 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
243 fdsToIgnore, startChildZygote, instructionSet, appDataDir, packageName,
244 packagesForUid, visibleVolIds);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100245 // Enable tracing as soon as possible for the child process.
246 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700247 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100248
249 // Note that this event ends at the end of handleChildProc,
250 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
251 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100252 VM_HOOKS.postForkCommon();
253 return pid;
254 }
255
Chris Wailesaa1c9622019-01-10 16:55:32 -0800256 private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
257 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
258 int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
259 String appDataDir, String packageName, String[] packagesForUid, String[] visibleVolIds);
260
Chris Wailescb0b37f2019-01-11 17:04:41 -0800261 /**
262 * Specialize a Blastula instance. The current VM must have been started
263 * with the -Xzygote flag.
264 *
265 * @param uid The UNIX uid that the new process should setuid() to before spawning any threads
266 * @param gid The UNIX gid that the new process should setgid() to before spawning any threads
267 * @param gids null-ok; A list of UNIX gids that the new process should
268 * setgroups() to before spawning any threads
269 * @param runtimeFlags Bit flags that enable ART features
270 * @param rlimits null-ok An array of rlimit tuples, with the second
271 * dimension having a length of 3 and representing
272 * (resource, rlim_cur, rlim_max). These are set via the posix
273 * setrlimit(2) call.
274 * @param seInfo null-ok A string specifying SELinux information for
275 * the new process.
276 * @param niceName null-ok A string specifying the process name.
277 * @param startChildZygote If true, the new child process will itself be a
278 * new zygote process.
279 * @param instructionSet null-ok The instruction set to use.
280 * @param appDataDir null-ok The data directory of the app.
281 */
282 public static void specializeBlastula(int uid, int gid, int[] gids, int runtimeFlags,
283 int[][] rlimits, int mountExternal, String seInfo, String niceName,
284 boolean startChildZygote, String instructionSet, String appDataDir,
285 String packageName, String[] packagesForUid, String[] visibleVolIds) {
286
287 nativeSpecializeBlastula(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
288 niceName, startChildZygote, instructionSet, appDataDir,
289 packageName, packagesForUid, visibleVolIds);
290
291 // Enable tracing as soon as possible for the child process.
292 Trace.setTracingEnabled(true, runtimeFlags);
293
294 // Note that this event ends at the end of handleChildProc.
295 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
296
297 /*
298 * This is called here (instead of after the fork but before the specialize) to maintain
299 * consistancy with the code paths for forkAndSpecialize.
300 *
301 * TODO (chriswailes): Look into moving this to immediately after the fork.
302 */
303 VM_HOOKS.postForkCommon();
304 }
305
Chris Wailesaa1c9622019-01-10 16:55:32 -0800306 private static native void nativeSpecializeBlastula(int uid, int gid, int[] gids,
307 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
308 boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
309 String[] packagesForUid, String[] visibleVolIds);
Narayan Kamath973b4662014-03-31 13:41:26 +0100310
311 /**
Christopher Ferris2980de42017-06-20 16:13:40 -0700312 * Called to do any initialization before starting an application.
313 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800314 static native void nativePreApplicationInit();
Christopher Ferris2980de42017-06-20 16:13:40 -0700315
316 /**
Narayan Kamath973b4662014-03-31 13:41:26 +0100317 * Special method to start the system server process. In addition to the
318 * common actions performed in forkAndSpecialize, the pid of the child
319 * process is recorded such that the death of the child process will cause
320 * zygote to exit.
321 *
322 * @param uid the UNIX uid that the new process should setuid() to after
323 * fork()ing and and before spawning any threads.
324 * @param gid the UNIX gid that the new process should setgid() to after
325 * fork()ing and and before spawning any threads.
326 * @param gids null-ok; a list of UNIX gids that the new process should
327 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100328 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100329 * @param rlimits null-ok an array of rlimit tuples, with the second
330 * dimension having a length of 3 and representing
331 * (resource, rlim_cur, rlim_max). These are set via the posix
332 * setrlimit(2) call.
333 * @param permittedCapabilities argument for setcap()
334 * @param effectiveCapabilities argument for setcap()
335 *
336 * @return 0 if this is the child, pid of the child
337 * if this is the parent, or -1 on error.
338 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100339 public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100340 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
341 VM_HOOKS.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800342 // Resets nice priority for zygote process.
343 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100344 int pid = nativeForkSystemServer(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800345 uid, gid, gids, runtimeFlags, rlimits,
346 permittedCapabilities, effectiveCapabilities);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100347 // Enable tracing as soon as we enter the system_server.
348 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700349 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100350 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100351 VM_HOOKS.postForkCommon();
352 return pid;
353 }
354
Chris Wailesaa1c9622019-01-10 16:55:32 -0800355 private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100356 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
357
doheon1.lee885b7422016-01-20 13:07:27 +0900358 /**
Robert Sesek54e387d2016-12-02 17:27:50 -0500359 * Lets children of the zygote inherit open file descriptors to this path.
360 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800361 protected static native void nativeAllowFileAcrossFork(String path);
Robert Sesek54e387d2016-12-02 17:27:50 -0500362
363 /**
Martijn Coenen86f08a52019-01-03 16:23:01 +0100364 * Installs a seccomp filter that limits setresuid()/setresgid() to the passed-in range
365 * @param uidGidMin The smallest allowed uid/gid
366 * @param uidGidMax The largest allowed uid/gid
367 */
368 native protected static void nativeInstallSeccompUidGidFilter(int uidGidMin, int uidGidMax);
369
370 /**
doheon1.lee885b7422016-01-20 13:07:27 +0900371 * Zygote unmount storage space on initializing.
372 * This method is called once.
373 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800374 protected static native void nativeUnmountStorageOnInit();
375
Chris Wailescb0b37f2019-01-11 17:04:41 -0800376 /**
377 * Get socket file descriptors (opened by init) from the environment and
378 * store them for access from native code later.
379 *
380 * @param isPrimary True if this is the zygote process, false if it is zygote_secondary
381 */
382 public static void getSocketFDs(boolean isPrimary) {
383 nativeGetSocketFDs(isPrimary);
384 }
385
Chris Wailesaa1c9622019-01-10 16:55:32 -0800386 protected static native void nativeGetSocketFDs(boolean isPrimary);
387
Chris Wailescb0b37f2019-01-11 17:04:41 -0800388 /**
389 * Initialize the blastula pool and fill it with the desired number of
390 * processes.
391 */
392 protected static Runnable initBlastulaPool() {
393 if (BLASTULA_POOL_ENABLED) {
394 sBlastulaPoolEventFD = getBlastulaPoolEventFD();
395
396 return fillBlastulaPool(null);
397 } else {
398 return null;
399 }
400 }
401
402 /**
403 * Checks to see if the current policy says that pool should be refilled, and spawns new
404 * blastulas if necessary.
405 *
406 * NOTE: This function doesn't need to be guarded with BLASTULA_POOL_ENABLED because it is
407 * only called from contexts that are only valid if the pool is enabled.
408 *
409 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
410 * @return In the Zygote process this function will always return null; in blastula processes
411 * this function will return a Runnable object representing the new application that is
412 * passed up from blastulaMain.
413 */
414 protected static Runnable fillBlastulaPool(int[] sessionSocketRawFDs) {
415 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Zygote:FillBlastulaPool");
416
417 int blastulaPoolCount = getBlastulaPoolCount();
418
419 int numBlastulasToSpawn = sBlastulaPoolMax - blastulaPoolCount;
420
421 if (blastulaPoolCount < sBlastulaPoolMin
422 || numBlastulasToSpawn >= sBlastulaPoolRefillThreshold) {
423
424 // Disable some VM functionality and reset some system values
425 // before forking.
426 VM_HOOKS.preFork();
427 resetNicePriority();
428
429 while (blastulaPoolCount++ < sBlastulaPoolMax) {
430 Runnable caller = forkBlastula(sessionSocketRawFDs);
431
432 if (caller != null) {
433 return caller;
434 }
435 }
436
437 // Re-enable runtime services for the Zygote. Blastula services
438 // are re-enabled in specializeBlastula.
439 VM_HOOKS.postForkCommon();
440
441 Log.i("zygote", "Filled the blastula pool. New blastulas: " + numBlastulasToSpawn);
442 }
443
444 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
445
446 return null;
447 }
448
449 /**
450 * @return Number of blastulas currently in the pool
451 */
452 private static int getBlastulaPoolCount() {
453 return nativeGetBlastulaPoolCount();
454 }
455
Chris Wailesaa1c9622019-01-10 16:55:32 -0800456 private static native int nativeGetBlastulaPoolCount();
457
Chris Wailescb0b37f2019-01-11 17:04:41 -0800458 /**
459 * @return The event FD used for communication between the signal handler and the ZygoteServer
460 * poll loop
461 */
462 private static FileDescriptor getBlastulaPoolEventFD() {
463 FileDescriptor fd = new FileDescriptor();
464 fd.setInt$(nativeGetBlastulaPoolEventFD());
465
466 return fd;
467 }
468
Chris Wailesaa1c9622019-01-10 16:55:32 -0800469 private static native int nativeGetBlastulaPoolEventFD();
470
Chris Wailescb0b37f2019-01-11 17:04:41 -0800471 /**
472 * Fork a new blastula process from the zygote
473 *
474 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
475 * @return In the Zygote process this function will always return null; in blastula processes
476 * this function will return a Runnable object representing the new application that is
477 * passed up from blastulaMain.
478 */
479 private static Runnable forkBlastula(int[] sessionSocketRawFDs) {
480 FileDescriptor[] pipeFDs = null;
481
482 try {
483 pipeFDs = Os.pipe2(O_CLOEXEC);
484 } catch (ErrnoException errnoEx) {
485 throw new IllegalStateException("Unable to create blastula pipe.", errnoEx);
486 }
487
488 int pid =
489 nativeForkBlastula(pipeFDs[0].getInt$(), pipeFDs[1].getInt$(), sessionSocketRawFDs);
490
491 if (pid == 0) {
492 IoUtils.closeQuietly(pipeFDs[0]);
493 return blastulaMain(pipeFDs[1]);
494 } else {
495 // The read-end of the pipe will be closed by the native code.
496 // See removeBlastulaTableEntry();
497 IoUtils.closeQuietly(pipeFDs[1]);
498 return null;
499 }
500 }
501
Chris Wailesaa1c9622019-01-10 16:55:32 -0800502 private static native int nativeForkBlastula(int readPipeFD,
503 int writePipeFD,
504 int[] sessionSocketRawFDs);
505
Chris Wailescb0b37f2019-01-11 17:04:41 -0800506 /**
507 * This function is used by blastulas to wait for specialization requests from the system
508 * server.
509 *
510 * @param writePipe The write end of the reporting pipe used to communicate with the poll loop
511 * of the ZygoteServer.
512 * @return A runnable oject representing the new application.
513 */
514 static Runnable blastulaMain(FileDescriptor writePipe) {
515 final int pid = Process.myPid();
516
517 LocalSocket sessionSocket = null;
518 DataOutputStream blastulaOutputStream = null;
519 Credentials peerCredentials = null;
520 String[] argStrings = null;
521
522 while (true) {
523 try {
524 sessionSocket = sBlastulaPoolSocket.accept();
525
526 BufferedReader blastulaReader =
527 new BufferedReader(new InputStreamReader(sessionSocket.getInputStream()));
528 blastulaOutputStream =
529 new DataOutputStream(sessionSocket.getOutputStream());
530
531 peerCredentials = sessionSocket.getPeerCredentials();
532
533 argStrings = readArgumentList(blastulaReader);
534
535 if (argStrings != null) {
536 break;
537 } else {
538 Log.e("Blastula", "Truncated command received.");
539 IoUtils.closeQuietly(sessionSocket);
540 }
541 } catch (IOException ioEx) {
542 Log.e("Blastula", "Failed to read command: " + ioEx.getMessage());
543 IoUtils.closeQuietly(sessionSocket);
544 }
545 }
546
547 ZygoteArguments args = new ZygoteArguments(argStrings);
548
549 // TODO (chriswailes): Should this only be run for debug builds?
550 validateBlastulaCommand(args);
551
552 applyUidSecurityPolicy(args, peerCredentials);
553 applyDebuggerSystemProperty(args);
554
555 int[][] rlimits = null;
556
557 if (args.mRLimits != null) {
558 rlimits = args.mRLimits.toArray(INT_ARRAY_2D);
559 }
560
561 // This must happen before the SELinux policy for this process is
562 // changed when specializing.
563 try {
564 // Used by ZygoteProcess.zygoteSendArgsAndGetResult to fill in a
565 // Process.ProcessStartResult object.
566 blastulaOutputStream.writeInt(pid);
567 } catch (IOException ioEx) {
568 Log.e("Blastula", "Failed to write response to session socket: " + ioEx.getMessage());
569 System.exit(-1);
570 } finally {
571 IoUtils.closeQuietly(sessionSocket);
572 IoUtils.closeQuietly(sBlastulaPoolSocket);
573 }
574
575 try {
576 ByteArrayOutputStream buffer =
577 new ByteArrayOutputStream(Zygote.BLASTULA_MANAGEMENT_MESSAGE_BYTES);
578 DataOutputStream outputStream = new DataOutputStream(buffer);
579
580 // This is written as a long so that the blastula reporting pipe and blastula pool
581 // event FD handlers in ZygoteServer.runSelectLoop can be unified. These two cases
582 // should both send/receive 8 bytes.
583 outputStream.writeLong(pid);
584 outputStream.flush();
585
586 Os.write(writePipe, buffer.toByteArray(), 0, buffer.size());
587 } catch (Exception ex) {
588 Log.e("Blastula",
589 String.format("Failed to write PID (%d) to pipe (%d): %s",
590 pid, writePipe.getInt$(), ex.getMessage()));
591 System.exit(-1);
592 } finally {
593 IoUtils.closeQuietly(writePipe);
594 }
595
596 specializeBlastula(args.mUid, args.mGid, args.mGids,
597 args.mRuntimeFlags, rlimits, args.mMountExternal,
598 args.mSeInfo, args.mNiceName, args.mStartChildZygote,
599 args.mInstructionSet, args.mAppDataDir, args.mPackageName,
600 args.mPackagesForUid, args.mVisibleVolIds);
601
602 if (args.mNiceName != null) {
603 Process.setArgV0(args.mNiceName);
604 }
605
606 // End of the postFork event.
607 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
608
609 return ZygoteInit.zygoteInit(args.mTargetSdkVersion,
610 args.mRemainingArgs,
611 null /* classLoader */);
612 }
613
614 private static final String BLASTULA_ERROR_PREFIX = "Invalid command to blastula: ";
615
616 /**
617 * Checks a set of zygote arguments to see if they can be handled by a blastula. Throws an
618 * exception if an invalid arugment is encountered.
619 * @param args The arguments to test
620 */
621 static void validateBlastulaCommand(ZygoteArguments args) {
622 if (args.mAbiListQuery) {
623 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--query-abi-list");
624 } else if (args.mPidQuery) {
625 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--get-pid");
626 } else if (args.mPreloadDefault) {
627 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-default");
628 } else if (args.mPreloadPackage != null) {
629 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-package");
630 } else if (args.mPreloadApp != null) {
631 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-app");
632 } else if (args.mStartChildZygote) {
633 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--start-child-zygote");
634 } else if (args.mApiBlacklistExemptions != null) {
635 throw new IllegalArgumentException(
636 BLASTULA_ERROR_PREFIX + "--set-api-blacklist-exemptions");
637 } else if (args.mHiddenApiAccessLogSampleRate != -1) {
638 throw new IllegalArgumentException(
639 BLASTULA_ERROR_PREFIX + "--hidden-api-log-sampling-rate=");
640 } else if (args.mInvokeWith != null) {
641 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--invoke-with");
642 } else if (args.mPermittedCapabilities != 0 || args.mEffectiveCapabilities != 0) {
643 throw new ZygoteSecurityException("Client may not specify capabilities: "
644 + "permitted=0x" + Long.toHexString(args.mPermittedCapabilities)
645 + ", effective=0x" + Long.toHexString(args.mEffectiveCapabilities));
646 }
647 }
648
649 /**
650 * @return Raw file descriptors for the read-end of blastula reporting pipes.
651 */
652 protected static int[] getBlastulaPipeFDs() {
653 return nativeGetBlastulaPipeFDs();
654 }
655
Chris Wailesaa1c9622019-01-10 16:55:32 -0800656 private static native int[] nativeGetBlastulaPipeFDs();
657
Chris Wailescb0b37f2019-01-11 17:04:41 -0800658 /**
659 * Remove the blastula table entry for the provided process ID.
660 *
661 * @param blastulaPID Process ID of the entry to remove
662 * @return True if the entry was removed; false if it doesn't exist
663 */
664 protected static boolean removeBlastulaTableEntry(int blastulaPID) {
665 return nativeRemoveBlastulaTableEntry(blastulaPID);
666 }
667
Chris Wailesaa1c9622019-01-10 16:55:32 -0800668 private static native boolean nativeRemoveBlastulaTableEntry(int blastulaPID);
669
Chris Wailes2be26262019-01-11 16:14:43 -0800670 /**
671 * uid 1000 (Process.SYSTEM_UID) may specify any uid &gt; 1000 in normal
672 * operation. It may also specify any gid and setgroups() list it chooses.
673 * In factory test mode, it may specify any UID.
674 *
675 * @param args non-null; zygote spawner arguments
676 * @param peer non-null; peer credentials
677 * @throws ZygoteSecurityException
678 */
679 protected static void applyUidSecurityPolicy(ZygoteArguments args, Credentials peer)
680 throws ZygoteSecurityException {
681
682 if (peer.getUid() == Process.SYSTEM_UID) {
683 /* In normal operation, SYSTEM_UID can only specify a restricted
684 * set of UIDs. In factory test mode, SYSTEM_UID may specify any uid.
685 */
686 boolean uidRestricted = FactoryTest.getMode() == FactoryTest.FACTORY_TEST_OFF;
687
688 if (uidRestricted && args.mUidSpecified && (args.mUid < Process.SYSTEM_UID)) {
689 throw new ZygoteSecurityException(
690 "System UID may not launch process with UID < "
691 + Process.SYSTEM_UID);
692 }
693 }
694
695 // If not otherwise specified, uid and gid are inherited from peer
696 if (!args.mUidSpecified) {
697 args.mUid = peer.getUid();
698 args.mUidSpecified = true;
699 }
700 if (!args.mGidSpecified) {
701 args.mGid = peer.getGid();
702 args.mGidSpecified = true;
703 }
704 }
705
706 /**
707 * Applies debugger system properties to the zygote arguments.
708 *
709 * If "ro.debuggable" is "1", all apps are debuggable. Otherwise,
710 * the debugger state is specified via the "--enable-jdwp" flag
711 * in the spawn request.
712 *
713 * @param args non-null; zygote spawner args
714 */
715 protected static void applyDebuggerSystemProperty(ZygoteArguments args) {
716 if (RoSystemProperties.DEBUGGABLE) {
717 args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
718 }
719 }
720
721 /**
722 * Applies zygote security policy.
723 * Based on the credentials of the process issuing a zygote command:
724 * <ol>
725 * <li> uid 0 (root) may specify --invoke-with to launch Zygote with a
726 * wrapper command.
727 * <li> Any other uid may not specify any invoke-with argument.
728 * </ul>
729 *
730 * @param args non-null; zygote spawner arguments
731 * @param peer non-null; peer credentials
732 * @throws ZygoteSecurityException
733 */
734 protected static void applyInvokeWithSecurityPolicy(ZygoteArguments args, Credentials peer)
735 throws ZygoteSecurityException {
736 int peerUid = peer.getUid();
737
738 if (args.mInvokeWith != null && peerUid != 0
739 && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
740 throw new ZygoteSecurityException("Peer is permitted to specify an"
741 + "explicit invoke-with wrapper command only for debuggable"
742 + "applications.");
743 }
744 }
745
746 /**
747 * Applies invoke-with system properties to the zygote arguments.
748 *
749 * @param args non-null; zygote args
750 */
751 protected static void applyInvokeWithSystemProperty(ZygoteArguments args) {
752 if (args.mInvokeWith == null && args.mNiceName != null) {
753 String property = "wrap." + args.mNiceName;
754 args.mInvokeWith = SystemProperties.get(property);
755 if (args.mInvokeWith != null && args.mInvokeWith.length() == 0) {
756 args.mInvokeWith = null;
757 }
758 }
759 }
760
761 /**
762 * Reads an argument list from the provided socket
763 * @return Argument list or null if EOF is reached
764 * @throws IOException passed straight through
765 */
766 static String[] readArgumentList(BufferedReader socketReader) throws IOException {
767
768 /**
769 * See android.os.Process.zygoteSendArgsAndGetPid()
770 * Presently the wire format to the zygote process is:
771 * a) a count of arguments (argc, in essence)
772 * b) a number of newline-separated argument strings equal to count
773 *
774 * After the zygote process reads these it will write the pid of
775 * the child or -1 on failure.
776 */
777
778 int argc;
779
780 try {
781 String argc_string = socketReader.readLine();
782
783 if (argc_string == null) {
784 // EOF reached.
785 return null;
786 }
787 argc = Integer.parseInt(argc_string);
788
789 } catch (NumberFormatException ex) {
790 Log.e("Zygote", "Invalid Zygote wire format: non-int at argc");
791 throw new IOException("Invalid wire format");
792 }
793
794 // See bug 1092107: large argc can be used for a DOS attack
795 if (argc > MAX_ZYGOTE_ARGC) {
796 throw new IOException("Max arg count exceeded");
797 }
798
799 String[] args = new String[argc];
800 for (int arg_index = 0; arg_index < argc; arg_index++) {
801 args[arg_index] = socketReader.readLine();
802 if (args[arg_index] == null) {
803 // We got an unexpected EOF.
804 throw new IOException("Truncated request");
805 }
806 }
807
808 return args;
809 }
810
Chris Wailescb0b37f2019-01-11 17:04:41 -0800811 /**
812 * Creates a managed object representing the Blastula pool socket that has
813 * already been initialized and bound by init.
814 *
815 * TODO (chriswailes): Move the name selection logic into this function.
816 *
817 * @throws RuntimeException when open fails
818 */
819 static void createBlastulaSocket(String socketName) {
820 if (BLASTULA_POOL_ENABLED && sBlastulaPoolSocket == null) {
821 sBlastulaPoolSocket = createManagedSocketFromInitSocket(socketName);
822 }
823 }
824
825 /**
826 * Creates a managed LocalServerSocket object using a file descriptor
827 * created by an init.rc script. The init scripts that specify the
828 * sockets name can be found in system/core/rootdir. The socket is bound
829 * to the file system in the /dev/sockets/ directory, and the file
830 * descriptor is shared via the ANDROID_SOCKET_<socketName> environment
831 * variable.
832 */
833 static LocalServerSocket createManagedSocketFromInitSocket(String socketName) {
834 int fileDesc;
835 final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
836
837 try {
838 String env = System.getenv(fullSocketName);
839 fileDesc = Integer.parseInt(env);
840 } catch (RuntimeException ex) {
841 throw new RuntimeException("Socket unset or invalid: " + fullSocketName, ex);
842 }
843
844 try {
845 FileDescriptor fd = new FileDescriptor();
846 fd.setInt$(fileDesc);
847 return new LocalServerSocket(fd);
848 } catch (IOException ex) {
849 throw new RuntimeException(
850 "Error building socket from file descriptor: " + fileDesc, ex);
851 }
852 }
doheon1.lee885b7422016-01-20 13:07:27 +0900853
Orion Hodson46724e72018-10-19 13:05:33 +0100854 private static void callPostForkSystemServerHooks() {
855 // SystemServer specific post fork hooks run before child post fork hooks.
856 VM_HOOKS.postForkSystemServer();
857 }
858
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100859 private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500860 boolean isZygote, String instructionSet) {
861 VM_HOOKS.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100862 }
863
Narayan Kamathb49996d2017-02-06 20:24:08 +0000864 /**
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800865 * Resets the calling thread priority to the default value (Thread.NORM_PRIORITY
866 * or nice value 0). This updates both the priority value in java.lang.Thread and
867 * the nice value (setpriority).
Narayan Kamathb49996d2017-02-06 20:24:08 +0000868 */
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800869 static void resetNicePriority() {
870 Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
871 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100872
873 /**
874 * Executes "/system/bin/sh -c &lt;command&gt;" using the exec() system call.
875 * This method throws a runtime exception if exec() failed, otherwise, this
876 * method never returns.
877 *
878 * @param command The shell command to execute.
879 */
880 public static void execShell(String command) {
881 String[] args = { "/system/bin/sh", "-c", command };
882 try {
Elliott Hughes860c5912014-04-28 19:19:13 -0700883 Os.execv(args[0], args);
Narayan Kamath973b4662014-03-31 13:41:26 +0100884 } catch (ErrnoException e) {
885 throw new RuntimeException(e);
886 }
887 }
888
889 /**
890 * Appends quotes shell arguments to the specified string builder.
891 * The arguments are quoted using single-quotes, escaped if necessary,
892 * prefixed with a space, and appended to the command.
893 *
894 * @param command A string builder for the shell command being constructed.
895 * @param args An array of argument strings to be quoted and appended to the command.
896 * @see #execShell(String)
897 */
898 public static void appendQuotedShellArgs(StringBuilder command, String[] args) {
899 for (String arg : args) {
900 command.append(" '").append(arg.replace("'", "'\\''")).append("'");
901 }
902 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100903}