blob: 069413fe6678e5d06a51f069a301d4c34b07cdd4 [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
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800120 /**
121 * If the blastula pool should be created and used to start applications.
122 *
123 * Setting this value to false will disable the creation, maintenance, and use of the blastula
124 * pool. When the blastula pool is disabled the application lifecycle will be identical to
125 * previous versions of Android.
126 */
Chris Wailescb0b37f2019-01-11 17:04:41 -0800127 public static final boolean BLASTULA_POOL_ENABLED = false;
128
129 /**
130 * File descriptor used for communication between the signal handler and the ZygoteServer poll
131 * loop.
132 * */
133 protected static FileDescriptor sBlastulaPoolEventFD;
134
Narayan Kamath973b4662014-03-31 13:41:26 +0100135 private static final ZygoteHooks VM_HOOKS = new ZygoteHooks();
136
Robert Sesekd0a190df2018-02-12 18:46:01 -0500137 /**
138 * An extraArg passed when a zygote process is forking a child-zygote, specifying a name
139 * in the abstract socket namespace. This socket name is what the new child zygote
140 * should listen for connections on.
141 */
142 public static final String CHILD_ZYGOTE_SOCKET_NAME_ARG = "--zygote-socket=";
143
Martijn Coenen7e6fa672018-11-05 11:45:26 +0100144 /**
145 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
146 * requested ABI for the child Zygote.
147 */
148 public static final String CHILD_ZYGOTE_ABI_LIST_ARG = "--abi-list=";
149
Martijn Coenen86f08a52019-01-03 16:23:01 +0100150 /**
151 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
152 * start of the UID range the children of the Zygote may setuid()/setgid() to. This
153 * will be enforced with a seccomp filter.
154 */
155 public static final String CHILD_ZYGOTE_UID_RANGE_START = "--uid-range-start=";
156
157 /**
158 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
159 * end of the UID range the children of the Zygote may setuid()/setgid() to. This
160 * will be enforced with a seccomp filter.
161 */
162 public static final String CHILD_ZYGOTE_UID_RANGE_END = "--uid-range-end=";
163
Chris Wailescb0b37f2019-01-11 17:04:41 -0800164 /** Prefix prepended to socket names created by init */
165 private static final String ANDROID_SOCKET_PREFIX = "ANDROID_SOCKET_";
166
167 /**
168 * The maximum value that the sBlastulaPoolMax variable may take. This value
169 * is a mirror of BLASTULA_POOL_MAX_LIMIT found in com_android_internal_os_Zygote.cpp.
170 */
171 static final int BLASTULA_POOL_MAX_LIMIT = 10;
172
173 /**
174 * The minimum value that the sBlastulaPoolMin variable may take.
175 */
176 static final int BLASTULA_POOL_MIN_LIMIT = 1;
177
178 /**
179 * The runtime-adjustable maximum Blastula pool size.
180 */
181 static int sBlastulaPoolMax = BLASTULA_POOL_MAX_LIMIT;
182
183 /**
184 * The runtime-adjustable minimum Blastula pool size.
185 */
186 static int sBlastulaPoolMin = BLASTULA_POOL_MIN_LIMIT;
187
188 /**
189 * The runtime-adjustable value used to determine when to re-fill the
190 * blastula pool. The pool will be re-filled when
191 * (sBlastulaPoolMax - gBlastulaPoolCount) >= sBlastulaPoolRefillThreshold.
192 */
193 // TODO (chriswailes): This must be updated at the same time as sBlastulaPoolMax.
194 static int sBlastulaPoolRefillThreshold = (sBlastulaPoolMax / 2);
195
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800196 /**
197 * @hide for internal use only
198 */
199 public static final int SOCKET_BUFFER_SIZE = 256;
200
Chris Wailescb0b37f2019-01-11 17:04:41 -0800201 private static LocalServerSocket sBlastulaPoolSocket = null;
202
Chris Wailes2be26262019-01-11 16:14:43 -0800203 /** a prototype instance for a future List.toArray() */
204 protected static final int[][] INT_ARRAY_2D = new int[0][0];
205
Narayan Kamath973b4662014-03-31 13:41:26 +0100206 private Zygote() {}
207
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800208 /** Called for some security initialization before any fork. */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800209 static native void nativeSecurityInit();
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800210
Narayan Kamath973b4662014-03-31 13:41:26 +0100211 /**
212 * Forks a new VM instance. The current VM must have been started
213 * with the -Xzygote flag. <b>NOTE: new instance keeps all
214 * root capabilities. The new process is expected to call capset()</b>.
215 *
216 * @param uid the UNIX uid that the new process should setuid() to after
217 * fork()ing and and before spawning any threads.
218 * @param gid the UNIX gid that the new process should setgid() to after
219 * fork()ing and and before spawning any threads.
220 * @param gids null-ok; a list of UNIX gids that the new process should
221 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100222 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100223 * @param rlimits null-ok an array of rlimit tuples, with the second
224 * dimension having a length of 3 and representing
225 * (resource, rlim_cur, rlim_max). These are set via the posix
226 * setrlimit(2) call.
227 * @param seInfo null-ok a string specifying SELinux information for
228 * the new process.
229 * @param niceName null-ok a string specifying the process name.
230 * @param fdsToClose an array of ints, holding one or more POSIX
231 * file descriptor numbers that are to be closed by the child
232 * (and replaced by /dev/null) after forking. An integer value
233 * of -1 in any entry in the array means "ignore this one".
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800234 * @param fdsToIgnore null-ok an array of ints, either null or holding
235 * one or more POSIX file descriptor numbers that are to be ignored
236 * in the file descriptor table check.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500237 * @param startChildZygote if true, the new child process will itself be a
238 * new zygote process.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700239 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400240 * @param appDataDir null-ok the data directory of the app.
Narayan Kamath973b4662014-03-31 13:41:26 +0100241 *
242 * @return 0 if this is the child, pid of the child
243 * if this is the parent, or -1 on error.
244 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100245 public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700246 int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
247 int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800248 String packageName, String[] packagesForUID, String[] visibleVolIDs) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100249 VM_HOOKS.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800250 // Resets nice priority for zygote process.
251 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100252 int pid = nativeForkAndSpecialize(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800253 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
254 fdsToIgnore, startChildZygote, instructionSet, appDataDir, packageName,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800255 packagesForUID, visibleVolIDs);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100256 // Enable tracing as soon as possible for the child process.
257 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700258 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100259
260 // Note that this event ends at the end of handleChildProc,
261 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
262 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100263 VM_HOOKS.postForkCommon();
264 return pid;
265 }
266
Chris Wailesaa1c9622019-01-10 16:55:32 -0800267 private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
268 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
269 int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800270 String appDataDir, String packageName, String[] packagesForUID, String[] visibleVolIDs);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800271
Chris Wailescb0b37f2019-01-11 17:04:41 -0800272 /**
273 * Specialize a Blastula instance. The current VM must have been started
274 * with the -Xzygote flag.
275 *
276 * @param uid The UNIX uid that the new process should setuid() to before spawning any threads
277 * @param gid The UNIX gid that the new process should setgid() to before spawning any threads
278 * @param gids null-ok; A list of UNIX gids that the new process should
279 * setgroups() to before spawning any threads
280 * @param runtimeFlags Bit flags that enable ART features
281 * @param rlimits null-ok An array of rlimit tuples, with the second
282 * dimension having a length of 3 and representing
283 * (resource, rlim_cur, rlim_max). These are set via the posix
284 * setrlimit(2) call.
285 * @param seInfo null-ok A string specifying SELinux information for
286 * the new process.
287 * @param niceName null-ok A string specifying the process name.
288 * @param startChildZygote If true, the new child process will itself be a
289 * new zygote process.
290 * @param instructionSet null-ok The instruction set to use.
291 * @param appDataDir null-ok The data directory of the app.
292 */
293 public static void specializeBlastula(int uid, int gid, int[] gids, int runtimeFlags,
294 int[][] rlimits, int mountExternal, String seInfo, String niceName,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800295 boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
296 String[] packagesForUID, String[] visibleVolIDs) {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800297
298 nativeSpecializeBlastula(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
299 niceName, startChildZygote, instructionSet, appDataDir,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800300 packageName, packagesForUID, visibleVolIDs);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800301
302 // Enable tracing as soon as possible for the child process.
303 Trace.setTracingEnabled(true, runtimeFlags);
304
305 // Note that this event ends at the end of handleChildProc.
306 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
307
308 /*
309 * This is called here (instead of after the fork but before the specialize) to maintain
310 * consistancy with the code paths for forkAndSpecialize.
311 *
312 * TODO (chriswailes): Look into moving this to immediately after the fork.
313 */
314 VM_HOOKS.postForkCommon();
315 }
316
Chris Wailesaa1c9622019-01-10 16:55:32 -0800317 private static native void nativeSpecializeBlastula(int uid, int gid, int[] gids,
318 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
319 boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800320 String[] packagesForUID, String[] visibleVolIDs);
Narayan Kamath973b4662014-03-31 13:41:26 +0100321
322 /**
Christopher Ferris2980de42017-06-20 16:13:40 -0700323 * Called to do any initialization before starting an application.
324 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800325 static native void nativePreApplicationInit();
Christopher Ferris2980de42017-06-20 16:13:40 -0700326
327 /**
Narayan Kamath973b4662014-03-31 13:41:26 +0100328 * Special method to start the system server process. In addition to the
329 * common actions performed in forkAndSpecialize, the pid of the child
330 * process is recorded such that the death of the child process will cause
331 * zygote to exit.
332 *
333 * @param uid the UNIX uid that the new process should setuid() to after
334 * fork()ing and and before spawning any threads.
335 * @param gid the UNIX gid that the new process should setgid() to after
336 * fork()ing and and before spawning any threads.
337 * @param gids null-ok; a list of UNIX gids that the new process should
338 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100339 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100340 * @param rlimits null-ok an array of rlimit tuples, with the second
341 * dimension having a length of 3 and representing
342 * (resource, rlim_cur, rlim_max). These are set via the posix
343 * setrlimit(2) call.
344 * @param permittedCapabilities argument for setcap()
345 * @param effectiveCapabilities argument for setcap()
346 *
347 * @return 0 if this is the child, pid of the child
348 * if this is the parent, or -1 on error.
349 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100350 public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100351 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
352 VM_HOOKS.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800353 // Resets nice priority for zygote process.
354 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100355 int pid = nativeForkSystemServer(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800356 uid, gid, gids, runtimeFlags, rlimits,
357 permittedCapabilities, effectiveCapabilities);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100358 // Enable tracing as soon as we enter the system_server.
359 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700360 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100361 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100362 VM_HOOKS.postForkCommon();
363 return pid;
364 }
365
Chris Wailesaa1c9622019-01-10 16:55:32 -0800366 private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100367 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
368
doheon1.lee885b7422016-01-20 13:07:27 +0900369 /**
Robert Sesek54e387d2016-12-02 17:27:50 -0500370 * Lets children of the zygote inherit open file descriptors to this path.
371 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800372 protected static native void nativeAllowFileAcrossFork(String path);
Robert Sesek54e387d2016-12-02 17:27:50 -0500373
374 /**
Martijn Coenen86f08a52019-01-03 16:23:01 +0100375 * Installs a seccomp filter that limits setresuid()/setresgid() to the passed-in range
376 * @param uidGidMin The smallest allowed uid/gid
377 * @param uidGidMax The largest allowed uid/gid
378 */
379 native protected static void nativeInstallSeccompUidGidFilter(int uidGidMin, int uidGidMax);
380
381 /**
doheon1.lee885b7422016-01-20 13:07:27 +0900382 * Zygote unmount storage space on initializing.
383 * This method is called once.
384 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800385 protected static native void nativeUnmountStorageOnInit();
386
Chris Wailescb0b37f2019-01-11 17:04:41 -0800387 /**
388 * Get socket file descriptors (opened by init) from the environment and
389 * store them for access from native code later.
390 *
391 * @param isPrimary True if this is the zygote process, false if it is zygote_secondary
392 */
393 public static void getSocketFDs(boolean isPrimary) {
394 nativeGetSocketFDs(isPrimary);
395 }
396
Chris Wailesaa1c9622019-01-10 16:55:32 -0800397 protected static native void nativeGetSocketFDs(boolean isPrimary);
398
Chris Wailescb0b37f2019-01-11 17:04:41 -0800399 /**
400 * Initialize the blastula pool and fill it with the desired number of
401 * processes.
402 */
403 protected static Runnable initBlastulaPool() {
404 if (BLASTULA_POOL_ENABLED) {
405 sBlastulaPoolEventFD = getBlastulaPoolEventFD();
406
407 return fillBlastulaPool(null);
408 } else {
409 return null;
410 }
411 }
412
413 /**
414 * Checks to see if the current policy says that pool should be refilled, and spawns new
415 * blastulas if necessary.
416 *
417 * NOTE: This function doesn't need to be guarded with BLASTULA_POOL_ENABLED because it is
418 * only called from contexts that are only valid if the pool is enabled.
419 *
420 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
421 * @return In the Zygote process this function will always return null; in blastula processes
422 * this function will return a Runnable object representing the new application that is
423 * passed up from blastulaMain.
424 */
425 protected static Runnable fillBlastulaPool(int[] sessionSocketRawFDs) {
426 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Zygote:FillBlastulaPool");
427
428 int blastulaPoolCount = getBlastulaPoolCount();
429
430 int numBlastulasToSpawn = sBlastulaPoolMax - blastulaPoolCount;
431
432 if (blastulaPoolCount < sBlastulaPoolMin
433 || numBlastulasToSpawn >= sBlastulaPoolRefillThreshold) {
434
435 // Disable some VM functionality and reset some system values
436 // before forking.
437 VM_HOOKS.preFork();
438 resetNicePriority();
439
440 while (blastulaPoolCount++ < sBlastulaPoolMax) {
441 Runnable caller = forkBlastula(sessionSocketRawFDs);
442
443 if (caller != null) {
444 return caller;
445 }
446 }
447
448 // Re-enable runtime services for the Zygote. Blastula services
449 // are re-enabled in specializeBlastula.
450 VM_HOOKS.postForkCommon();
451
452 Log.i("zygote", "Filled the blastula pool. New blastulas: " + numBlastulasToSpawn);
453 }
454
455 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
456
457 return null;
458 }
459
460 /**
461 * @return Number of blastulas currently in the pool
462 */
463 private static int getBlastulaPoolCount() {
464 return nativeGetBlastulaPoolCount();
465 }
466
Chris Wailesaa1c9622019-01-10 16:55:32 -0800467 private static native int nativeGetBlastulaPoolCount();
468
Chris Wailescb0b37f2019-01-11 17:04:41 -0800469 /**
470 * @return The event FD used for communication between the signal handler and the ZygoteServer
471 * poll loop
472 */
473 private static FileDescriptor getBlastulaPoolEventFD() {
474 FileDescriptor fd = new FileDescriptor();
475 fd.setInt$(nativeGetBlastulaPoolEventFD());
476
477 return fd;
478 }
479
Chris Wailesaa1c9622019-01-10 16:55:32 -0800480 private static native int nativeGetBlastulaPoolEventFD();
481
Chris Wailescb0b37f2019-01-11 17:04:41 -0800482 /**
483 * Fork a new blastula process from the zygote
484 *
485 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
486 * @return In the Zygote process this function will always return null; in blastula processes
487 * this function will return a Runnable object representing the new application that is
488 * passed up from blastulaMain.
489 */
490 private static Runnable forkBlastula(int[] sessionSocketRawFDs) {
491 FileDescriptor[] pipeFDs = null;
492
493 try {
494 pipeFDs = Os.pipe2(O_CLOEXEC);
495 } catch (ErrnoException errnoEx) {
496 throw new IllegalStateException("Unable to create blastula pipe.", errnoEx);
497 }
498
499 int pid =
500 nativeForkBlastula(pipeFDs[0].getInt$(), pipeFDs[1].getInt$(), sessionSocketRawFDs);
501
502 if (pid == 0) {
503 IoUtils.closeQuietly(pipeFDs[0]);
504 return blastulaMain(pipeFDs[1]);
505 } else {
506 // The read-end of the pipe will be closed by the native code.
507 // See removeBlastulaTableEntry();
508 IoUtils.closeQuietly(pipeFDs[1]);
509 return null;
510 }
511 }
512
Chris Wailesaa1c9622019-01-10 16:55:32 -0800513 private static native int nativeForkBlastula(int readPipeFD,
514 int writePipeFD,
515 int[] sessionSocketRawFDs);
516
Chris Wailescb0b37f2019-01-11 17:04:41 -0800517 /**
518 * This function is used by blastulas to wait for specialization requests from the system
519 * server.
520 *
521 * @param writePipe The write end of the reporting pipe used to communicate with the poll loop
522 * of the ZygoteServer.
523 * @return A runnable oject representing the new application.
524 */
525 static Runnable blastulaMain(FileDescriptor writePipe) {
526 final int pid = Process.myPid();
527
528 LocalSocket sessionSocket = null;
529 DataOutputStream blastulaOutputStream = null;
530 Credentials peerCredentials = null;
531 String[] argStrings = null;
532
533 while (true) {
534 try {
535 sessionSocket = sBlastulaPoolSocket.accept();
536
537 BufferedReader blastulaReader =
538 new BufferedReader(new InputStreamReader(sessionSocket.getInputStream()));
539 blastulaOutputStream =
540 new DataOutputStream(sessionSocket.getOutputStream());
541
542 peerCredentials = sessionSocket.getPeerCredentials();
543
544 argStrings = readArgumentList(blastulaReader);
545
546 if (argStrings != null) {
547 break;
548 } else {
549 Log.e("Blastula", "Truncated command received.");
550 IoUtils.closeQuietly(sessionSocket);
551 }
552 } catch (IOException ioEx) {
553 Log.e("Blastula", "Failed to read command: " + ioEx.getMessage());
554 IoUtils.closeQuietly(sessionSocket);
555 }
556 }
557
558 ZygoteArguments args = new ZygoteArguments(argStrings);
559
560 // TODO (chriswailes): Should this only be run for debug builds?
561 validateBlastulaCommand(args);
562
563 applyUidSecurityPolicy(args, peerCredentials);
564 applyDebuggerSystemProperty(args);
565
566 int[][] rlimits = null;
567
568 if (args.mRLimits != null) {
569 rlimits = args.mRLimits.toArray(INT_ARRAY_2D);
570 }
571
572 // This must happen before the SELinux policy for this process is
573 // changed when specializing.
574 try {
575 // Used by ZygoteProcess.zygoteSendArgsAndGetResult to fill in a
576 // Process.ProcessStartResult object.
577 blastulaOutputStream.writeInt(pid);
578 } catch (IOException ioEx) {
579 Log.e("Blastula", "Failed to write response to session socket: " + ioEx.getMessage());
580 System.exit(-1);
581 } finally {
582 IoUtils.closeQuietly(sessionSocket);
583 IoUtils.closeQuietly(sBlastulaPoolSocket);
584 }
585
586 try {
587 ByteArrayOutputStream buffer =
588 new ByteArrayOutputStream(Zygote.BLASTULA_MANAGEMENT_MESSAGE_BYTES);
589 DataOutputStream outputStream = new DataOutputStream(buffer);
590
591 // This is written as a long so that the blastula reporting pipe and blastula pool
592 // event FD handlers in ZygoteServer.runSelectLoop can be unified. These two cases
593 // should both send/receive 8 bytes.
594 outputStream.writeLong(pid);
595 outputStream.flush();
596
597 Os.write(writePipe, buffer.toByteArray(), 0, buffer.size());
598 } catch (Exception ex) {
599 Log.e("Blastula",
600 String.format("Failed to write PID (%d) to pipe (%d): %s",
601 pid, writePipe.getInt$(), ex.getMessage()));
602 System.exit(-1);
603 } finally {
604 IoUtils.closeQuietly(writePipe);
605 }
606
607 specializeBlastula(args.mUid, args.mGid, args.mGids,
608 args.mRuntimeFlags, rlimits, args.mMountExternal,
609 args.mSeInfo, args.mNiceName, args.mStartChildZygote,
610 args.mInstructionSet, args.mAppDataDir, args.mPackageName,
611 args.mPackagesForUid, args.mVisibleVolIds);
612
613 if (args.mNiceName != null) {
614 Process.setArgV0(args.mNiceName);
615 }
616
617 // End of the postFork event.
618 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
619
620 return ZygoteInit.zygoteInit(args.mTargetSdkVersion,
621 args.mRemainingArgs,
622 null /* classLoader */);
623 }
624
625 private static final String BLASTULA_ERROR_PREFIX = "Invalid command to blastula: ";
626
627 /**
628 * Checks a set of zygote arguments to see if they can be handled by a blastula. Throws an
629 * exception if an invalid arugment is encountered.
630 * @param args The arguments to test
631 */
632 static void validateBlastulaCommand(ZygoteArguments args) {
633 if (args.mAbiListQuery) {
634 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--query-abi-list");
635 } else if (args.mPidQuery) {
636 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--get-pid");
637 } else if (args.mPreloadDefault) {
638 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-default");
639 } else if (args.mPreloadPackage != null) {
640 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-package");
641 } else if (args.mPreloadApp != null) {
642 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-app");
643 } else if (args.mStartChildZygote) {
644 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--start-child-zygote");
645 } else if (args.mApiBlacklistExemptions != null) {
646 throw new IllegalArgumentException(
647 BLASTULA_ERROR_PREFIX + "--set-api-blacklist-exemptions");
648 } else if (args.mHiddenApiAccessLogSampleRate != -1) {
649 throw new IllegalArgumentException(
650 BLASTULA_ERROR_PREFIX + "--hidden-api-log-sampling-rate=");
651 } else if (args.mInvokeWith != null) {
652 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--invoke-with");
653 } else if (args.mPermittedCapabilities != 0 || args.mEffectiveCapabilities != 0) {
654 throw new ZygoteSecurityException("Client may not specify capabilities: "
655 + "permitted=0x" + Long.toHexString(args.mPermittedCapabilities)
656 + ", effective=0x" + Long.toHexString(args.mEffectiveCapabilities));
657 }
658 }
659
660 /**
661 * @return Raw file descriptors for the read-end of blastula reporting pipes.
662 */
663 protected static int[] getBlastulaPipeFDs() {
664 return nativeGetBlastulaPipeFDs();
665 }
666
Chris Wailesaa1c9622019-01-10 16:55:32 -0800667 private static native int[] nativeGetBlastulaPipeFDs();
668
Chris Wailescb0b37f2019-01-11 17:04:41 -0800669 /**
670 * Remove the blastula table entry for the provided process ID.
671 *
672 * @param blastulaPID Process ID of the entry to remove
673 * @return True if the entry was removed; false if it doesn't exist
674 */
675 protected static boolean removeBlastulaTableEntry(int blastulaPID) {
676 return nativeRemoveBlastulaTableEntry(blastulaPID);
677 }
678
Chris Wailesaa1c9622019-01-10 16:55:32 -0800679 private static native boolean nativeRemoveBlastulaTableEntry(int blastulaPID);
680
Chris Wailes2be26262019-01-11 16:14:43 -0800681 /**
682 * uid 1000 (Process.SYSTEM_UID) may specify any uid &gt; 1000 in normal
683 * operation. It may also specify any gid and setgroups() list it chooses.
684 * In factory test mode, it may specify any UID.
685 *
686 * @param args non-null; zygote spawner arguments
687 * @param peer non-null; peer credentials
688 * @throws ZygoteSecurityException
689 */
690 protected static void applyUidSecurityPolicy(ZygoteArguments args, Credentials peer)
691 throws ZygoteSecurityException {
692
693 if (peer.getUid() == Process.SYSTEM_UID) {
694 /* In normal operation, SYSTEM_UID can only specify a restricted
695 * set of UIDs. In factory test mode, SYSTEM_UID may specify any uid.
696 */
697 boolean uidRestricted = FactoryTest.getMode() == FactoryTest.FACTORY_TEST_OFF;
698
699 if (uidRestricted && args.mUidSpecified && (args.mUid < Process.SYSTEM_UID)) {
700 throw new ZygoteSecurityException(
701 "System UID may not launch process with UID < "
702 + Process.SYSTEM_UID);
703 }
704 }
705
706 // If not otherwise specified, uid and gid are inherited from peer
707 if (!args.mUidSpecified) {
708 args.mUid = peer.getUid();
709 args.mUidSpecified = true;
710 }
711 if (!args.mGidSpecified) {
712 args.mGid = peer.getGid();
713 args.mGidSpecified = true;
714 }
715 }
716
717 /**
718 * Applies debugger system properties to the zygote arguments.
719 *
720 * If "ro.debuggable" is "1", all apps are debuggable. Otherwise,
721 * the debugger state is specified via the "--enable-jdwp" flag
722 * in the spawn request.
723 *
724 * @param args non-null; zygote spawner args
725 */
726 protected static void applyDebuggerSystemProperty(ZygoteArguments args) {
727 if (RoSystemProperties.DEBUGGABLE) {
728 args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
729 }
730 }
731
732 /**
733 * Applies zygote security policy.
734 * Based on the credentials of the process issuing a zygote command:
735 * <ol>
736 * <li> uid 0 (root) may specify --invoke-with to launch Zygote with a
737 * wrapper command.
738 * <li> Any other uid may not specify any invoke-with argument.
739 * </ul>
740 *
741 * @param args non-null; zygote spawner arguments
742 * @param peer non-null; peer credentials
743 * @throws ZygoteSecurityException
744 */
745 protected static void applyInvokeWithSecurityPolicy(ZygoteArguments args, Credentials peer)
746 throws ZygoteSecurityException {
747 int peerUid = peer.getUid();
748
749 if (args.mInvokeWith != null && peerUid != 0
750 && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
751 throw new ZygoteSecurityException("Peer is permitted to specify an"
752 + "explicit invoke-with wrapper command only for debuggable"
753 + "applications.");
754 }
755 }
756
757 /**
758 * Applies invoke-with system properties to the zygote arguments.
759 *
760 * @param args non-null; zygote args
761 */
762 protected static void applyInvokeWithSystemProperty(ZygoteArguments args) {
763 if (args.mInvokeWith == null && args.mNiceName != null) {
764 String property = "wrap." + args.mNiceName;
765 args.mInvokeWith = SystemProperties.get(property);
766 if (args.mInvokeWith != null && args.mInvokeWith.length() == 0) {
767 args.mInvokeWith = null;
768 }
769 }
770 }
771
772 /**
773 * Reads an argument list from the provided socket
774 * @return Argument list or null if EOF is reached
775 * @throws IOException passed straight through
776 */
777 static String[] readArgumentList(BufferedReader socketReader) throws IOException {
778
779 /**
780 * See android.os.Process.zygoteSendArgsAndGetPid()
781 * Presently the wire format to the zygote process is:
782 * a) a count of arguments (argc, in essence)
783 * b) a number of newline-separated argument strings equal to count
784 *
785 * After the zygote process reads these it will write the pid of
786 * the child or -1 on failure.
787 */
788
789 int argc;
790
791 try {
792 String argc_string = socketReader.readLine();
793
794 if (argc_string == null) {
795 // EOF reached.
796 return null;
797 }
798 argc = Integer.parseInt(argc_string);
799
800 } catch (NumberFormatException ex) {
801 Log.e("Zygote", "Invalid Zygote wire format: non-int at argc");
802 throw new IOException("Invalid wire format");
803 }
804
805 // See bug 1092107: large argc can be used for a DOS attack
806 if (argc > MAX_ZYGOTE_ARGC) {
807 throw new IOException("Max arg count exceeded");
808 }
809
810 String[] args = new String[argc];
811 for (int arg_index = 0; arg_index < argc; arg_index++) {
812 args[arg_index] = socketReader.readLine();
813 if (args[arg_index] == null) {
814 // We got an unexpected EOF.
815 throw new IOException("Truncated request");
816 }
817 }
818
819 return args;
820 }
821
Chris Wailescb0b37f2019-01-11 17:04:41 -0800822 /**
823 * Creates a managed object representing the Blastula pool socket that has
824 * already been initialized and bound by init.
825 *
826 * TODO (chriswailes): Move the name selection logic into this function.
827 *
828 * @throws RuntimeException when open fails
829 */
830 static void createBlastulaSocket(String socketName) {
831 if (BLASTULA_POOL_ENABLED && sBlastulaPoolSocket == null) {
832 sBlastulaPoolSocket = createManagedSocketFromInitSocket(socketName);
833 }
834 }
835
836 /**
837 * Creates a managed LocalServerSocket object using a file descriptor
838 * created by an init.rc script. The init scripts that specify the
839 * sockets name can be found in system/core/rootdir. The socket is bound
840 * to the file system in the /dev/sockets/ directory, and the file
841 * descriptor is shared via the ANDROID_SOCKET_<socketName> environment
842 * variable.
843 */
844 static LocalServerSocket createManagedSocketFromInitSocket(String socketName) {
845 int fileDesc;
846 final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
847
848 try {
849 String env = System.getenv(fullSocketName);
850 fileDesc = Integer.parseInt(env);
851 } catch (RuntimeException ex) {
852 throw new RuntimeException("Socket unset or invalid: " + fullSocketName, ex);
853 }
854
855 try {
856 FileDescriptor fd = new FileDescriptor();
857 fd.setInt$(fileDesc);
858 return new LocalServerSocket(fd);
859 } catch (IOException ex) {
860 throw new RuntimeException(
861 "Error building socket from file descriptor: " + fileDesc, ex);
862 }
863 }
doheon1.lee885b7422016-01-20 13:07:27 +0900864
Orion Hodson46724e72018-10-19 13:05:33 +0100865 private static void callPostForkSystemServerHooks() {
866 // SystemServer specific post fork hooks run before child post fork hooks.
867 VM_HOOKS.postForkSystemServer();
868 }
869
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100870 private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500871 boolean isZygote, String instructionSet) {
872 VM_HOOKS.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100873 }
874
Narayan Kamathb49996d2017-02-06 20:24:08 +0000875 /**
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800876 * Resets the calling thread priority to the default value (Thread.NORM_PRIORITY
877 * or nice value 0). This updates both the priority value in java.lang.Thread and
878 * the nice value (setpriority).
Narayan Kamathb49996d2017-02-06 20:24:08 +0000879 */
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800880 static void resetNicePriority() {
881 Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
882 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100883
884 /**
885 * Executes "/system/bin/sh -c &lt;command&gt;" using the exec() system call.
886 * This method throws a runtime exception if exec() failed, otherwise, this
887 * method never returns.
888 *
889 * @param command The shell command to execute.
890 */
891 public static void execShell(String command) {
892 String[] args = { "/system/bin/sh", "-c", command };
893 try {
Elliott Hughes860c5912014-04-28 19:19:13 -0700894 Os.execv(args[0], args);
Narayan Kamath973b4662014-03-31 13:41:26 +0100895 } catch (ErrnoException e) {
896 throw new RuntimeException(e);
897 }
898 }
899
900 /**
901 * Appends quotes shell arguments to the specified string builder.
902 * The arguments are quoted using single-quotes, escaped if necessary,
903 * prefixed with a space, and appended to the command.
904 *
905 * @param command A string builder for the shell command being constructed.
906 * @param args An array of argument strings to be quoted and appended to the command.
907 * @see #execShell(String)
908 */
909 public static void appendQuotedShellArgs(StringBuilder command, String[] args) {
910 for (String arg : args) {
911 command.append(" '").append(arg.replace("'", "'\\''")).append("'");
912 }
913 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100914}