blob: 0e21fab08608589513f5eee5268c1641a417f541 [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;
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -070027import android.os.Build;
Chris Wailes2be26262019-01-11 16:14:43 -080028import android.os.FactoryTest;
Jeff Sharkeyace874b2017-09-07 15:27:33 -060029import android.os.IVold;
Chris Wailes2be26262019-01-11 16:14:43 -080030import android.os.Process;
31import android.os.SystemProperties;
Narayan Kamathfbb32f62015-06-12 15:34:35 +010032import android.os.Trace;
Mathieu Chartier0bccbf72019-01-30 15:56:17 -080033import android.provider.DeviceConfig;
Elliott Hughes860c5912014-04-28 19:19:13 -070034import android.system.ErrnoException;
35import android.system.Os;
Chris Wailes2be26262019-01-11 16:14:43 -080036import android.util.Log;
Narayan Kamath973b4662014-03-31 13:41:26 +010037
Jeff Sharkeyace874b2017-09-07 15:27:33 -060038import dalvik.system.ZygoteHooks;
Tobias Sargeantb9679dc2016-01-19 16:34:54 +000039
Chris Wailescb0b37f2019-01-11 17:04:41 -080040import libcore.io.IoUtils;
41
Chris Wailes2be26262019-01-11 16:14:43 -080042import java.io.BufferedReader;
Chris Wailescb0b37f2019-01-11 17:04:41 -080043import java.io.ByteArrayOutputStream;
44import java.io.DataOutputStream;
45import java.io.FileDescriptor;
Chris Wailes2be26262019-01-11 16:14:43 -080046import java.io.IOException;
Chris Wailescb0b37f2019-01-11 17:04:41 -080047import java.io.InputStreamReader;
Chris Wailes2be26262019-01-11 16:14:43 -080048
Narayan Kamath973b4662014-03-31 13:41:26 +010049/** @hide */
50public final class Zygote {
51 /*
Nicolas Geoffray81edac42017-09-07 14:13:29 +010052 * Bit values for "runtimeFlags" argument. The definitions are duplicated
Narayan Kamath973b4662014-03-31 13:41:26 +010053 * in the native code.
54 */
55
56 /** enable debugging over JDWP */
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000057 public static final int DEBUG_ENABLE_JDWP = 1;
Narayan Kamath973b4662014-03-31 13:41:26 +010058 /** enable JNI checks */
59 public static final int DEBUG_ENABLE_CHECKJNI = 1 << 1;
60 /** enable Java programming language "assert" statements */
61 public static final int DEBUG_ENABLE_ASSERT = 1 << 2;
Mathieu Chartier7a490282015-03-17 09:51:36 -070062 /** disable the AOT compiler and JIT */
Narayan Kamath973b4662014-03-31 13:41:26 +010063 public static final int DEBUG_ENABLE_SAFEMODE = 1 << 3;
64 /** Enable logging of third-party JNI activity. */
65 public static final int DEBUG_ENABLE_JNI_LOGGING = 1 << 4;
David Srbecky065075e2015-05-28 17:16:09 +010066 /** Force generation of native debugging information. */
Nicolas Geoffray9abbf452015-11-05 11:29:42 +000067 public static final int DEBUG_GENERATE_DEBUG_INFO = 1 << 5;
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000068 /** Always use JIT-ed code. */
69 public static final int DEBUG_ALWAYS_JIT = 1 << 6;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000070 /** Make the code native debuggable by turning off some optimizations. */
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000071 public static final int DEBUG_NATIVE_DEBUGGABLE = 1 << 7;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000072 /** Make the code Java debuggable by turning off some optimizations. */
73 public static final int DEBUG_JAVA_DEBUGGABLE = 1 << 8;
Mathieu Chartier7a490282015-03-17 09:51:36 -070074
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010075 /** Turn off the verifier. */
76 public static final int DISABLE_VERIFIER = 1 << 9;
77 /** Only use oat files located in /system. Otherwise use dex/jar/apk . */
78 public static final int ONLY_USE_SYSTEM_OAT_FILES = 1 << 10;
David Srbecky156ed922018-01-30 14:37:37 +000079 /** Force generation of native debugging information for backtraces. */
Mathew Inwood16073b82018-03-23 10:05:01 +000080 public static final int DEBUG_GENERATE_MINI_DEBUG_INFO = 1 << 11;
81 /**
82 * Hidden API access restrictions. This is a mask for bits representing the API enforcement
83 * policy, defined by {@code @ApplicationInfo.HiddenApiEnforcementPolicy}.
84 */
85 public static final int API_ENFORCEMENT_POLICY_MASK = (1 << 12) | (1 << 13);
86 /**
87 * Bit shift for use with {@link #API_ENFORCEMENT_POLICY_MASK}.
88 *
89 * (flags & API_ENFORCEMENT_POLICY_MASK) >> API_ENFORCEMENT_POLICY_SHIFT gives
90 * @ApplicationInfo.ApiEnforcementPolicy values.
91 */
92 public static final int API_ENFORCEMENT_POLICY_SHIFT =
93 Integer.numberOfTrailingZeros(API_ENFORCEMENT_POLICY_MASK);
Calin Juravle8eb891b2018-05-03 19:51:18 -070094 /**
95 * Enable system server ART profiling.
96 */
97 public static final int PROFILE_SYSTEM_SERVER = 1 << 14;
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010098
Yabin Cui4d8546d2019-01-29 16:29:20 -080099 /**
100 * Enable profiling from shell.
101 */
102 public static final int PROFILE_FROM_SHELL = 1 << 15;
103
Mathieu Chartierced7e082019-02-04 13:28:36 -0800104 /*
105 * Enable using the ART app image startup cache
106 */
107 public static final int USE_APP_IMAGE_STARTUP_CACHE = 1 << 16;
108
Narayan Kamath973b4662014-03-31 13:41:26 +0100109 /** No external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600110 public static final int MOUNT_EXTERNAL_NONE = IVold.REMOUNT_MODE_NONE;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700111 /** Default external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600112 public static final int MOUNT_EXTERNAL_DEFAULT = IVold.REMOUNT_MODE_DEFAULT;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700113 /** Read-only external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600114 public static final int MOUNT_EXTERNAL_READ = IVold.REMOUNT_MODE_READ;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700115 /** Read-write external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600116 public static final int MOUNT_EXTERNAL_WRITE = IVold.REMOUNT_MODE_WRITE;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800117 /**
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800118 * Mount mode for apps that are already installed on the device before the isolated_storage
119 * feature is enabled.
120 */
121 public static final int MOUNT_EXTERNAL_LEGACY = IVold.REMOUNT_MODE_LEGACY;
122 /**
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800123 * Mount mode for package installers which should give them access to
124 * all obb dirs in addition to their package sandboxes
125 */
126 public static final int MOUNT_EXTERNAL_INSTALLER = IVold.REMOUNT_MODE_INSTALLER;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700127 /** Read-write external storage should be mounted instead of package sandbox */
128 public static final int MOUNT_EXTERNAL_FULL = IVold.REMOUNT_MODE_FULL;
Narayan Kamath973b4662014-03-31 13:41:26 +0100129
Chris Wailes7e797b62019-02-22 18:29:22 -0800130 /** Number of bytes sent to the Zygote over USAP pipes or the pool event FD */
131 public static final int USAP_MANAGEMENT_MESSAGE_BYTES = 8;
Chris Wailescb0b37f2019-01-11 17:04:41 -0800132
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800133 /**
Robert Sesekd0a190df2018-02-12 18:46:01 -0500134 * An extraArg passed when a zygote process is forking a child-zygote, specifying a name
135 * in the abstract socket namespace. This socket name is what the new child zygote
136 * should listen for connections on.
137 */
138 public static final String CHILD_ZYGOTE_SOCKET_NAME_ARG = "--zygote-socket=";
139
Martijn Coenen7e6fa672018-11-05 11:45:26 +0100140 /**
141 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
142 * requested ABI for the child Zygote.
143 */
144 public static final String CHILD_ZYGOTE_ABI_LIST_ARG = "--abi-list=";
145
Martijn Coenen86f08a52019-01-03 16:23:01 +0100146 /**
147 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
148 * start of the UID range the children of the Zygote may setuid()/setgid() to. This
149 * will be enforced with a seccomp filter.
150 */
151 public static final String CHILD_ZYGOTE_UID_RANGE_START = "--uid-range-start=";
152
153 /**
154 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
155 * end of the UID range the children of the Zygote may setuid()/setgid() to. This
156 * will be enforced with a seccomp filter.
157 */
158 public static final String CHILD_ZYGOTE_UID_RANGE_END = "--uid-range-end=";
159
Chris Wailescb0b37f2019-01-11 17:04:41 -0800160 /** Prefix prepended to socket names created by init */
161 private static final String ANDROID_SOCKET_PREFIX = "ANDROID_SOCKET_";
162
163 /**
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800164 * The duration to wait before re-checking Zygote related system properties.
165 *
Chris Wailesdb132a32019-02-20 10:49:27 -0800166 * One minute in milliseconds.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800167 */
Chris Wailesdb132a32019-02-20 10:49:27 -0800168 public static final long PROPERTY_CHECK_INTERVAL = 60000;
Chris Wailescb0b37f2019-01-11 17:04:41 -0800169
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800170 /**
171 * @hide for internal use only
172 */
173 public static final int SOCKET_BUFFER_SIZE = 256;
174
Chris Wailes2be26262019-01-11 16:14:43 -0800175 /** a prototype instance for a future List.toArray() */
176 protected static final int[][] INT_ARRAY_2D = new int[0][0];
177
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800178 /**
179 * @hide for internal use only.
180 */
181 public static final String PRIMARY_SOCKET_NAME = "zygote";
182
183 /**
184 * @hide for internal use only.
185 */
186 public static final String SECONDARY_SOCKET_NAME = "zygote_secondary";
187
188 /**
189 * @hide for internal use only
190 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800191 public static final String USAP_POOL_PRIMARY_SOCKET_NAME = "usap_pool_primary";
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800192
193 /**
194 * @hide for internal use only
195 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800196 public static final String USAP_POOL_SECONDARY_SOCKET_NAME = "usap_pool_secondary";
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800197
Narayan Kamath973b4662014-03-31 13:41:26 +0100198 private Zygote() {}
199
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800200 /** Called for some security initialization before any fork. */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800201 static native void nativeSecurityInit();
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800202
Narayan Kamath973b4662014-03-31 13:41:26 +0100203 /**
204 * Forks a new VM instance. The current VM must have been started
205 * with the -Xzygote flag. <b>NOTE: new instance keeps all
206 * root capabilities. The new process is expected to call capset()</b>.
207 *
208 * @param uid the UNIX uid that the new process should setuid() to after
209 * fork()ing and and before spawning any threads.
210 * @param gid the UNIX gid that the new process should setgid() to after
211 * fork()ing and and before spawning any threads.
212 * @param gids null-ok; a list of UNIX gids that the new process should
213 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100214 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100215 * @param rlimits null-ok an array of rlimit tuples, with the second
216 * dimension having a length of 3 and representing
217 * (resource, rlim_cur, rlim_max). These are set via the posix
218 * setrlimit(2) call.
219 * @param seInfo null-ok a string specifying SELinux information for
220 * the new process.
221 * @param niceName null-ok a string specifying the process name.
222 * @param fdsToClose an array of ints, holding one or more POSIX
223 * file descriptor numbers that are to be closed by the child
224 * (and replaced by /dev/null) after forking. An integer value
225 * of -1 in any entry in the array means "ignore this one".
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800226 * @param fdsToIgnore null-ok an array of ints, either null or holding
227 * one or more POSIX file descriptor numbers that are to be ignored
228 * in the file descriptor table check.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500229 * @param startChildZygote if true, the new child process will itself be a
230 * new zygote process.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700231 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400232 * @param appDataDir null-ok the data directory of the app.
Narayan Kamath973b4662014-03-31 13:41:26 +0100233 *
234 * @return 0 if this is the child, pid of the child
235 * if this is the parent, or -1 on error.
236 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100237 public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700238 int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
239 int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -0700240 String packageName, String[] packagesForUID, String sandboxId, int targetSdkVersion) {
Neil Fuller555d8b72019-01-28 18:29:20 +0000241 ZygoteHooks.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800242 // Resets nice priority for zygote process.
243 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100244 int pid = nativeForkAndSpecialize(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800245 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
246 fdsToIgnore, startChildZygote, instructionSet, appDataDir, packageName,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800247 packagesForUID, sandboxId);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100248 // Enable tracing as soon as possible for the child process.
249 if (pid == 0) {
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -0700250 Zygote.disableExecuteOnly(targetSdkVersion);
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700251 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100252
253 // Note that this event ends at the end of handleChildProc,
254 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
255 }
Neil Fuller555d8b72019-01-28 18:29:20 +0000256 ZygoteHooks.postForkCommon();
Narayan Kamath973b4662014-03-31 13:41:26 +0100257 return pid;
258 }
259
Chris Wailesaa1c9622019-01-10 16:55:32 -0800260 private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
261 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
262 int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800263 String appDataDir, String packageName, String[] packagesForUID,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800264 String sandboxId);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800265
Chris Wailescb0b37f2019-01-11 17:04:41 -0800266 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800267 * Specialize an unspecialized app process. The current VM must have been started
Chris Wailescb0b37f2019-01-11 17:04:41 -0800268 * with the -Xzygote flag.
269 *
270 * @param uid The UNIX uid that the new process should setuid() to before spawning any threads
271 * @param gid The UNIX gid that the new process should setgid() to before spawning any threads
272 * @param gids null-ok; A list of UNIX gids that the new process should
273 * setgroups() to before spawning any threads
274 * @param runtimeFlags Bit flags that enable ART features
275 * @param rlimits null-ok An array of rlimit tuples, with the second
276 * dimension having a length of 3 and representing
277 * (resource, rlim_cur, rlim_max). These are set via the posix
278 * setrlimit(2) call.
279 * @param seInfo null-ok A string specifying SELinux information for
280 * the new process.
281 * @param niceName null-ok A string specifying the process name.
282 * @param startChildZygote If true, the new child process will itself be a
283 * new zygote process.
284 * @param instructionSet null-ok The instruction set to use.
285 * @param appDataDir null-ok The data directory of the app.
286 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800287 public static void specializeAppProcess(int uid, int gid, int[] gids, int runtimeFlags,
Chris Wailescb0b37f2019-01-11 17:04:41 -0800288 int[][] rlimits, int mountExternal, String seInfo, String niceName,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800289 boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800290 String[] packagesForUID, String sandboxId) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800291 nativeSpecializeAppProcess(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
Chris Wailescb0b37f2019-01-11 17:04:41 -0800292 niceName, startChildZygote, instructionSet, appDataDir,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800293 packageName, packagesForUID, sandboxId);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800294
295 // Enable tracing as soon as possible for the child process.
296 Trace.setTracingEnabled(true, runtimeFlags);
297
298 // Note that this event ends at the end of handleChildProc.
299 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
300
301 /*
302 * This is called here (instead of after the fork but before the specialize) to maintain
303 * consistancy with the code paths for forkAndSpecialize.
304 *
305 * TODO (chriswailes): Look into moving this to immediately after the fork.
306 */
Neil Fuller555d8b72019-01-28 18:29:20 +0000307 ZygoteHooks.postForkCommon();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800308 }
309
Chris Wailes7e797b62019-02-22 18:29:22 -0800310 private static native void nativeSpecializeAppProcess(int uid, int gid, int[] gids,
Chris Wailesaa1c9622019-01-10 16:55:32 -0800311 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
312 boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800313 String[] packagesForUID, String sandboxId);
Narayan Kamath973b4662014-03-31 13:41:26 +0100314
315 /**
Christopher Ferris2980de42017-06-20 16:13:40 -0700316 * Called to do any initialization before starting an application.
317 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800318 static native void nativePreApplicationInit();
Christopher Ferris2980de42017-06-20 16:13:40 -0700319
320 /**
Narayan Kamath973b4662014-03-31 13:41:26 +0100321 * Special method to start the system server process. In addition to the
322 * common actions performed in forkAndSpecialize, the pid of the child
323 * process is recorded such that the death of the child process will cause
324 * zygote to exit.
325 *
326 * @param uid the UNIX uid that the new process should setuid() to after
327 * fork()ing and and before spawning any threads.
328 * @param gid the UNIX gid that the new process should setgid() to after
329 * fork()ing and and before spawning any threads.
330 * @param gids null-ok; a list of UNIX gids that the new process should
331 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100332 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100333 * @param rlimits null-ok an array of rlimit tuples, with the second
334 * dimension having a length of 3 and representing
335 * (resource, rlim_cur, rlim_max). These are set via the posix
336 * setrlimit(2) call.
337 * @param permittedCapabilities argument for setcap()
338 * @param effectiveCapabilities argument for setcap()
339 *
340 * @return 0 if this is the child, pid of the child
341 * if this is the parent, or -1 on error.
342 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100343 public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100344 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
Neil Fuller555d8b72019-01-28 18:29:20 +0000345 ZygoteHooks.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800346 // Resets nice priority for zygote process.
347 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100348 int pid = nativeForkSystemServer(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800349 uid, gid, gids, runtimeFlags, rlimits,
350 permittedCapabilities, effectiveCapabilities);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100351 // Enable tracing as soon as we enter the system_server.
352 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700353 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100354 }
Neil Fuller555d8b72019-01-28 18:29:20 +0000355 ZygoteHooks.postForkCommon();
Narayan Kamath973b4662014-03-31 13:41:26 +0100356 return pid;
357 }
358
Chris Wailesaa1c9622019-01-10 16:55:32 -0800359 private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100360 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
361
doheon1.lee885b7422016-01-20 13:07:27 +0900362 /**
Robert Sesek54e387d2016-12-02 17:27:50 -0500363 * Lets children of the zygote inherit open file descriptors to this path.
364 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800365 protected static native void nativeAllowFileAcrossFork(String path);
Robert Sesek54e387d2016-12-02 17:27:50 -0500366
367 /**
Martijn Coenen4b988162019-01-28 13:58:45 +0100368 * Lets children of the zygote inherit open file descriptors that belong to the
369 * ApplicationInfo that is passed in.
370 *
371 * @param appInfo ApplicationInfo of the application
372 */
373 protected static void allowAppFilesAcrossFork(ApplicationInfo appInfo) {
Torne (Richard Coles)1aaae102019-03-01 15:02:29 -0500374 for (String path : appInfo.getAllApkPaths()) {
375 Zygote.nativeAllowFileAcrossFork(path);
Martijn Coenen4b988162019-01-28 13:58:45 +0100376 }
377 }
378
379 /**
Martijn Coenen86f08a52019-01-03 16:23:01 +0100380 * Installs a seccomp filter that limits setresuid()/setresgid() to the passed-in range
381 * @param uidGidMin The smallest allowed uid/gid
382 * @param uidGidMax The largest allowed uid/gid
383 */
384 native protected static void nativeInstallSeccompUidGidFilter(int uidGidMin, int uidGidMax);
385
386 /**
doheon1.lee885b7422016-01-20 13:07:27 +0900387 * Zygote unmount storage space on initializing.
388 * This method is called once.
389 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800390 protected static native void nativeUnmountStorageOnInit();
391
Chris Wailescb0b37f2019-01-11 17:04:41 -0800392 /**
393 * Get socket file descriptors (opened by init) from the environment and
394 * store them for access from native code later.
395 *
396 * @param isPrimary True if this is the zygote process, false if it is zygote_secondary
397 */
398 public static void getSocketFDs(boolean isPrimary) {
399 nativeGetSocketFDs(isPrimary);
400 }
401
Chris Wailesaa1c9622019-01-10 16:55:32 -0800402 protected static native void nativeGetSocketFDs(boolean isPrimary);
403
Chris Wailescb0b37f2019-01-11 17:04:41 -0800404 /**
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800405 * Returns the raw string value of a system property.
406 *
407 * Note that Device Config is not available without an application so SystemProperties is used
408 * instead.
409 *
410 * TODO (chriswailes): Cache the system property location in native code and then write a JNI
411 * function to fetch it.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800412 */
Chris Wailesfe3a3482019-03-13 14:38:04 -0700413 public static String getConfigurationProperty(String propertyName, String defaultValue) {
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800414 return SystemProperties.get(
415 String.join(".",
416 "persist.device_config",
Matt Papee9b680a2019-03-05 15:53:13 -0800417 DeviceConfig.NAMESPACE_RUNTIME_NATIVE,
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800418 propertyName),
419 defaultValue);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800420 }
421
Chris Wailes7e797b62019-02-22 18:29:22 -0800422 protected static void emptyUsapPool() {
423 nativeEmptyUsapPool();
Chris Wailesae937142019-01-24 12:57:33 -0800424 }
425
Chris Wailes7e797b62019-02-22 18:29:22 -0800426 private static native void nativeEmptyUsapPool();
Chris Wailesae937142019-01-24 12:57:33 -0800427
Chris Wailescb0b37f2019-01-11 17:04:41 -0800428 /**
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800429 * Returns the value of a system property converted to a boolean using specific logic.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800430 *
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800431 * Note that Device Config is not available without an application so SystemProperties is used
432 * instead.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800433 *
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800434 * @see SystemProperties.getBoolean
435 *
436 * TODO (chriswailes): Cache the system property location in native code and then write a JNI
437 * function to fetch it.
Chris Wailesfe3a3482019-03-13 14:38:04 -0700438 * TODO (chriswailes): Move into ZygoteConfig.java once the necessary CL lands (go/ag/6580627)
Chris Wailescb0b37f2019-01-11 17:04:41 -0800439 */
Chris Wailesfe3a3482019-03-13 14:38:04 -0700440 public static boolean getConfigurationPropertyBoolean(
441 String propertyName, Boolean defaultValue) {
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800442 return SystemProperties.getBoolean(
443 String.join(".",
444 "persist.device_config",
Matt Papee9b680a2019-03-05 15:53:13 -0800445 DeviceConfig.NAMESPACE_RUNTIME_NATIVE,
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800446 propertyName),
447 defaultValue);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800448 }
449
450 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800451 * @return Number of unspecialized app processes currently in the pool
Chris Wailescb0b37f2019-01-11 17:04:41 -0800452 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800453 static int getUsapPoolCount() {
454 return nativeGetUsapPoolCount();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800455 }
456
Chris Wailes7e797b62019-02-22 18:29:22 -0800457 private static native int nativeGetUsapPoolCount();
Chris Wailesaa1c9622019-01-10 16:55:32 -0800458
Chris Wailescb0b37f2019-01-11 17:04:41 -0800459 /**
460 * @return The event FD used for communication between the signal handler and the ZygoteServer
461 * poll loop
462 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800463 static FileDescriptor getUsapPoolEventFD() {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800464 FileDescriptor fd = new FileDescriptor();
Chris Wailes7e797b62019-02-22 18:29:22 -0800465 fd.setInt$(nativeGetUsapPoolEventFD());
Chris Wailescb0b37f2019-01-11 17:04:41 -0800466
467 return fd;
468 }
469
Chris Wailes7e797b62019-02-22 18:29:22 -0800470 private static native int nativeGetUsapPoolEventFD();
Chris Wailesaa1c9622019-01-10 16:55:32 -0800471
Chris Wailescb0b37f2019-01-11 17:04:41 -0800472 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800473 * Fork a new unspecialized app process from the zygote
Chris Wailescb0b37f2019-01-11 17:04:41 -0800474 *
475 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
Chris Wailes7e797b62019-02-22 18:29:22 -0800476 * @return In the Zygote process this function will always return null; in unspecialized app
477 * processes this function will return a Runnable object representing the new
478 * application that is passed up from usapMain.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800479 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800480 static Runnable forkUsap(LocalServerSocket usapPoolSocket,
481 int[] sessionSocketRawFDs) {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800482 FileDescriptor[] pipeFDs = null;
483
484 try {
485 pipeFDs = Os.pipe2(O_CLOEXEC);
486 } catch (ErrnoException errnoEx) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800487 throw new IllegalStateException("Unable to create USAP pipe.", errnoEx);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800488 }
489
490 int pid =
Chris Wailes7e797b62019-02-22 18:29:22 -0800491 nativeForkUsap(pipeFDs[0].getInt$(), pipeFDs[1].getInt$(), sessionSocketRawFDs);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800492
493 if (pid == 0) {
494 IoUtils.closeQuietly(pipeFDs[0]);
Chris Wailes7e797b62019-02-22 18:29:22 -0800495 return usapMain(usapPoolSocket, pipeFDs[1]);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800496 } else {
497 // The read-end of the pipe will be closed by the native code.
Chris Wailes7e797b62019-02-22 18:29:22 -0800498 // See removeUsapTableEntry();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800499 IoUtils.closeQuietly(pipeFDs[1]);
500 return null;
501 }
502 }
503
Chris Wailes7e797b62019-02-22 18:29:22 -0800504 private static native int nativeForkUsap(int readPipeFD,
Chris Wailesaa1c9622019-01-10 16:55:32 -0800505 int writePipeFD,
506 int[] sessionSocketRawFDs);
507
Chris Wailescb0b37f2019-01-11 17:04:41 -0800508 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800509 * This function is used by unspecialized app processes to wait for specialization requests from
510 * the system server.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800511 *
512 * @param writePipe The write end of the reporting pipe used to communicate with the poll loop
513 * of the ZygoteServer.
514 * @return A runnable oject representing the new application.
515 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800516 private static Runnable usapMain(LocalServerSocket usapPoolSocket,
517 FileDescriptor writePipe) {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800518 final int pid = Process.myPid();
519
520 LocalSocket sessionSocket = null;
Chris Wailes7e797b62019-02-22 18:29:22 -0800521 DataOutputStream usapOutputStream = null;
Chris Wailescb0b37f2019-01-11 17:04:41 -0800522 Credentials peerCredentials = null;
Chris Wailesae937142019-01-24 12:57:33 -0800523 ZygoteArguments args = null;
Chris Wailescb0b37f2019-01-11 17:04:41 -0800524
525 while (true) {
526 try {
Chris Wailes7e797b62019-02-22 18:29:22 -0800527 sessionSocket = usapPoolSocket.accept();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800528
Chris Wailes7e797b62019-02-22 18:29:22 -0800529 BufferedReader usapReader =
Chris Wailescb0b37f2019-01-11 17:04:41 -0800530 new BufferedReader(new InputStreamReader(sessionSocket.getInputStream()));
Chris Wailes7e797b62019-02-22 18:29:22 -0800531 usapOutputStream =
Chris Wailescb0b37f2019-01-11 17:04:41 -0800532 new DataOutputStream(sessionSocket.getOutputStream());
533
534 peerCredentials = sessionSocket.getPeerCredentials();
535
Chris Wailes7e797b62019-02-22 18:29:22 -0800536 String[] argStrings = readArgumentList(usapReader);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800537
538 if (argStrings != null) {
Chris Wailesae937142019-01-24 12:57:33 -0800539 args = new ZygoteArguments(argStrings);
540
541 // TODO (chriswailes): Should this only be run for debug builds?
Chris Wailes7e797b62019-02-22 18:29:22 -0800542 validateUsapCommand(args);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800543 break;
544 } else {
Chris Wailes7e797b62019-02-22 18:29:22 -0800545 Log.e("USAP", "Truncated command received.");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800546 IoUtils.closeQuietly(sessionSocket);
547 }
Chris Wailesae937142019-01-24 12:57:33 -0800548 } catch (Exception ex) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800549 Log.e("USAP", ex.getMessage());
Chris Wailescb0b37f2019-01-11 17:04:41 -0800550 IoUtils.closeQuietly(sessionSocket);
551 }
552 }
553
Chris Wailescb0b37f2019-01-11 17:04:41 -0800554 applyUidSecurityPolicy(args, peerCredentials);
555 applyDebuggerSystemProperty(args);
556
557 int[][] rlimits = null;
558
559 if (args.mRLimits != null) {
560 rlimits = args.mRLimits.toArray(INT_ARRAY_2D);
561 }
562
563 // This must happen before the SELinux policy for this process is
564 // changed when specializing.
565 try {
566 // Used by ZygoteProcess.zygoteSendArgsAndGetResult to fill in a
567 // Process.ProcessStartResult object.
Chris Wailes7e797b62019-02-22 18:29:22 -0800568 usapOutputStream.writeInt(pid);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800569 } catch (IOException ioEx) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800570 Log.e("USAP", "Failed to write response to session socket: " + ioEx.getMessage());
Chris Wailescb0b37f2019-01-11 17:04:41 -0800571 System.exit(-1);
572 } finally {
573 IoUtils.closeQuietly(sessionSocket);
Chris Wailes7e797b62019-02-22 18:29:22 -0800574 IoUtils.closeQuietly(usapPoolSocket);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800575 }
576
577 try {
578 ByteArrayOutputStream buffer =
Chris Wailes7e797b62019-02-22 18:29:22 -0800579 new ByteArrayOutputStream(Zygote.USAP_MANAGEMENT_MESSAGE_BYTES);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800580 DataOutputStream outputStream = new DataOutputStream(buffer);
581
Chris Wailes7e797b62019-02-22 18:29:22 -0800582 // This is written as a long so that the USAP reporting pipe and USAP pool event FD
583 // handlers in ZygoteServer.runSelectLoop can be unified. These two cases should both
584 // send/receive 8 bytes.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800585 outputStream.writeLong(pid);
586 outputStream.flush();
587
588 Os.write(writePipe, buffer.toByteArray(), 0, buffer.size());
589 } catch (Exception ex) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800590 Log.e("USAP",
Chris Wailescb0b37f2019-01-11 17:04:41 -0800591 String.format("Failed to write PID (%d) to pipe (%d): %s",
592 pid, writePipe.getInt$(), ex.getMessage()));
593 System.exit(-1);
594 } finally {
595 IoUtils.closeQuietly(writePipe);
596 }
597
Chris Wailes7e797b62019-02-22 18:29:22 -0800598 specializeAppProcess(args.mUid, args.mGid, args.mGids,
Chris Wailescb0b37f2019-01-11 17:04:41 -0800599 args.mRuntimeFlags, rlimits, args.mMountExternal,
600 args.mSeInfo, args.mNiceName, args.mStartChildZygote,
601 args.mInstructionSet, args.mAppDataDir, args.mPackageName,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800602 args.mPackagesForUid, args.mSandboxId);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800603
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -0700604 disableExecuteOnly(args.mTargetSdkVersion);
605
Chris Wailescb0b37f2019-01-11 17:04:41 -0800606 if (args.mNiceName != null) {
607 Process.setArgV0(args.mNiceName);
608 }
609
610 // End of the postFork event.
611 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
612
613 return ZygoteInit.zygoteInit(args.mTargetSdkVersion,
614 args.mRemainingArgs,
615 null /* classLoader */);
616 }
617
Chris Wailes7e797b62019-02-22 18:29:22 -0800618 private static final String USAP_ERROR_PREFIX = "Invalid command to USAP: ";
Chris Wailescb0b37f2019-01-11 17:04:41 -0800619
620 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800621 * Checks a set of zygote arguments to see if they can be handled by a USAP. Throws an
Chris Wailescb0b37f2019-01-11 17:04:41 -0800622 * exception if an invalid arugment is encountered.
623 * @param args The arguments to test
624 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800625 private static void validateUsapCommand(ZygoteArguments args) {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800626 if (args.mAbiListQuery) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800627 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--query-abi-list");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800628 } else if (args.mPidQuery) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800629 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--get-pid");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800630 } else if (args.mPreloadDefault) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800631 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--preload-default");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800632 } else if (args.mPreloadPackage != null) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800633 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--preload-package");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800634 } else if (args.mPreloadApp != null) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800635 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--preload-app");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800636 } else if (args.mStartChildZygote) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800637 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--start-child-zygote");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800638 } else if (args.mApiBlacklistExemptions != null) {
639 throw new IllegalArgumentException(
Chris Wailes7e797b62019-02-22 18:29:22 -0800640 USAP_ERROR_PREFIX + "--set-api-blacklist-exemptions");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800641 } else if (args.mHiddenApiAccessLogSampleRate != -1) {
642 throw new IllegalArgumentException(
Chris Wailes7e797b62019-02-22 18:29:22 -0800643 USAP_ERROR_PREFIX + "--hidden-api-log-sampling-rate=");
Andrei Oneae8e150d2019-02-18 18:27:11 +0000644 } else if (args.mHiddenApiAccessStatslogSampleRate != -1) {
645 throw new IllegalArgumentException(
Chris Wailes7e797b62019-02-22 18:29:22 -0800646 USAP_ERROR_PREFIX + "--hidden-api-statslog-sampling-rate=");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800647 } else if (args.mInvokeWith != null) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800648 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--invoke-with");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800649 } else if (args.mPermittedCapabilities != 0 || args.mEffectiveCapabilities != 0) {
650 throw new ZygoteSecurityException("Client may not specify capabilities: "
651 + "permitted=0x" + Long.toHexString(args.mPermittedCapabilities)
652 + ", effective=0x" + Long.toHexString(args.mEffectiveCapabilities));
653 }
654 }
655
656 /**
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -0700657 * Mark execute-only segments of libraries read+execute for apps with targetSdkVersion<Q.
658 */
659 protected static void disableExecuteOnly(int targetSdkVersion) {
660 if ((targetSdkVersion < Build.VERSION_CODES.Q) && !nativeDisableExecuteOnly()) {
661 Log.e("Zygote", "Failed to set libraries to read+execute.");
662 }
663 }
664
665 private static native boolean nativeDisableExecuteOnly();
666
667 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800668 * @return Raw file descriptors for the read-end of USAP reporting pipes.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800669 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800670 protected static int[] getUsapPipeFDs() {
671 return nativeGetUsapPipeFDs();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800672 }
673
Chris Wailes7e797b62019-02-22 18:29:22 -0800674 private static native int[] nativeGetUsapPipeFDs();
Chris Wailesaa1c9622019-01-10 16:55:32 -0800675
Chris Wailescb0b37f2019-01-11 17:04:41 -0800676 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800677 * Remove the USAP table entry for the provided process ID.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800678 *
Chris Wailes7e797b62019-02-22 18:29:22 -0800679 * @param usapPID Process ID of the entry to remove
Chris Wailescb0b37f2019-01-11 17:04:41 -0800680 * @return True if the entry was removed; false if it doesn't exist
681 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800682 protected static boolean removeUsapTableEntry(int usapPID) {
683 return nativeRemoveUsapTableEntry(usapPID);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800684 }
685
Chris Wailes7e797b62019-02-22 18:29:22 -0800686 private static native boolean nativeRemoveUsapTableEntry(int usapPID);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800687
Chris Wailes2be26262019-01-11 16:14:43 -0800688 /**
689 * uid 1000 (Process.SYSTEM_UID) may specify any uid &gt; 1000 in normal
690 * operation. It may also specify any gid and setgroups() list it chooses.
691 * In factory test mode, it may specify any UID.
692 *
693 * @param args non-null; zygote spawner arguments
694 * @param peer non-null; peer credentials
695 * @throws ZygoteSecurityException
696 */
697 protected static void applyUidSecurityPolicy(ZygoteArguments args, Credentials peer)
698 throws ZygoteSecurityException {
699
700 if (peer.getUid() == Process.SYSTEM_UID) {
701 /* In normal operation, SYSTEM_UID can only specify a restricted
702 * set of UIDs. In factory test mode, SYSTEM_UID may specify any uid.
703 */
704 boolean uidRestricted = FactoryTest.getMode() == FactoryTest.FACTORY_TEST_OFF;
705
706 if (uidRestricted && args.mUidSpecified && (args.mUid < Process.SYSTEM_UID)) {
707 throw new ZygoteSecurityException(
708 "System UID may not launch process with UID < "
709 + Process.SYSTEM_UID);
710 }
711 }
712
713 // If not otherwise specified, uid and gid are inherited from peer
714 if (!args.mUidSpecified) {
715 args.mUid = peer.getUid();
716 args.mUidSpecified = true;
717 }
718 if (!args.mGidSpecified) {
719 args.mGid = peer.getGid();
720 args.mGidSpecified = true;
721 }
722 }
723
724 /**
725 * Applies debugger system properties to the zygote arguments.
726 *
727 * If "ro.debuggable" is "1", all apps are debuggable. Otherwise,
728 * the debugger state is specified via the "--enable-jdwp" flag
729 * in the spawn request.
730 *
731 * @param args non-null; zygote spawner args
732 */
733 protected static void applyDebuggerSystemProperty(ZygoteArguments args) {
734 if (RoSystemProperties.DEBUGGABLE) {
735 args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
736 }
737 }
738
739 /**
740 * Applies zygote security policy.
741 * Based on the credentials of the process issuing a zygote command:
742 * <ol>
743 * <li> uid 0 (root) may specify --invoke-with to launch Zygote with a
744 * wrapper command.
745 * <li> Any other uid may not specify any invoke-with argument.
746 * </ul>
747 *
748 * @param args non-null; zygote spawner arguments
749 * @param peer non-null; peer credentials
750 * @throws ZygoteSecurityException
751 */
752 protected static void applyInvokeWithSecurityPolicy(ZygoteArguments args, Credentials peer)
753 throws ZygoteSecurityException {
754 int peerUid = peer.getUid();
755
756 if (args.mInvokeWith != null && peerUid != 0
757 && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
Chris Wailesae937142019-01-24 12:57:33 -0800758 throw new ZygoteSecurityException("Peer is permitted to specify an "
759 + "explicit invoke-with wrapper command only for debuggable "
Chris Wailes2be26262019-01-11 16:14:43 -0800760 + "applications.");
761 }
762 }
763
764 /**
765 * Applies invoke-with system properties to the zygote arguments.
766 *
767 * @param args non-null; zygote args
768 */
769 protected static void applyInvokeWithSystemProperty(ZygoteArguments args) {
770 if (args.mInvokeWith == null && args.mNiceName != null) {
771 String property = "wrap." + args.mNiceName;
772 args.mInvokeWith = SystemProperties.get(property);
773 if (args.mInvokeWith != null && args.mInvokeWith.length() == 0) {
774 args.mInvokeWith = null;
775 }
776 }
777 }
778
779 /**
780 * Reads an argument list from the provided socket
781 * @return Argument list or null if EOF is reached
782 * @throws IOException passed straight through
783 */
784 static String[] readArgumentList(BufferedReader socketReader) throws IOException {
Chris Wailes2be26262019-01-11 16:14:43 -0800785 int argc;
786
787 try {
788 String argc_string = socketReader.readLine();
789
790 if (argc_string == null) {
791 // EOF reached.
792 return null;
793 }
794 argc = Integer.parseInt(argc_string);
795
796 } catch (NumberFormatException ex) {
797 Log.e("Zygote", "Invalid Zygote wire format: non-int at argc");
798 throw new IOException("Invalid wire format");
799 }
800
801 // See bug 1092107: large argc can be used for a DOS attack
802 if (argc > MAX_ZYGOTE_ARGC) {
803 throw new IOException("Max arg count exceeded");
804 }
805
806 String[] args = new String[argc];
807 for (int arg_index = 0; arg_index < argc; arg_index++) {
808 args[arg_index] = socketReader.readLine();
809 if (args[arg_index] == null) {
810 // We got an unexpected EOF.
811 throw new IOException("Truncated request");
812 }
813 }
814
815 return args;
816 }
817
Chris Wailescb0b37f2019-01-11 17:04:41 -0800818 /**
Chris Wailescb0b37f2019-01-11 17:04:41 -0800819 * Creates a managed LocalServerSocket object using a file descriptor
820 * created by an init.rc script. The init scripts that specify the
821 * sockets name can be found in system/core/rootdir. The socket is bound
822 * to the file system in the /dev/sockets/ directory, and the file
823 * descriptor is shared via the ANDROID_SOCKET_<socketName> environment
824 * variable.
825 */
826 static LocalServerSocket createManagedSocketFromInitSocket(String socketName) {
827 int fileDesc;
828 final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
829
830 try {
831 String env = System.getenv(fullSocketName);
832 fileDesc = Integer.parseInt(env);
833 } catch (RuntimeException ex) {
834 throw new RuntimeException("Socket unset or invalid: " + fullSocketName, ex);
835 }
836
837 try {
838 FileDescriptor fd = new FileDescriptor();
839 fd.setInt$(fileDesc);
840 return new LocalServerSocket(fd);
841 } catch (IOException ex) {
842 throw new RuntimeException(
843 "Error building socket from file descriptor: " + fileDesc, ex);
844 }
845 }
doheon1.lee885b7422016-01-20 13:07:27 +0900846
Orion Hodson46724e72018-10-19 13:05:33 +0100847 private static void callPostForkSystemServerHooks() {
848 // SystemServer specific post fork hooks run before child post fork hooks.
Neil Fuller555d8b72019-01-28 18:29:20 +0000849 ZygoteHooks.postForkSystemServer();
Orion Hodson46724e72018-10-19 13:05:33 +0100850 }
851
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100852 private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500853 boolean isZygote, String instructionSet) {
Neil Fuller555d8b72019-01-28 18:29:20 +0000854 ZygoteHooks.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100855 }
856
Narayan Kamathb49996d2017-02-06 20:24:08 +0000857 /**
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800858 * Resets the calling thread priority to the default value (Thread.NORM_PRIORITY
859 * or nice value 0). This updates both the priority value in java.lang.Thread and
860 * the nice value (setpriority).
Narayan Kamathb49996d2017-02-06 20:24:08 +0000861 */
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800862 static void resetNicePriority() {
863 Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
864 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100865
866 /**
867 * Executes "/system/bin/sh -c &lt;command&gt;" using the exec() system call.
868 * This method throws a runtime exception if exec() failed, otherwise, this
869 * method never returns.
870 *
871 * @param command The shell command to execute.
872 */
873 public static void execShell(String command) {
874 String[] args = { "/system/bin/sh", "-c", command };
875 try {
Elliott Hughes860c5912014-04-28 19:19:13 -0700876 Os.execv(args[0], args);
Narayan Kamath973b4662014-03-31 13:41:26 +0100877 } catch (ErrnoException e) {
878 throw new RuntimeException(e);
879 }
880 }
881
882 /**
883 * Appends quotes shell arguments to the specified string builder.
884 * The arguments are quoted using single-quotes, escaped if necessary,
885 * prefixed with a space, and appended to the command.
886 *
887 * @param command A string builder for the shell command being constructed.
888 * @param args An array of argument strings to be quoted and appended to the command.
889 * @see #execShell(String)
890 */
891 public static void appendQuotedShellArgs(StringBuilder command, String[] args) {
892 for (String arg : args) {
893 command.append(" '").append(arg.replace("'", "'\\''")).append("'");
894 }
895 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100896}