blob: b881aef221cedae88d7affbedf0aa138d266a440 [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
Martijn Coenen4b988162019-01-28 13:58:45 +010023import android.content.pm.ApplicationInfo;
Chris Wailes2be26262019-01-11 16:14:43 -080024import android.net.Credentials;
Chris Wailescb0b37f2019-01-11 17:04:41 -080025import android.net.LocalServerSocket;
26import android.net.LocalSocket;
Chris Wailes2be26262019-01-11 16:14:43 -080027import android.os.FactoryTest;
Jeff Sharkeyace874b2017-09-07 15:27:33 -060028import android.os.IVold;
Chris Wailes2be26262019-01-11 16:14:43 -080029import android.os.Process;
30import android.os.SystemProperties;
Narayan Kamathfbb32f62015-06-12 15:34:35 +010031import android.os.Trace;
Elliott Hughes860c5912014-04-28 19:19:13 -070032import android.system.ErrnoException;
33import android.system.Os;
Chris Wailes2be26262019-01-11 16:14:43 -080034import android.util.Log;
Narayan Kamath973b4662014-03-31 13:41:26 +010035
Jeff Sharkeyace874b2017-09-07 15:27:33 -060036import dalvik.system.ZygoteHooks;
Tobias Sargeantb9679dc2016-01-19 16:34:54 +000037
Chris Wailescb0b37f2019-01-11 17:04:41 -080038import libcore.io.IoUtils;
39
Chris Wailes2be26262019-01-11 16:14:43 -080040import java.io.BufferedReader;
Chris Wailescb0b37f2019-01-11 17:04:41 -080041import java.io.ByteArrayOutputStream;
42import java.io.DataOutputStream;
43import java.io.FileDescriptor;
Chris Wailes2be26262019-01-11 16:14:43 -080044import java.io.IOException;
Chris Wailescb0b37f2019-01-11 17:04:41 -080045import java.io.InputStreamReader;
Chris Wailes2be26262019-01-11 16:14:43 -080046
Narayan Kamath973b4662014-03-31 13:41:26 +010047/** @hide */
48public final class Zygote {
49 /*
Nicolas Geoffray81edac42017-09-07 14:13:29 +010050 * Bit values for "runtimeFlags" argument. The definitions are duplicated
Narayan Kamath973b4662014-03-31 13:41:26 +010051 * in the native code.
52 */
53
54 /** enable debugging over JDWP */
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000055 public static final int DEBUG_ENABLE_JDWP = 1;
Narayan Kamath973b4662014-03-31 13:41:26 +010056 /** enable JNI checks */
57 public static final int DEBUG_ENABLE_CHECKJNI = 1 << 1;
58 /** enable Java programming language "assert" statements */
59 public static final int DEBUG_ENABLE_ASSERT = 1 << 2;
Mathieu Chartier7a490282015-03-17 09:51:36 -070060 /** disable the AOT compiler and JIT */
Narayan Kamath973b4662014-03-31 13:41:26 +010061 public static final int DEBUG_ENABLE_SAFEMODE = 1 << 3;
62 /** Enable logging of third-party JNI activity. */
63 public static final int DEBUG_ENABLE_JNI_LOGGING = 1 << 4;
David Srbecky065075e2015-05-28 17:16:09 +010064 /** Force generation of native debugging information. */
Nicolas Geoffray9abbf452015-11-05 11:29:42 +000065 public static final int DEBUG_GENERATE_DEBUG_INFO = 1 << 5;
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000066 /** Always use JIT-ed code. */
67 public static final int DEBUG_ALWAYS_JIT = 1 << 6;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000068 /** Make the code native debuggable by turning off some optimizations. */
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000069 public static final int DEBUG_NATIVE_DEBUGGABLE = 1 << 7;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000070 /** Make the code Java debuggable by turning off some optimizations. */
71 public static final int DEBUG_JAVA_DEBUGGABLE = 1 << 8;
Mathieu Chartier7a490282015-03-17 09:51:36 -070072
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010073 /** Turn off the verifier. */
74 public static final int DISABLE_VERIFIER = 1 << 9;
75 /** Only use oat files located in /system. Otherwise use dex/jar/apk . */
76 public static final int ONLY_USE_SYSTEM_OAT_FILES = 1 << 10;
David Srbecky156ed922018-01-30 14:37:37 +000077 /** Force generation of native debugging information for backtraces. */
Mathew Inwood16073b82018-03-23 10:05:01 +000078 public static final int DEBUG_GENERATE_MINI_DEBUG_INFO = 1 << 11;
79 /**
80 * Hidden API access restrictions. This is a mask for bits representing the API enforcement
81 * policy, defined by {@code @ApplicationInfo.HiddenApiEnforcementPolicy}.
82 */
83 public static final int API_ENFORCEMENT_POLICY_MASK = (1 << 12) | (1 << 13);
84 /**
85 * Bit shift for use with {@link #API_ENFORCEMENT_POLICY_MASK}.
86 *
87 * (flags & API_ENFORCEMENT_POLICY_MASK) >> API_ENFORCEMENT_POLICY_SHIFT gives
88 * @ApplicationInfo.ApiEnforcementPolicy values.
89 */
90 public static final int API_ENFORCEMENT_POLICY_SHIFT =
91 Integer.numberOfTrailingZeros(API_ENFORCEMENT_POLICY_MASK);
Calin Juravle8eb891b2018-05-03 19:51:18 -070092 /**
93 * Enable system server ART profiling.
94 */
95 public static final int PROFILE_SYSTEM_SERVER = 1 << 14;
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010096
Yabin Cui4d8546d2019-01-29 16:29:20 -080097 /**
98 * Enable profiling from shell.
99 */
100 public static final int PROFILE_FROM_SHELL = 1 << 15;
101
Narayan Kamath973b4662014-03-31 13:41:26 +0100102 /** No external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600103 public static final int MOUNT_EXTERNAL_NONE = IVold.REMOUNT_MODE_NONE;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700104 /** Default external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600105 public static final int MOUNT_EXTERNAL_DEFAULT = IVold.REMOUNT_MODE_DEFAULT;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700106 /** Read-only external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600107 public static final int MOUNT_EXTERNAL_READ = IVold.REMOUNT_MODE_READ;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700108 /** Read-write external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600109 public static final int MOUNT_EXTERNAL_WRITE = IVold.REMOUNT_MODE_WRITE;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800110 /**
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800111 * Mount mode for apps that are already installed on the device before the isolated_storage
112 * feature is enabled.
113 */
114 public static final int MOUNT_EXTERNAL_LEGACY = IVold.REMOUNT_MODE_LEGACY;
115 /**
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800116 * Mount mode for package installers which should give them access to
117 * all obb dirs in addition to their package sandboxes
118 */
119 public static final int MOUNT_EXTERNAL_INSTALLER = IVold.REMOUNT_MODE_INSTALLER;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700120 /** Read-write external storage should be mounted instead of package sandbox */
121 public static final int MOUNT_EXTERNAL_FULL = IVold.REMOUNT_MODE_FULL;
Narayan Kamath973b4662014-03-31 13:41:26 +0100122
Chris Wailescb0b37f2019-01-11 17:04:41 -0800123 /** Number of bytes sent to the Zygote over blastula pipes or the pool event FD */
124 public static final int BLASTULA_MANAGEMENT_MESSAGE_BYTES = 8;
125
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800126 /**
127 * If the blastula pool should be created and used to start applications.
128 *
129 * Setting this value to false will disable the creation, maintenance, and use of the blastula
130 * pool. When the blastula pool is disabled the application lifecycle will be identical to
131 * previous versions of Android.
132 */
Chris Wailescb0b37f2019-01-11 17:04:41 -0800133 public static final boolean BLASTULA_POOL_ENABLED = false;
134
135 /**
136 * File descriptor used for communication between the signal handler and the ZygoteServer poll
137 * loop.
138 * */
139 protected static FileDescriptor sBlastulaPoolEventFD;
140
Robert Sesekd0a190df2018-02-12 18:46:01 -0500141 /**
142 * An extraArg passed when a zygote process is forking a child-zygote, specifying a name
143 * in the abstract socket namespace. This socket name is what the new child zygote
144 * should listen for connections on.
145 */
146 public static final String CHILD_ZYGOTE_SOCKET_NAME_ARG = "--zygote-socket=";
147
Martijn Coenen7e6fa672018-11-05 11:45:26 +0100148 /**
149 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
150 * requested ABI for the child Zygote.
151 */
152 public static final String CHILD_ZYGOTE_ABI_LIST_ARG = "--abi-list=";
153
Martijn Coenen86f08a52019-01-03 16:23:01 +0100154 /**
155 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
156 * start of the UID range the children of the Zygote may setuid()/setgid() to. This
157 * will be enforced with a seccomp filter.
158 */
159 public static final String CHILD_ZYGOTE_UID_RANGE_START = "--uid-range-start=";
160
161 /**
162 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
163 * end of the UID range the children of the Zygote may setuid()/setgid() to. This
164 * will be enforced with a seccomp filter.
165 */
166 public static final String CHILD_ZYGOTE_UID_RANGE_END = "--uid-range-end=";
167
Chris Wailescb0b37f2019-01-11 17:04:41 -0800168 /** Prefix prepended to socket names created by init */
169 private static final String ANDROID_SOCKET_PREFIX = "ANDROID_SOCKET_";
170
171 /**
172 * The maximum value that the sBlastulaPoolMax variable may take. This value
173 * is a mirror of BLASTULA_POOL_MAX_LIMIT found in com_android_internal_os_Zygote.cpp.
174 */
175 static final int BLASTULA_POOL_MAX_LIMIT = 10;
176
177 /**
178 * The minimum value that the sBlastulaPoolMin variable may take.
179 */
180 static final int BLASTULA_POOL_MIN_LIMIT = 1;
181
182 /**
183 * The runtime-adjustable maximum Blastula pool size.
184 */
185 static int sBlastulaPoolMax = BLASTULA_POOL_MAX_LIMIT;
186
187 /**
188 * The runtime-adjustable minimum Blastula pool size.
189 */
190 static int sBlastulaPoolMin = BLASTULA_POOL_MIN_LIMIT;
191
192 /**
193 * The runtime-adjustable value used to determine when to re-fill the
194 * blastula pool. The pool will be re-filled when
195 * (sBlastulaPoolMax - gBlastulaPoolCount) >= sBlastulaPoolRefillThreshold.
196 */
197 // TODO (chriswailes): This must be updated at the same time as sBlastulaPoolMax.
198 static int sBlastulaPoolRefillThreshold = (sBlastulaPoolMax / 2);
199
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800200 /**
201 * @hide for internal use only
202 */
203 public static final int SOCKET_BUFFER_SIZE = 256;
204
Chris Wailescb0b37f2019-01-11 17:04:41 -0800205 private static LocalServerSocket sBlastulaPoolSocket = null;
206
Chris Wailes2be26262019-01-11 16:14:43 -0800207 /** a prototype instance for a future List.toArray() */
208 protected static final int[][] INT_ARRAY_2D = new int[0][0];
209
Narayan Kamath973b4662014-03-31 13:41:26 +0100210 private Zygote() {}
211
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800212 /** Called for some security initialization before any fork. */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800213 static native void nativeSecurityInit();
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800214
Narayan Kamath973b4662014-03-31 13:41:26 +0100215 /**
216 * Forks a new VM instance. The current VM must have been started
217 * with the -Xzygote flag. <b>NOTE: new instance keeps all
218 * root capabilities. The new process is expected to call capset()</b>.
219 *
220 * @param uid the UNIX uid that the new process should setuid() to after
221 * fork()ing and and before spawning any threads.
222 * @param gid the UNIX gid that the new process should setgid() to after
223 * fork()ing and and before spawning any threads.
224 * @param gids null-ok; a list of UNIX gids that the new process should
225 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100226 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100227 * @param rlimits null-ok an array of rlimit tuples, with the second
228 * dimension having a length of 3 and representing
229 * (resource, rlim_cur, rlim_max). These are set via the posix
230 * setrlimit(2) call.
231 * @param seInfo null-ok a string specifying SELinux information for
232 * the new process.
233 * @param niceName null-ok a string specifying the process name.
234 * @param fdsToClose an array of ints, holding one or more POSIX
235 * file descriptor numbers that are to be closed by the child
236 * (and replaced by /dev/null) after forking. An integer value
237 * of -1 in any entry in the array means "ignore this one".
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800238 * @param fdsToIgnore null-ok an array of ints, either null or holding
239 * one or more POSIX file descriptor numbers that are to be ignored
240 * in the file descriptor table check.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500241 * @param startChildZygote if true, the new child process will itself be a
242 * new zygote process.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700243 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400244 * @param appDataDir null-ok the data directory of the app.
Narayan Kamath973b4662014-03-31 13:41:26 +0100245 *
246 * @return 0 if this is the child, pid of the child
247 * if this is the parent, or -1 on error.
248 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100249 public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700250 int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
251 int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800252 String packageName, String[] packagesForUID, String[] visibleVolIDs) {
Neil Fuller555d8b72019-01-28 18:29:20 +0000253 ZygoteHooks.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800254 // Resets nice priority for zygote process.
255 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100256 int pid = nativeForkAndSpecialize(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800257 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
258 fdsToIgnore, startChildZygote, instructionSet, appDataDir, packageName,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800259 packagesForUID, visibleVolIDs);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100260 // Enable tracing as soon as possible for the child process.
261 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700262 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100263
264 // Note that this event ends at the end of handleChildProc,
265 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
266 }
Neil Fuller555d8b72019-01-28 18:29:20 +0000267 ZygoteHooks.postForkCommon();
Narayan Kamath973b4662014-03-31 13:41:26 +0100268 return pid;
269 }
270
Chris Wailesaa1c9622019-01-10 16:55:32 -0800271 private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
272 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
273 int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800274 String appDataDir, String packageName, String[] packagesForUID, String[] visibleVolIDs);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800275
Chris Wailescb0b37f2019-01-11 17:04:41 -0800276 /**
277 * Specialize a Blastula instance. The current VM must have been started
278 * with the -Xzygote flag.
279 *
280 * @param uid The UNIX uid that the new process should setuid() to before spawning any threads
281 * @param gid The UNIX gid that the new process should setgid() to before spawning any threads
282 * @param gids null-ok; A list of UNIX gids that the new process should
283 * setgroups() to before spawning any threads
284 * @param runtimeFlags Bit flags that enable ART features
285 * @param rlimits null-ok An array of rlimit tuples, with the second
286 * dimension having a length of 3 and representing
287 * (resource, rlim_cur, rlim_max). These are set via the posix
288 * setrlimit(2) call.
289 * @param seInfo null-ok A string specifying SELinux information for
290 * the new process.
291 * @param niceName null-ok A string specifying the process name.
292 * @param startChildZygote If true, the new child process will itself be a
293 * new zygote process.
294 * @param instructionSet null-ok The instruction set to use.
295 * @param appDataDir null-ok The data directory of the app.
296 */
297 public static void specializeBlastula(int uid, int gid, int[] gids, int runtimeFlags,
298 int[][] rlimits, int mountExternal, String seInfo, String niceName,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800299 boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
300 String[] packagesForUID, String[] visibleVolIDs) {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800301
302 nativeSpecializeBlastula(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
303 niceName, startChildZygote, instructionSet, appDataDir,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800304 packageName, packagesForUID, visibleVolIDs);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800305
306 // Enable tracing as soon as possible for the child process.
307 Trace.setTracingEnabled(true, runtimeFlags);
308
309 // Note that this event ends at the end of handleChildProc.
310 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
311
312 /*
313 * This is called here (instead of after the fork but before the specialize) to maintain
314 * consistancy with the code paths for forkAndSpecialize.
315 *
316 * TODO (chriswailes): Look into moving this to immediately after the fork.
317 */
Neil Fuller555d8b72019-01-28 18:29:20 +0000318 ZygoteHooks.postForkCommon();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800319 }
320
Chris Wailesaa1c9622019-01-10 16:55:32 -0800321 private static native void nativeSpecializeBlastula(int uid, int gid, int[] gids,
322 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
323 boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800324 String[] packagesForUID, String[] visibleVolIDs);
Narayan Kamath973b4662014-03-31 13:41:26 +0100325
326 /**
Christopher Ferris2980de42017-06-20 16:13:40 -0700327 * Called to do any initialization before starting an application.
328 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800329 static native void nativePreApplicationInit();
Christopher Ferris2980de42017-06-20 16:13:40 -0700330
331 /**
Narayan Kamath973b4662014-03-31 13:41:26 +0100332 * Special method to start the system server process. In addition to the
333 * common actions performed in forkAndSpecialize, the pid of the child
334 * process is recorded such that the death of the child process will cause
335 * zygote to exit.
336 *
337 * @param uid the UNIX uid that the new process should setuid() to after
338 * fork()ing and and before spawning any threads.
339 * @param gid the UNIX gid that the new process should setgid() to after
340 * fork()ing and and before spawning any threads.
341 * @param gids null-ok; a list of UNIX gids that the new process should
342 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100343 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100344 * @param rlimits null-ok an array of rlimit tuples, with the second
345 * dimension having a length of 3 and representing
346 * (resource, rlim_cur, rlim_max). These are set via the posix
347 * setrlimit(2) call.
348 * @param permittedCapabilities argument for setcap()
349 * @param effectiveCapabilities argument for setcap()
350 *
351 * @return 0 if this is the child, pid of the child
352 * if this is the parent, or -1 on error.
353 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100354 public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100355 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
Neil Fuller555d8b72019-01-28 18:29:20 +0000356 ZygoteHooks.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800357 // Resets nice priority for zygote process.
358 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100359 int pid = nativeForkSystemServer(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800360 uid, gid, gids, runtimeFlags, rlimits,
361 permittedCapabilities, effectiveCapabilities);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100362 // Enable tracing as soon as we enter the system_server.
363 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700364 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100365 }
Neil Fuller555d8b72019-01-28 18:29:20 +0000366 ZygoteHooks.postForkCommon();
Narayan Kamath973b4662014-03-31 13:41:26 +0100367 return pid;
368 }
369
Chris Wailesaa1c9622019-01-10 16:55:32 -0800370 private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100371 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
372
doheon1.lee885b7422016-01-20 13:07:27 +0900373 /**
Robert Sesek54e387d2016-12-02 17:27:50 -0500374 * Lets children of the zygote inherit open file descriptors to this path.
375 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800376 protected static native void nativeAllowFileAcrossFork(String path);
Robert Sesek54e387d2016-12-02 17:27:50 -0500377
378 /**
Martijn Coenen4b988162019-01-28 13:58:45 +0100379 * Lets children of the zygote inherit open file descriptors that belong to the
380 * ApplicationInfo that is passed in.
381 *
382 * @param appInfo ApplicationInfo of the application
383 */
384 protected static void allowAppFilesAcrossFork(ApplicationInfo appInfo) {
385 Zygote.nativeAllowFileAcrossFork(appInfo.sourceDir);
386 if (appInfo.splitSourceDirs != null) {
387 for (String path : appInfo.splitSourceDirs) {
388 Zygote.nativeAllowFileAcrossFork(path);
389 }
390 }
391 // As well as its shared libs
392 if (appInfo.sharedLibraryFiles != null) {
393 for (String path : appInfo.sharedLibraryFiles) {
394 Zygote.nativeAllowFileAcrossFork(path);
395 }
396 }
397 }
398
399 /**
Martijn Coenen86f08a52019-01-03 16:23:01 +0100400 * Installs a seccomp filter that limits setresuid()/setresgid() to the passed-in range
401 * @param uidGidMin The smallest allowed uid/gid
402 * @param uidGidMax The largest allowed uid/gid
403 */
404 native protected static void nativeInstallSeccompUidGidFilter(int uidGidMin, int uidGidMax);
405
406 /**
doheon1.lee885b7422016-01-20 13:07:27 +0900407 * Zygote unmount storage space on initializing.
408 * This method is called once.
409 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800410 protected static native void nativeUnmountStorageOnInit();
411
Chris Wailescb0b37f2019-01-11 17:04:41 -0800412 /**
413 * Get socket file descriptors (opened by init) from the environment and
414 * store them for access from native code later.
415 *
416 * @param isPrimary True if this is the zygote process, false if it is zygote_secondary
417 */
418 public static void getSocketFDs(boolean isPrimary) {
419 nativeGetSocketFDs(isPrimary);
420 }
421
Chris Wailesaa1c9622019-01-10 16:55:32 -0800422 protected static native void nativeGetSocketFDs(boolean isPrimary);
423
Chris Wailescb0b37f2019-01-11 17:04:41 -0800424 /**
425 * Initialize the blastula pool and fill it with the desired number of
426 * processes.
427 */
428 protected static Runnable initBlastulaPool() {
429 if (BLASTULA_POOL_ENABLED) {
430 sBlastulaPoolEventFD = getBlastulaPoolEventFD();
431
432 return fillBlastulaPool(null);
433 } else {
434 return null;
435 }
436 }
437
438 /**
439 * Checks to see if the current policy says that pool should be refilled, and spawns new
440 * blastulas if necessary.
441 *
442 * NOTE: This function doesn't need to be guarded with BLASTULA_POOL_ENABLED because it is
443 * only called from contexts that are only valid if the pool is enabled.
444 *
445 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
446 * @return In the Zygote process this function will always return null; in blastula processes
447 * this function will return a Runnable object representing the new application that is
448 * passed up from blastulaMain.
449 */
450 protected static Runnable fillBlastulaPool(int[] sessionSocketRawFDs) {
451 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Zygote:FillBlastulaPool");
452
453 int blastulaPoolCount = getBlastulaPoolCount();
454
455 int numBlastulasToSpawn = sBlastulaPoolMax - blastulaPoolCount;
456
457 if (blastulaPoolCount < sBlastulaPoolMin
458 || numBlastulasToSpawn >= sBlastulaPoolRefillThreshold) {
459
460 // Disable some VM functionality and reset some system values
461 // before forking.
Neil Fuller555d8b72019-01-28 18:29:20 +0000462 ZygoteHooks.preFork();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800463 resetNicePriority();
464
465 while (blastulaPoolCount++ < sBlastulaPoolMax) {
466 Runnable caller = forkBlastula(sessionSocketRawFDs);
467
468 if (caller != null) {
469 return caller;
470 }
471 }
472
473 // Re-enable runtime services for the Zygote. Blastula services
474 // are re-enabled in specializeBlastula.
Neil Fuller555d8b72019-01-28 18:29:20 +0000475 ZygoteHooks.postForkCommon();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800476
477 Log.i("zygote", "Filled the blastula pool. New blastulas: " + numBlastulasToSpawn);
478 }
479
480 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
481
482 return null;
483 }
484
485 /**
486 * @return Number of blastulas currently in the pool
487 */
488 private static int getBlastulaPoolCount() {
489 return nativeGetBlastulaPoolCount();
490 }
491
Chris Wailesaa1c9622019-01-10 16:55:32 -0800492 private static native int nativeGetBlastulaPoolCount();
493
Chris Wailescb0b37f2019-01-11 17:04:41 -0800494 /**
495 * @return The event FD used for communication between the signal handler and the ZygoteServer
496 * poll loop
497 */
498 private static FileDescriptor getBlastulaPoolEventFD() {
499 FileDescriptor fd = new FileDescriptor();
500 fd.setInt$(nativeGetBlastulaPoolEventFD());
501
502 return fd;
503 }
504
Chris Wailesaa1c9622019-01-10 16:55:32 -0800505 private static native int nativeGetBlastulaPoolEventFD();
506
Chris Wailescb0b37f2019-01-11 17:04:41 -0800507 /**
508 * Fork a new blastula process from the zygote
509 *
510 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
511 * @return In the Zygote process this function will always return null; in blastula processes
512 * this function will return a Runnable object representing the new application that is
513 * passed up from blastulaMain.
514 */
515 private static Runnable forkBlastula(int[] sessionSocketRawFDs) {
516 FileDescriptor[] pipeFDs = null;
517
518 try {
519 pipeFDs = Os.pipe2(O_CLOEXEC);
520 } catch (ErrnoException errnoEx) {
521 throw new IllegalStateException("Unable to create blastula pipe.", errnoEx);
522 }
523
524 int pid =
525 nativeForkBlastula(pipeFDs[0].getInt$(), pipeFDs[1].getInt$(), sessionSocketRawFDs);
526
527 if (pid == 0) {
528 IoUtils.closeQuietly(pipeFDs[0]);
529 return blastulaMain(pipeFDs[1]);
530 } else {
531 // The read-end of the pipe will be closed by the native code.
532 // See removeBlastulaTableEntry();
533 IoUtils.closeQuietly(pipeFDs[1]);
534 return null;
535 }
536 }
537
Chris Wailesaa1c9622019-01-10 16:55:32 -0800538 private static native int nativeForkBlastula(int readPipeFD,
539 int writePipeFD,
540 int[] sessionSocketRawFDs);
541
Chris Wailescb0b37f2019-01-11 17:04:41 -0800542 /**
543 * This function is used by blastulas to wait for specialization requests from the system
544 * server.
545 *
546 * @param writePipe The write end of the reporting pipe used to communicate with the poll loop
547 * of the ZygoteServer.
548 * @return A runnable oject representing the new application.
549 */
550 static Runnable blastulaMain(FileDescriptor writePipe) {
551 final int pid = Process.myPid();
552
553 LocalSocket sessionSocket = null;
554 DataOutputStream blastulaOutputStream = null;
555 Credentials peerCredentials = null;
556 String[] argStrings = null;
557
558 while (true) {
559 try {
560 sessionSocket = sBlastulaPoolSocket.accept();
561
562 BufferedReader blastulaReader =
563 new BufferedReader(new InputStreamReader(sessionSocket.getInputStream()));
564 blastulaOutputStream =
565 new DataOutputStream(sessionSocket.getOutputStream());
566
567 peerCredentials = sessionSocket.getPeerCredentials();
568
569 argStrings = readArgumentList(blastulaReader);
570
571 if (argStrings != null) {
572 break;
573 } else {
574 Log.e("Blastula", "Truncated command received.");
575 IoUtils.closeQuietly(sessionSocket);
576 }
577 } catch (IOException ioEx) {
578 Log.e("Blastula", "Failed to read command: " + ioEx.getMessage());
579 IoUtils.closeQuietly(sessionSocket);
580 }
581 }
582
583 ZygoteArguments args = new ZygoteArguments(argStrings);
584
585 // TODO (chriswailes): Should this only be run for debug builds?
586 validateBlastulaCommand(args);
587
588 applyUidSecurityPolicy(args, peerCredentials);
589 applyDebuggerSystemProperty(args);
590
591 int[][] rlimits = null;
592
593 if (args.mRLimits != null) {
594 rlimits = args.mRLimits.toArray(INT_ARRAY_2D);
595 }
596
597 // This must happen before the SELinux policy for this process is
598 // changed when specializing.
599 try {
600 // Used by ZygoteProcess.zygoteSendArgsAndGetResult to fill in a
601 // Process.ProcessStartResult object.
602 blastulaOutputStream.writeInt(pid);
603 } catch (IOException ioEx) {
604 Log.e("Blastula", "Failed to write response to session socket: " + ioEx.getMessage());
605 System.exit(-1);
606 } finally {
607 IoUtils.closeQuietly(sessionSocket);
608 IoUtils.closeQuietly(sBlastulaPoolSocket);
609 }
610
611 try {
612 ByteArrayOutputStream buffer =
613 new ByteArrayOutputStream(Zygote.BLASTULA_MANAGEMENT_MESSAGE_BYTES);
614 DataOutputStream outputStream = new DataOutputStream(buffer);
615
616 // This is written as a long so that the blastula reporting pipe and blastula pool
617 // event FD handlers in ZygoteServer.runSelectLoop can be unified. These two cases
618 // should both send/receive 8 bytes.
619 outputStream.writeLong(pid);
620 outputStream.flush();
621
622 Os.write(writePipe, buffer.toByteArray(), 0, buffer.size());
623 } catch (Exception ex) {
624 Log.e("Blastula",
625 String.format("Failed to write PID (%d) to pipe (%d): %s",
626 pid, writePipe.getInt$(), ex.getMessage()));
627 System.exit(-1);
628 } finally {
629 IoUtils.closeQuietly(writePipe);
630 }
631
632 specializeBlastula(args.mUid, args.mGid, args.mGids,
633 args.mRuntimeFlags, rlimits, args.mMountExternal,
634 args.mSeInfo, args.mNiceName, args.mStartChildZygote,
635 args.mInstructionSet, args.mAppDataDir, args.mPackageName,
636 args.mPackagesForUid, args.mVisibleVolIds);
637
638 if (args.mNiceName != null) {
639 Process.setArgV0(args.mNiceName);
640 }
641
642 // End of the postFork event.
643 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
644
645 return ZygoteInit.zygoteInit(args.mTargetSdkVersion,
646 args.mRemainingArgs,
647 null /* classLoader */);
648 }
649
650 private static final String BLASTULA_ERROR_PREFIX = "Invalid command to blastula: ";
651
652 /**
653 * Checks a set of zygote arguments to see if they can be handled by a blastula. Throws an
654 * exception if an invalid arugment is encountered.
655 * @param args The arguments to test
656 */
657 static void validateBlastulaCommand(ZygoteArguments args) {
658 if (args.mAbiListQuery) {
659 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--query-abi-list");
660 } else if (args.mPidQuery) {
661 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--get-pid");
662 } else if (args.mPreloadDefault) {
663 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-default");
664 } else if (args.mPreloadPackage != null) {
665 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-package");
666 } else if (args.mPreloadApp != null) {
667 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--preload-app");
668 } else if (args.mStartChildZygote) {
669 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--start-child-zygote");
670 } else if (args.mApiBlacklistExemptions != null) {
671 throw new IllegalArgumentException(
672 BLASTULA_ERROR_PREFIX + "--set-api-blacklist-exemptions");
673 } else if (args.mHiddenApiAccessLogSampleRate != -1) {
674 throw new IllegalArgumentException(
675 BLASTULA_ERROR_PREFIX + "--hidden-api-log-sampling-rate=");
676 } else if (args.mInvokeWith != null) {
677 throw new IllegalArgumentException(BLASTULA_ERROR_PREFIX + "--invoke-with");
678 } else if (args.mPermittedCapabilities != 0 || args.mEffectiveCapabilities != 0) {
679 throw new ZygoteSecurityException("Client may not specify capabilities: "
680 + "permitted=0x" + Long.toHexString(args.mPermittedCapabilities)
681 + ", effective=0x" + Long.toHexString(args.mEffectiveCapabilities));
682 }
683 }
684
685 /**
686 * @return Raw file descriptors for the read-end of blastula reporting pipes.
687 */
688 protected static int[] getBlastulaPipeFDs() {
689 return nativeGetBlastulaPipeFDs();
690 }
691
Chris Wailesaa1c9622019-01-10 16:55:32 -0800692 private static native int[] nativeGetBlastulaPipeFDs();
693
Chris Wailescb0b37f2019-01-11 17:04:41 -0800694 /**
695 * Remove the blastula table entry for the provided process ID.
696 *
697 * @param blastulaPID Process ID of the entry to remove
698 * @return True if the entry was removed; false if it doesn't exist
699 */
700 protected static boolean removeBlastulaTableEntry(int blastulaPID) {
701 return nativeRemoveBlastulaTableEntry(blastulaPID);
702 }
703
Chris Wailesaa1c9622019-01-10 16:55:32 -0800704 private static native boolean nativeRemoveBlastulaTableEntry(int blastulaPID);
705
Chris Wailes2be26262019-01-11 16:14:43 -0800706 /**
707 * uid 1000 (Process.SYSTEM_UID) may specify any uid &gt; 1000 in normal
708 * operation. It may also specify any gid and setgroups() list it chooses.
709 * In factory test mode, it may specify any UID.
710 *
711 * @param args non-null; zygote spawner arguments
712 * @param peer non-null; peer credentials
713 * @throws ZygoteSecurityException
714 */
715 protected static void applyUidSecurityPolicy(ZygoteArguments args, Credentials peer)
716 throws ZygoteSecurityException {
717
718 if (peer.getUid() == Process.SYSTEM_UID) {
719 /* In normal operation, SYSTEM_UID can only specify a restricted
720 * set of UIDs. In factory test mode, SYSTEM_UID may specify any uid.
721 */
722 boolean uidRestricted = FactoryTest.getMode() == FactoryTest.FACTORY_TEST_OFF;
723
724 if (uidRestricted && args.mUidSpecified && (args.mUid < Process.SYSTEM_UID)) {
725 throw new ZygoteSecurityException(
726 "System UID may not launch process with UID < "
727 + Process.SYSTEM_UID);
728 }
729 }
730
731 // If not otherwise specified, uid and gid are inherited from peer
732 if (!args.mUidSpecified) {
733 args.mUid = peer.getUid();
734 args.mUidSpecified = true;
735 }
736 if (!args.mGidSpecified) {
737 args.mGid = peer.getGid();
738 args.mGidSpecified = true;
739 }
740 }
741
742 /**
743 * Applies debugger system properties to the zygote arguments.
744 *
745 * If "ro.debuggable" is "1", all apps are debuggable. Otherwise,
746 * the debugger state is specified via the "--enable-jdwp" flag
747 * in the spawn request.
748 *
749 * @param args non-null; zygote spawner args
750 */
751 protected static void applyDebuggerSystemProperty(ZygoteArguments args) {
752 if (RoSystemProperties.DEBUGGABLE) {
753 args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
754 }
755 }
756
757 /**
758 * Applies zygote security policy.
759 * Based on the credentials of the process issuing a zygote command:
760 * <ol>
761 * <li> uid 0 (root) may specify --invoke-with to launch Zygote with a
762 * wrapper command.
763 * <li> Any other uid may not specify any invoke-with argument.
764 * </ul>
765 *
766 * @param args non-null; zygote spawner arguments
767 * @param peer non-null; peer credentials
768 * @throws ZygoteSecurityException
769 */
770 protected static void applyInvokeWithSecurityPolicy(ZygoteArguments args, Credentials peer)
771 throws ZygoteSecurityException {
772 int peerUid = peer.getUid();
773
774 if (args.mInvokeWith != null && peerUid != 0
775 && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
776 throw new ZygoteSecurityException("Peer is permitted to specify an"
777 + "explicit invoke-with wrapper command only for debuggable"
778 + "applications.");
779 }
780 }
781
782 /**
783 * Applies invoke-with system properties to the zygote arguments.
784 *
785 * @param args non-null; zygote args
786 */
787 protected static void applyInvokeWithSystemProperty(ZygoteArguments args) {
788 if (args.mInvokeWith == null && args.mNiceName != null) {
789 String property = "wrap." + args.mNiceName;
790 args.mInvokeWith = SystemProperties.get(property);
791 if (args.mInvokeWith != null && args.mInvokeWith.length() == 0) {
792 args.mInvokeWith = null;
793 }
794 }
795 }
796
797 /**
798 * Reads an argument list from the provided socket
799 * @return Argument list or null if EOF is reached
800 * @throws IOException passed straight through
801 */
802 static String[] readArgumentList(BufferedReader socketReader) throws IOException {
803
804 /**
805 * See android.os.Process.zygoteSendArgsAndGetPid()
806 * Presently the wire format to the zygote process is:
807 * a) a count of arguments (argc, in essence)
808 * b) a number of newline-separated argument strings equal to count
809 *
810 * After the zygote process reads these it will write the pid of
811 * the child or -1 on failure.
812 */
813
814 int argc;
815
816 try {
817 String argc_string = socketReader.readLine();
818
819 if (argc_string == null) {
820 // EOF reached.
821 return null;
822 }
823 argc = Integer.parseInt(argc_string);
824
825 } catch (NumberFormatException ex) {
826 Log.e("Zygote", "Invalid Zygote wire format: non-int at argc");
827 throw new IOException("Invalid wire format");
828 }
829
830 // See bug 1092107: large argc can be used for a DOS attack
831 if (argc > MAX_ZYGOTE_ARGC) {
832 throw new IOException("Max arg count exceeded");
833 }
834
835 String[] args = new String[argc];
836 for (int arg_index = 0; arg_index < argc; arg_index++) {
837 args[arg_index] = socketReader.readLine();
838 if (args[arg_index] == null) {
839 // We got an unexpected EOF.
840 throw new IOException("Truncated request");
841 }
842 }
843
844 return args;
845 }
846
Chris Wailescb0b37f2019-01-11 17:04:41 -0800847 /**
848 * Creates a managed object representing the Blastula pool socket that has
849 * already been initialized and bound by init.
850 *
851 * TODO (chriswailes): Move the name selection logic into this function.
852 *
853 * @throws RuntimeException when open fails
854 */
855 static void createBlastulaSocket(String socketName) {
856 if (BLASTULA_POOL_ENABLED && sBlastulaPoolSocket == null) {
857 sBlastulaPoolSocket = createManagedSocketFromInitSocket(socketName);
858 }
859 }
860
861 /**
862 * Creates a managed LocalServerSocket object using a file descriptor
863 * created by an init.rc script. The init scripts that specify the
864 * sockets name can be found in system/core/rootdir. The socket is bound
865 * to the file system in the /dev/sockets/ directory, and the file
866 * descriptor is shared via the ANDROID_SOCKET_<socketName> environment
867 * variable.
868 */
869 static LocalServerSocket createManagedSocketFromInitSocket(String socketName) {
870 int fileDesc;
871 final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
872
873 try {
874 String env = System.getenv(fullSocketName);
875 fileDesc = Integer.parseInt(env);
876 } catch (RuntimeException ex) {
877 throw new RuntimeException("Socket unset or invalid: " + fullSocketName, ex);
878 }
879
880 try {
881 FileDescriptor fd = new FileDescriptor();
882 fd.setInt$(fileDesc);
883 return new LocalServerSocket(fd);
884 } catch (IOException ex) {
885 throw new RuntimeException(
886 "Error building socket from file descriptor: " + fileDesc, ex);
887 }
888 }
doheon1.lee885b7422016-01-20 13:07:27 +0900889
Orion Hodson46724e72018-10-19 13:05:33 +0100890 private static void callPostForkSystemServerHooks() {
891 // SystemServer specific post fork hooks run before child post fork hooks.
Neil Fuller555d8b72019-01-28 18:29:20 +0000892 ZygoteHooks.postForkSystemServer();
Orion Hodson46724e72018-10-19 13:05:33 +0100893 }
894
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100895 private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500896 boolean isZygote, String instructionSet) {
Neil Fuller555d8b72019-01-28 18:29:20 +0000897 ZygoteHooks.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100898 }
899
Narayan Kamathb49996d2017-02-06 20:24:08 +0000900 /**
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800901 * Resets the calling thread priority to the default value (Thread.NORM_PRIORITY
902 * or nice value 0). This updates both the priority value in java.lang.Thread and
903 * the nice value (setpriority).
Narayan Kamathb49996d2017-02-06 20:24:08 +0000904 */
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800905 static void resetNicePriority() {
906 Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
907 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100908
909 /**
910 * Executes "/system/bin/sh -c &lt;command&gt;" using the exec() system call.
911 * This method throws a runtime exception if exec() failed, otherwise, this
912 * method never returns.
913 *
914 * @param command The shell command to execute.
915 */
916 public static void execShell(String command) {
917 String[] args = { "/system/bin/sh", "-c", command };
918 try {
Elliott Hughes860c5912014-04-28 19:19:13 -0700919 Os.execv(args[0], args);
Narayan Kamath973b4662014-03-31 13:41:26 +0100920 } catch (ErrnoException e) {
921 throw new RuntimeException(e);
922 }
923 }
924
925 /**
926 * Appends quotes shell arguments to the specified string builder.
927 * The arguments are quoted using single-quotes, escaped if necessary,
928 * prefixed with a space, and appended to the command.
929 *
930 * @param command A string builder for the shell command being constructed.
931 * @param args An array of argument strings to be quoted and appended to the command.
932 * @see #execShell(String)
933 */
934 public static void appendQuotedShellArgs(StringBuilder command, String[] args) {
935 for (String arg : args) {
936 command.append(" '").append(arg.replace("'", "'\\''")).append("'");
937 }
938 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100939}