blob: 382542a1b458a3a1f0ebc08dac0c70986b832200 [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 Wailes682b4792019-01-11 16:14:43 -080019import static com.android.internal.os.ZygoteConnectionConstants.MAX_ZYGOTE_ARGC;
20
21import android.net.Credentials;
22import android.os.FactoryTest;
Jeff Sharkeyace874b2017-09-07 15:27:33 -060023import android.os.IVold;
Chris Wailes682b4792019-01-11 16:14:43 -080024import android.os.Process;
25import android.os.SystemProperties;
Narayan Kamathfbb32f62015-06-12 15:34:35 +010026import android.os.Trace;
Elliott Hughes860c5912014-04-28 19:19:13 -070027import android.system.ErrnoException;
28import android.system.Os;
Chris Wailes682b4792019-01-11 16:14:43 -080029import android.util.Log;
Narayan Kamath973b4662014-03-31 13:41:26 +010030
Jeff Sharkeyace874b2017-09-07 15:27:33 -060031import dalvik.system.ZygoteHooks;
Tobias Sargeantb9679dc2016-01-19 16:34:54 +000032
Chris Wailes682b4792019-01-11 16:14:43 -080033import java.io.BufferedReader;
34import java.io.IOException;
35
Narayan Kamath973b4662014-03-31 13:41:26 +010036/** @hide */
37public final class Zygote {
38 /*
Nicolas Geoffray81edac42017-09-07 14:13:29 +010039 * Bit values for "runtimeFlags" argument. The definitions are duplicated
Narayan Kamath973b4662014-03-31 13:41:26 +010040 * in the native code.
41 */
42
43 /** enable debugging over JDWP */
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000044 public static final int DEBUG_ENABLE_JDWP = 1;
Narayan Kamath973b4662014-03-31 13:41:26 +010045 /** enable JNI checks */
46 public static final int DEBUG_ENABLE_CHECKJNI = 1 << 1;
47 /** enable Java programming language "assert" statements */
48 public static final int DEBUG_ENABLE_ASSERT = 1 << 2;
Mathieu Chartier7a490282015-03-17 09:51:36 -070049 /** disable the AOT compiler and JIT */
Narayan Kamath973b4662014-03-31 13:41:26 +010050 public static final int DEBUG_ENABLE_SAFEMODE = 1 << 3;
51 /** Enable logging of third-party JNI activity. */
52 public static final int DEBUG_ENABLE_JNI_LOGGING = 1 << 4;
David Srbecky065075e2015-05-28 17:16:09 +010053 /** Force generation of native debugging information. */
Nicolas Geoffray9abbf452015-11-05 11:29:42 +000054 public static final int DEBUG_GENERATE_DEBUG_INFO = 1 << 5;
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000055 /** Always use JIT-ed code. */
56 public static final int DEBUG_ALWAYS_JIT = 1 << 6;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000057 /** Make the code native debuggable by turning off some optimizations. */
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000058 public static final int DEBUG_NATIVE_DEBUGGABLE = 1 << 7;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000059 /** Make the code Java debuggable by turning off some optimizations. */
60 public static final int DEBUG_JAVA_DEBUGGABLE = 1 << 8;
Mathieu Chartier7a490282015-03-17 09:51:36 -070061
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010062 /** Turn off the verifier. */
63 public static final int DISABLE_VERIFIER = 1 << 9;
64 /** Only use oat files located in /system. Otherwise use dex/jar/apk . */
65 public static final int ONLY_USE_SYSTEM_OAT_FILES = 1 << 10;
David Srbecky156ed922018-01-30 14:37:37 +000066 /** Force generation of native debugging information for backtraces. */
Mathew Inwood16073b82018-03-23 10:05:01 +000067 public static final int DEBUG_GENERATE_MINI_DEBUG_INFO = 1 << 11;
68 /**
69 * Hidden API access restrictions. This is a mask for bits representing the API enforcement
70 * policy, defined by {@code @ApplicationInfo.HiddenApiEnforcementPolicy}.
71 */
72 public static final int API_ENFORCEMENT_POLICY_MASK = (1 << 12) | (1 << 13);
73 /**
74 * Bit shift for use with {@link #API_ENFORCEMENT_POLICY_MASK}.
75 *
76 * (flags & API_ENFORCEMENT_POLICY_MASK) >> API_ENFORCEMENT_POLICY_SHIFT gives
77 * @ApplicationInfo.ApiEnforcementPolicy values.
78 */
79 public static final int API_ENFORCEMENT_POLICY_SHIFT =
80 Integer.numberOfTrailingZeros(API_ENFORCEMENT_POLICY_MASK);
Calin Juravle8eb891b2018-05-03 19:51:18 -070081 /**
82 * Enable system server ART profiling.
83 */
84 public static final int PROFILE_SYSTEM_SERVER = 1 << 14;
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010085
Narayan Kamath973b4662014-03-31 13:41:26 +010086 /** No external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -060087 public static final int MOUNT_EXTERNAL_NONE = IVold.REMOUNT_MODE_NONE;
Jeff Sharkey9527b222015-06-24 15:24:48 -070088 /** Default external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -060089 public static final int MOUNT_EXTERNAL_DEFAULT = IVold.REMOUNT_MODE_DEFAULT;
Jeff Sharkey9527b222015-06-24 15:24:48 -070090 /** Read-only external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -060091 public static final int MOUNT_EXTERNAL_READ = IVold.REMOUNT_MODE_READ;
Jeff Sharkey9527b222015-06-24 15:24:48 -070092 /** Read-write external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -060093 public static final int MOUNT_EXTERNAL_WRITE = IVold.REMOUNT_MODE_WRITE;
Narayan Kamath973b4662014-03-31 13:41:26 +010094
95 private static final ZygoteHooks VM_HOOKS = new ZygoteHooks();
96
Robert Sesekd0a190df2018-02-12 18:46:01 -050097 /**
98 * An extraArg passed when a zygote process is forking a child-zygote, specifying a name
99 * in the abstract socket namespace. This socket name is what the new child zygote
100 * should listen for connections on.
101 */
102 public static final String CHILD_ZYGOTE_SOCKET_NAME_ARG = "--zygote-socket=";
103
Chris Wailes682b4792019-01-11 16:14:43 -0800104 /** a prototype instance for a future List.toArray() */
105 protected static final int[][] INT_ARRAY_2D = new int[0][0];
106
Narayan Kamath973b4662014-03-31 13:41:26 +0100107 private Zygote() {}
108
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800109 /** Called for some security initialization before any fork. */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800110 static native void nativeSecurityInit();
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800111
Narayan Kamath973b4662014-03-31 13:41:26 +0100112 /**
113 * Forks a new VM instance. The current VM must have been started
114 * with the -Xzygote flag. <b>NOTE: new instance keeps all
115 * root capabilities. The new process is expected to call capset()</b>.
116 *
117 * @param uid the UNIX uid that the new process should setuid() to after
118 * fork()ing and and before spawning any threads.
119 * @param gid the UNIX gid that the new process should setgid() to after
120 * fork()ing and and before spawning any threads.
121 * @param gids null-ok; a list of UNIX gids that the new process should
122 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100123 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100124 * @param rlimits null-ok an array of rlimit tuples, with the second
125 * dimension having a length of 3 and representing
126 * (resource, rlim_cur, rlim_max). These are set via the posix
127 * setrlimit(2) call.
128 * @param seInfo null-ok a string specifying SELinux information for
129 * the new process.
130 * @param niceName null-ok a string specifying the process name.
131 * @param fdsToClose an array of ints, holding one or more POSIX
132 * file descriptor numbers that are to be closed by the child
133 * (and replaced by /dev/null) after forking. An integer value
134 * of -1 in any entry in the array means "ignore this one".
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800135 * @param fdsToIgnore null-ok an array of ints, either null or holding
136 * one or more POSIX file descriptor numbers that are to be ignored
137 * in the file descriptor table check.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500138 * @param startChildZygote if true, the new child process will itself be a
139 * new zygote process.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700140 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400141 * @param appDataDir null-ok the data directory of the app.
Narayan Kamath973b4662014-03-31 13:41:26 +0100142 *
143 * @return 0 if this is the child, pid of the child
144 * if this is the parent, or -1 on error.
145 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100146 public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
Chris Wailes8b35ba22019-01-10 16:55:32 -0800147 int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
148 int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100149 VM_HOOKS.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800150 // Resets nice priority for zygote process.
151 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100152 int pid = nativeForkAndSpecialize(
Chris Wailes8b35ba22019-01-10 16:55:32 -0800153 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
154 fdsToIgnore, startChildZygote, instructionSet, appDataDir);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100155 // Enable tracing as soon as possible for the child process.
156 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700157 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100158
159 // Note that this event ends at the end of handleChildProc,
160 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
161 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100162 VM_HOOKS.postForkCommon();
163 return pid;
164 }
165
Chris Wailes8b35ba22019-01-10 16:55:32 -0800166 private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
167 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
168 int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
169 String appDataDir);
170
171 private static native void nativeSpecializeBlastula(int uid, int gid, int[] gids,
172 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
173 boolean startChildZygote, String instructionSet, String appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100174
175 /**
Christopher Ferris2980de42017-06-20 16:13:40 -0700176 * Called to do any initialization before starting an application.
177 */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800178 static native void nativePreApplicationInit();
Christopher Ferris2980de42017-06-20 16:13:40 -0700179
180 /**
Narayan Kamath973b4662014-03-31 13:41:26 +0100181 * Special method to start the system server process. In addition to the
182 * common actions performed in forkAndSpecialize, the pid of the child
183 * process is recorded such that the death of the child process will cause
184 * zygote to exit.
185 *
186 * @param uid the UNIX uid that the new process should setuid() to after
187 * fork()ing and and before spawning any threads.
188 * @param gid the UNIX gid that the new process should setgid() to after
189 * fork()ing and and before spawning any threads.
190 * @param gids null-ok; a list of UNIX gids that the new process should
191 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100192 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100193 * @param rlimits null-ok an array of rlimit tuples, with the second
194 * dimension having a length of 3 and representing
195 * (resource, rlim_cur, rlim_max). These are set via the posix
196 * setrlimit(2) call.
197 * @param permittedCapabilities argument for setcap()
198 * @param effectiveCapabilities argument for setcap()
199 *
200 * @return 0 if this is the child, pid of the child
201 * if this is the parent, or -1 on error.
202 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100203 public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100204 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
205 VM_HOOKS.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800206 // Resets nice priority for zygote process.
207 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100208 int pid = nativeForkSystemServer(
Chris Wailes8b35ba22019-01-10 16:55:32 -0800209 uid, gid, gids, runtimeFlags, rlimits,
210 permittedCapabilities, effectiveCapabilities);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100211 // Enable tracing as soon as we enter the system_server.
212 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700213 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100214 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100215 VM_HOOKS.postForkCommon();
216 return pid;
217 }
218
Chris Wailes8b35ba22019-01-10 16:55:32 -0800219 private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100220 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
221
doheon1.lee885b7422016-01-20 13:07:27 +0900222 /**
Robert Sesek54e387d2016-12-02 17:27:50 -0500223 * Lets children of the zygote inherit open file descriptors to this path.
224 */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800225 protected static native void nativeAllowFileAcrossFork(String path);
Robert Sesek54e387d2016-12-02 17:27:50 -0500226
227 /**
doheon1.lee885b7422016-01-20 13:07:27 +0900228 * Zygote unmount storage space on initializing.
229 * This method is called once.
230 */
Chris Wailes8b35ba22019-01-10 16:55:32 -0800231 protected static native void nativeUnmountStorageOnInit();
232
233 protected static native void nativeGetSocketFDs(boolean isPrimary);
234
235 private static native int nativeGetBlastulaPoolCount();
236
237 private static native int nativeGetBlastulaPoolEventFD();
238
239 private static native int nativeForkBlastula(int readPipeFD,
240 int writePipeFD,
241 int[] sessionSocketRawFDs);
242
243 private static native int[] nativeGetBlastulaPipeFDs();
244
245 private static native boolean nativeRemoveBlastulaTableEntry(int blastulaPID);
246
Chris Wailes682b4792019-01-11 16:14:43 -0800247 /**
248 * uid 1000 (Process.SYSTEM_UID) may specify any uid &gt; 1000 in normal
249 * operation. It may also specify any gid and setgroups() list it chooses.
250 * In factory test mode, it may specify any UID.
251 *
252 * @param args non-null; zygote spawner arguments
253 * @param peer non-null; peer credentials
254 * @throws ZygoteSecurityException
255 */
256 protected static void applyUidSecurityPolicy(ZygoteArguments args, Credentials peer)
257 throws ZygoteSecurityException {
258
259 if (peer.getUid() == Process.SYSTEM_UID) {
260 /* In normal operation, SYSTEM_UID can only specify a restricted
261 * set of UIDs. In factory test mode, SYSTEM_UID may specify any uid.
262 */
263 boolean uidRestricted = FactoryTest.getMode() == FactoryTest.FACTORY_TEST_OFF;
264
265 if (uidRestricted && args.mUidSpecified && (args.mUid < Process.SYSTEM_UID)) {
266 throw new ZygoteSecurityException(
267 "System UID may not launch process with UID < "
268 + Process.SYSTEM_UID);
269 }
270 }
271
272 // If not otherwise specified, uid and gid are inherited from peer
273 if (!args.mUidSpecified) {
274 args.mUid = peer.getUid();
275 args.mUidSpecified = true;
276 }
277 if (!args.mGidSpecified) {
278 args.mGid = peer.getGid();
279 args.mGidSpecified = true;
280 }
281 }
282
283 /**
284 * Applies debugger system properties to the zygote arguments.
285 *
286 * If "ro.debuggable" is "1", all apps are debuggable. Otherwise,
287 * the debugger state is specified via the "--enable-jdwp" flag
288 * in the spawn request.
289 *
290 * @param args non-null; zygote spawner args
291 */
292 protected static void applyDebuggerSystemProperty(ZygoteArguments args) {
293 if (RoSystemProperties.DEBUGGABLE) {
294 args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
295 }
296 }
297
298 /**
299 * Applies zygote security policy.
300 * Based on the credentials of the process issuing a zygote command:
301 * <ol>
302 * <li> uid 0 (root) may specify --invoke-with to launch Zygote with a
303 * wrapper command.
304 * <li> Any other uid may not specify any invoke-with argument.
305 * </ul>
306 *
307 * @param args non-null; zygote spawner arguments
308 * @param peer non-null; peer credentials
309 * @throws ZygoteSecurityException
310 */
311 protected static void applyInvokeWithSecurityPolicy(ZygoteArguments args, Credentials peer)
312 throws ZygoteSecurityException {
313 int peerUid = peer.getUid();
314
315 if (args.mInvokeWith != null && peerUid != 0
316 && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
317 throw new ZygoteSecurityException("Peer is permitted to specify an"
318 + "explicit invoke-with wrapper command only for debuggable"
319 + "applications.");
320 }
321 }
322
323 /**
324 * Applies invoke-with system properties to the zygote arguments.
325 *
326 * @param args non-null; zygote args
327 */
328 protected static void applyInvokeWithSystemProperty(ZygoteArguments args) {
329 if (args.mInvokeWith == null && args.mNiceName != null) {
330 String property = "wrap." + args.mNiceName;
331 args.mInvokeWith = SystemProperties.get(property);
332 if (args.mInvokeWith != null && args.mInvokeWith.length() == 0) {
333 args.mInvokeWith = null;
334 }
335 }
336 }
337
338 /**
339 * Reads an argument list from the provided socket
340 * @return Argument list or null if EOF is reached
341 * @throws IOException passed straight through
342 */
343 static String[] readArgumentList(BufferedReader socketReader) throws IOException {
344
345 /**
346 * See android.os.Process.zygoteSendArgsAndGetPid()
347 * Presently the wire format to the zygote process is:
348 * a) a count of arguments (argc, in essence)
349 * b) a number of newline-separated argument strings equal to count
350 *
351 * After the zygote process reads these it will write the pid of
352 * the child or -1 on failure.
353 */
354
355 int argc;
356
357 try {
358 String argc_string = socketReader.readLine();
359
360 if (argc_string == null) {
361 // EOF reached.
362 return null;
363 }
364 argc = Integer.parseInt(argc_string);
365
366 } catch (NumberFormatException ex) {
367 Log.e("Zygote", "Invalid Zygote wire format: non-int at argc");
368 throw new IOException("Invalid wire format");
369 }
370
371 // See bug 1092107: large argc can be used for a DOS attack
372 if (argc > MAX_ZYGOTE_ARGC) {
373 throw new IOException("Max arg count exceeded");
374 }
375
376 String[] args = new String[argc];
377 for (int arg_index = 0; arg_index < argc; arg_index++) {
378 args[arg_index] = socketReader.readLine();
379 if (args[arg_index] == null) {
380 // We got an unexpected EOF.
381 throw new IOException("Truncated request");
382 }
383 }
384
385 return args;
386 }
387
doheon1.lee885b7422016-01-20 13:07:27 +0900388
Orion Hodson46724e72018-10-19 13:05:33 +0100389 private static void callPostForkSystemServerHooks() {
390 // SystemServer specific post fork hooks run before child post fork hooks.
391 VM_HOOKS.postForkSystemServer();
392 }
393
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100394 private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500395 boolean isZygote, String instructionSet) {
396 VM_HOOKS.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100397 }
398
Narayan Kamathb49996d2017-02-06 20:24:08 +0000399 /**
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800400 * Resets the calling thread priority to the default value (Thread.NORM_PRIORITY
401 * or nice value 0). This updates both the priority value in java.lang.Thread and
402 * the nice value (setpriority).
Narayan Kamathb49996d2017-02-06 20:24:08 +0000403 */
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800404 static void resetNicePriority() {
405 Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
406 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100407
408 /**
409 * Executes "/system/bin/sh -c &lt;command&gt;" using the exec() system call.
410 * This method throws a runtime exception if exec() failed, otherwise, this
411 * method never returns.
412 *
413 * @param command The shell command to execute.
414 */
415 public static void execShell(String command) {
416 String[] args = { "/system/bin/sh", "-c", command };
417 try {
Elliott Hughes860c5912014-04-28 19:19:13 -0700418 Os.execv(args[0], args);
Narayan Kamath973b4662014-03-31 13:41:26 +0100419 } catch (ErrnoException e) {
420 throw new RuntimeException(e);
421 }
422 }
423
424 /**
425 * Appends quotes shell arguments to the specified string builder.
426 * The arguments are quoted using single-quotes, escaped if necessary,
427 * prefixed with a space, and appended to the command.
428 *
429 * @param command A string builder for the shell command being constructed.
430 * @param args An array of argument strings to be quoted and appended to the command.
431 * @see #execShell(String)
432 */
433 public static void appendQuotedShellArgs(StringBuilder command, String[] args) {
434 for (String arg : args) {
435 command.append(" '").append(arg.replace("'", "'\\''")).append("'");
436 }
437 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100438}