blob: 70d8b453f5aed75931e621a08676cdf52bb6af80 [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;
Mathieu Chartier0bccbf72019-01-30 15:56:17 -080032import android.provider.DeviceConfig;
Elliott Hughes860c5912014-04-28 19:19:13 -070033import android.system.ErrnoException;
34import android.system.Os;
Chris Wailes2be26262019-01-11 16:14:43 -080035import android.util.Log;
Narayan Kamath973b4662014-03-31 13:41:26 +010036
Jeff Sharkeyace874b2017-09-07 15:27:33 -060037import dalvik.system.ZygoteHooks;
Tobias Sargeantb9679dc2016-01-19 16:34:54 +000038
Chris Wailescb0b37f2019-01-11 17:04:41 -080039import libcore.io.IoUtils;
40
Chris Wailes2be26262019-01-11 16:14:43 -080041import java.io.BufferedReader;
Chris Wailescb0b37f2019-01-11 17:04:41 -080042import java.io.ByteArrayOutputStream;
43import java.io.DataOutputStream;
44import java.io.FileDescriptor;
Chris Wailes2be26262019-01-11 16:14:43 -080045import java.io.IOException;
Chris Wailescb0b37f2019-01-11 17:04:41 -080046import java.io.InputStreamReader;
Chris Wailes2be26262019-01-11 16:14:43 -080047
Narayan Kamath973b4662014-03-31 13:41:26 +010048/** @hide */
49public final class Zygote {
50 /*
Nicolas Geoffray81edac42017-09-07 14:13:29 +010051 * Bit values for "runtimeFlags" argument. The definitions are duplicated
Narayan Kamath973b4662014-03-31 13:41:26 +010052 * in the native code.
53 */
54
55 /** enable debugging over JDWP */
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000056 public static final int DEBUG_ENABLE_JDWP = 1;
Narayan Kamath973b4662014-03-31 13:41:26 +010057 /** enable JNI checks */
58 public static final int DEBUG_ENABLE_CHECKJNI = 1 << 1;
59 /** enable Java programming language "assert" statements */
60 public static final int DEBUG_ENABLE_ASSERT = 1 << 2;
Mathieu Chartier7a490282015-03-17 09:51:36 -070061 /** disable the AOT compiler and JIT */
Narayan Kamath973b4662014-03-31 13:41:26 +010062 public static final int DEBUG_ENABLE_SAFEMODE = 1 << 3;
63 /** Enable logging of third-party JNI activity. */
64 public static final int DEBUG_ENABLE_JNI_LOGGING = 1 << 4;
David Srbecky065075e2015-05-28 17:16:09 +010065 /** Force generation of native debugging information. */
Nicolas Geoffray9abbf452015-11-05 11:29:42 +000066 public static final int DEBUG_GENERATE_DEBUG_INFO = 1 << 5;
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000067 /** Always use JIT-ed code. */
68 public static final int DEBUG_ALWAYS_JIT = 1 << 6;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000069 /** Make the code native debuggable by turning off some optimizations. */
Tamas Berghammerdf6cb282016-01-29 12:07:00 +000070 public static final int DEBUG_NATIVE_DEBUGGABLE = 1 << 7;
Nicolas Geoffray347b1df2016-12-20 14:05:05 +000071 /** Make the code Java debuggable by turning off some optimizations. */
72 public static final int DEBUG_JAVA_DEBUGGABLE = 1 << 8;
Mathieu Chartier7a490282015-03-17 09:51:36 -070073
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010074 /** Turn off the verifier. */
75 public static final int DISABLE_VERIFIER = 1 << 9;
76 /** Only use oat files located in /system. Otherwise use dex/jar/apk . */
77 public static final int ONLY_USE_SYSTEM_OAT_FILES = 1 << 10;
David Srbecky156ed922018-01-30 14:37:37 +000078 /** Force generation of native debugging information for backtraces. */
Mathew Inwood16073b82018-03-23 10:05:01 +000079 public static final int DEBUG_GENERATE_MINI_DEBUG_INFO = 1 << 11;
80 /**
81 * Hidden API access restrictions. This is a mask for bits representing the API enforcement
82 * policy, defined by {@code @ApplicationInfo.HiddenApiEnforcementPolicy}.
83 */
84 public static final int API_ENFORCEMENT_POLICY_MASK = (1 << 12) | (1 << 13);
85 /**
86 * Bit shift for use with {@link #API_ENFORCEMENT_POLICY_MASK}.
87 *
88 * (flags & API_ENFORCEMENT_POLICY_MASK) >> API_ENFORCEMENT_POLICY_SHIFT gives
89 * @ApplicationInfo.ApiEnforcementPolicy values.
90 */
91 public static final int API_ENFORCEMENT_POLICY_SHIFT =
92 Integer.numberOfTrailingZeros(API_ENFORCEMENT_POLICY_MASK);
Calin Juravle8eb891b2018-05-03 19:51:18 -070093 /**
94 * Enable system server ART profiling.
95 */
96 public static final int PROFILE_SYSTEM_SERVER = 1 << 14;
Nicolas Geoffray1f88ad62017-09-13 14:21:00 +010097
Yabin Cui4d8546d2019-01-29 16:29:20 -080098 /**
99 * Enable profiling from shell.
100 */
101 public static final int PROFILE_FROM_SHELL = 1 << 15;
102
Mathieu Chartierced7e082019-02-04 13:28:36 -0800103 /*
104 * Enable using the ART app image startup cache
105 */
106 public static final int USE_APP_IMAGE_STARTUP_CACHE = 1 << 16;
107
Narayan Kamath973b4662014-03-31 13:41:26 +0100108 /** No external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600109 public static final int MOUNT_EXTERNAL_NONE = IVold.REMOUNT_MODE_NONE;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700110 /** Default external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600111 public static final int MOUNT_EXTERNAL_DEFAULT = IVold.REMOUNT_MODE_DEFAULT;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700112 /** Read-only external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600113 public static final int MOUNT_EXTERNAL_READ = IVold.REMOUNT_MODE_READ;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700114 /** Read-write external storage should be mounted. */
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600115 public static final int MOUNT_EXTERNAL_WRITE = IVold.REMOUNT_MODE_WRITE;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800116 /**
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800117 * Mount mode for apps that are already installed on the device before the isolated_storage
118 * feature is enabled.
119 */
120 public static final int MOUNT_EXTERNAL_LEGACY = IVold.REMOUNT_MODE_LEGACY;
121 /**
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800122 * Mount mode for package installers which should give them access to
123 * all obb dirs in addition to their package sandboxes
124 */
125 public static final int MOUNT_EXTERNAL_INSTALLER = IVold.REMOUNT_MODE_INSTALLER;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700126 /** Read-write external storage should be mounted instead of package sandbox */
127 public static final int MOUNT_EXTERNAL_FULL = IVold.REMOUNT_MODE_FULL;
Narayan Kamath973b4662014-03-31 13:41:26 +0100128
Chris Wailes7e797b62019-02-22 18:29:22 -0800129 /** Number of bytes sent to the Zygote over USAP pipes or the pool event FD */
130 public static final int USAP_MANAGEMENT_MESSAGE_BYTES = 8;
Chris Wailescb0b37f2019-01-11 17:04:41 -0800131
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800132 /**
Robert Sesekd0a190df2018-02-12 18:46:01 -0500133 * An extraArg passed when a zygote process is forking a child-zygote, specifying a name
134 * in the abstract socket namespace. This socket name is what the new child zygote
135 * should listen for connections on.
136 */
137 public static final String CHILD_ZYGOTE_SOCKET_NAME_ARG = "--zygote-socket=";
138
Martijn Coenen7e6fa672018-11-05 11:45:26 +0100139 /**
140 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
141 * requested ABI for the child Zygote.
142 */
143 public static final String CHILD_ZYGOTE_ABI_LIST_ARG = "--abi-list=";
144
Martijn Coenen86f08a52019-01-03 16:23:01 +0100145 /**
146 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
147 * start of the UID range the children of the Zygote may setuid()/setgid() to. This
148 * will be enforced with a seccomp filter.
149 */
150 public static final String CHILD_ZYGOTE_UID_RANGE_START = "--uid-range-start=";
151
152 /**
153 * An extraArg passed when a zygote process is forking a child-zygote, specifying the
154 * end of the UID range the children of the Zygote may setuid()/setgid() to. This
155 * will be enforced with a seccomp filter.
156 */
157 public static final String CHILD_ZYGOTE_UID_RANGE_END = "--uid-range-end=";
158
Chris Wailescb0b37f2019-01-11 17:04:41 -0800159 /** Prefix prepended to socket names created by init */
160 private static final String ANDROID_SOCKET_PREFIX = "ANDROID_SOCKET_";
161
162 /**
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800163 * The duration to wait before re-checking Zygote related system properties.
164 *
Chris Wailesdb132a32019-02-20 10:49:27 -0800165 * One minute in milliseconds.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800166 */
Chris Wailesdb132a32019-02-20 10:49:27 -0800167 public static final long PROPERTY_CHECK_INTERVAL = 60000;
Chris Wailescb0b37f2019-01-11 17:04:41 -0800168
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800169 /**
170 * @hide for internal use only
171 */
172 public static final int SOCKET_BUFFER_SIZE = 256;
173
Chris Wailes2be26262019-01-11 16:14:43 -0800174 /** a prototype instance for a future List.toArray() */
175 protected static final int[][] INT_ARRAY_2D = new int[0][0];
176
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800177 /**
178 * @hide for internal use only.
179 */
180 public static final String PRIMARY_SOCKET_NAME = "zygote";
181
182 /**
183 * @hide for internal use only.
184 */
185 public static final String SECONDARY_SOCKET_NAME = "zygote_secondary";
186
187 /**
188 * @hide for internal use only
189 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800190 public static final String USAP_POOL_PRIMARY_SOCKET_NAME = "usap_pool_primary";
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800191
192 /**
193 * @hide for internal use only
194 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800195 public static final String USAP_POOL_SECONDARY_SOCKET_NAME = "usap_pool_secondary";
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800196
Narayan Kamath973b4662014-03-31 13:41:26 +0100197 private Zygote() {}
198
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800199 /** Called for some security initialization before any fork. */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800200 static native void nativeSecurityInit();
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800201
Narayan Kamath973b4662014-03-31 13:41:26 +0100202 /**
203 * Forks a new VM instance. The current VM must have been started
204 * with the -Xzygote flag. <b>NOTE: new instance keeps all
205 * root capabilities. The new process is expected to call capset()</b>.
206 *
207 * @param uid the UNIX uid that the new process should setuid() to after
208 * fork()ing and and before spawning any threads.
209 * @param gid the UNIX gid that the new process should setgid() to after
210 * fork()ing and and before spawning any threads.
211 * @param gids null-ok; a list of UNIX gids that the new process should
212 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100213 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100214 * @param rlimits null-ok an array of rlimit tuples, with the second
215 * dimension having a length of 3 and representing
216 * (resource, rlim_cur, rlim_max). These are set via the posix
217 * setrlimit(2) call.
218 * @param seInfo null-ok a string specifying SELinux information for
219 * the new process.
220 * @param niceName null-ok a string specifying the process name.
221 * @param fdsToClose an array of ints, holding one or more POSIX
222 * file descriptor numbers that are to be closed by the child
223 * (and replaced by /dev/null) after forking. An integer value
224 * of -1 in any entry in the array means "ignore this one".
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800225 * @param fdsToIgnore null-ok an array of ints, either null or holding
226 * one or more POSIX file descriptor numbers that are to be ignored
227 * in the file descriptor table check.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500228 * @param startChildZygote if true, the new child process will itself be a
229 * new zygote process.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700230 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400231 * @param appDataDir null-ok the data directory of the app.
Narayan Kamath973b4662014-03-31 13:41:26 +0100232 *
233 * @return 0 if this is the child, pid of the child
234 * if this is the parent, or -1 on error.
235 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100236 public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700237 int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
238 int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800239 String packageName, String[] packagesForUID, String sandboxId) {
Neil Fuller555d8b72019-01-28 18:29:20 +0000240 ZygoteHooks.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800241 // Resets nice priority for zygote process.
242 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100243 int pid = nativeForkAndSpecialize(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800244 uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
245 fdsToIgnore, startChildZygote, instructionSet, appDataDir, packageName,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800246 packagesForUID, sandboxId);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100247 // Enable tracing as soon as possible for the child process.
248 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700249 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100250
251 // Note that this event ends at the end of handleChildProc,
252 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
253 }
Neil Fuller555d8b72019-01-28 18:29:20 +0000254 ZygoteHooks.postForkCommon();
Narayan Kamath973b4662014-03-31 13:41:26 +0100255 return pid;
256 }
257
Chris Wailesaa1c9622019-01-10 16:55:32 -0800258 private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
259 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
260 int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800261 String appDataDir, String packageName, String[] packagesForUID,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800262 String sandboxId);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800263
Chris Wailescb0b37f2019-01-11 17:04:41 -0800264 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800265 * Specialize an unspecialized app process. The current VM must have been started
Chris Wailescb0b37f2019-01-11 17:04:41 -0800266 * with the -Xzygote flag.
267 *
268 * @param uid The UNIX uid that the new process should setuid() to before spawning any threads
269 * @param gid The UNIX gid that the new process should setgid() to before spawning any threads
270 * @param gids null-ok; A list of UNIX gids that the new process should
271 * setgroups() to before spawning any threads
272 * @param runtimeFlags Bit flags that enable ART features
273 * @param rlimits null-ok An array of rlimit tuples, with the second
274 * dimension having a length of 3 and representing
275 * (resource, rlim_cur, rlim_max). These are set via the posix
276 * setrlimit(2) call.
277 * @param seInfo null-ok A string specifying SELinux information for
278 * the new process.
279 * @param niceName null-ok A string specifying the process name.
280 * @param startChildZygote If true, the new child process will itself be a
281 * new zygote process.
282 * @param instructionSet null-ok The instruction set to use.
283 * @param appDataDir null-ok The data directory of the app.
284 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800285 public static void specializeAppProcess(int uid, int gid, int[] gids, int runtimeFlags,
Chris Wailescb0b37f2019-01-11 17:04:41 -0800286 int[][] rlimits, int mountExternal, String seInfo, String niceName,
Chris Wailesba4c2eb2019-01-11 17:13:00 -0800287 boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800288 String[] packagesForUID, String sandboxId) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800289 nativeSpecializeAppProcess(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
Chris Wailescb0b37f2019-01-11 17:04:41 -0800290 niceName, startChildZygote, instructionSet, appDataDir,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800291 packageName, packagesForUID, sandboxId);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800292
293 // Enable tracing as soon as possible for the child process.
294 Trace.setTracingEnabled(true, runtimeFlags);
295
296 // Note that this event ends at the end of handleChildProc.
297 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
298
299 /*
300 * This is called here (instead of after the fork but before the specialize) to maintain
301 * consistancy with the code paths for forkAndSpecialize.
302 *
303 * TODO (chriswailes): Look into moving this to immediately after the fork.
304 */
Neil Fuller555d8b72019-01-28 18:29:20 +0000305 ZygoteHooks.postForkCommon();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800306 }
307
Chris Wailes7e797b62019-02-22 18:29:22 -0800308 private static native void nativeSpecializeAppProcess(int uid, int gid, int[] gids,
Chris Wailesaa1c9622019-01-10 16:55:32 -0800309 int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
310 boolean startChildZygote, String instructionSet, String appDataDir, String packageName,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800311 String[] packagesForUID, String sandboxId);
Narayan Kamath973b4662014-03-31 13:41:26 +0100312
313 /**
Christopher Ferris2980de42017-06-20 16:13:40 -0700314 * Called to do any initialization before starting an application.
315 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800316 static native void nativePreApplicationInit();
Christopher Ferris2980de42017-06-20 16:13:40 -0700317
318 /**
Narayan Kamath973b4662014-03-31 13:41:26 +0100319 * Special method to start the system server process. In addition to the
320 * common actions performed in forkAndSpecialize, the pid of the child
321 * process is recorded such that the death of the child process will cause
322 * zygote to exit.
323 *
324 * @param uid the UNIX uid that the new process should setuid() to after
325 * fork()ing and and before spawning any threads.
326 * @param gid the UNIX gid that the new process should setgid() to after
327 * fork()ing and and before spawning any threads.
328 * @param gids null-ok; a list of UNIX gids that the new process should
329 * setgroups() to after fork and before spawning any threads.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100330 * @param runtimeFlags bit flags that enable ART features.
Narayan Kamath973b4662014-03-31 13:41:26 +0100331 * @param rlimits null-ok an array of rlimit tuples, with the second
332 * dimension having a length of 3 and representing
333 * (resource, rlim_cur, rlim_max). These are set via the posix
334 * setrlimit(2) call.
335 * @param permittedCapabilities argument for setcap()
336 * @param effectiveCapabilities argument for setcap()
337 *
338 * @return 0 if this is the child, pid of the child
339 * if this is the parent, or -1 on error.
340 */
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100341 public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100342 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
Neil Fuller555d8b72019-01-28 18:29:20 +0000343 ZygoteHooks.preFork();
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800344 // Resets nice priority for zygote process.
345 resetNicePriority();
Narayan Kamath973b4662014-03-31 13:41:26 +0100346 int pid = nativeForkSystemServer(
Chris Wailesaa1c9622019-01-10 16:55:32 -0800347 uid, gid, gids, runtimeFlags, rlimits,
348 permittedCapabilities, effectiveCapabilities);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100349 // Enable tracing as soon as we enter the system_server.
350 if (pid == 0) {
Andreas Gampe8f4eab22017-09-13 18:16:13 -0700351 Trace.setTracingEnabled(true, runtimeFlags);
Narayan Kamathfbb32f62015-06-12 15:34:35 +0100352 }
Neil Fuller555d8b72019-01-28 18:29:20 +0000353 ZygoteHooks.postForkCommon();
Narayan Kamath973b4662014-03-31 13:41:26 +0100354 return pid;
355 }
356
Chris Wailesaa1c9622019-01-10 16:55:32 -0800357 private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
Narayan Kamath973b4662014-03-31 13:41:26 +0100358 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
359
doheon1.lee885b7422016-01-20 13:07:27 +0900360 /**
Robert Sesek54e387d2016-12-02 17:27:50 -0500361 * Lets children of the zygote inherit open file descriptors to this path.
362 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800363 protected static native void nativeAllowFileAcrossFork(String path);
Robert Sesek54e387d2016-12-02 17:27:50 -0500364
365 /**
Martijn Coenen4b988162019-01-28 13:58:45 +0100366 * Lets children of the zygote inherit open file descriptors that belong to the
367 * ApplicationInfo that is passed in.
368 *
369 * @param appInfo ApplicationInfo of the application
370 */
371 protected static void allowAppFilesAcrossFork(ApplicationInfo appInfo) {
Torne (Richard Coles)1aaae102019-03-01 15:02:29 -0500372 for (String path : appInfo.getAllApkPaths()) {
373 Zygote.nativeAllowFileAcrossFork(path);
Martijn Coenen4b988162019-01-28 13:58:45 +0100374 }
375 }
376
377 /**
Martijn Coenen86f08a52019-01-03 16:23:01 +0100378 * Installs a seccomp filter that limits setresuid()/setresgid() to the passed-in range
379 * @param uidGidMin The smallest allowed uid/gid
380 * @param uidGidMax The largest allowed uid/gid
381 */
382 native protected static void nativeInstallSeccompUidGidFilter(int uidGidMin, int uidGidMax);
383
384 /**
doheon1.lee885b7422016-01-20 13:07:27 +0900385 * Zygote unmount storage space on initializing.
386 * This method is called once.
387 */
Chris Wailesaa1c9622019-01-10 16:55:32 -0800388 protected static native void nativeUnmountStorageOnInit();
389
Chris Wailescb0b37f2019-01-11 17:04:41 -0800390 /**
391 * Get socket file descriptors (opened by init) from the environment and
392 * store them for access from native code later.
393 *
394 * @param isPrimary True if this is the zygote process, false if it is zygote_secondary
395 */
396 public static void getSocketFDs(boolean isPrimary) {
397 nativeGetSocketFDs(isPrimary);
398 }
399
Chris Wailesaa1c9622019-01-10 16:55:32 -0800400 protected static native void nativeGetSocketFDs(boolean isPrimary);
401
Chris Wailescb0b37f2019-01-11 17:04:41 -0800402 /**
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800403 * Returns the raw string value of a system property.
404 *
405 * Note that Device Config is not available without an application so SystemProperties is used
406 * instead.
407 *
408 * TODO (chriswailes): Cache the system property location in native code and then write a JNI
409 * function to fetch it.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800410 */
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800411 public static String getSystemProperty(String propertyName, String defaultValue) {
412 return SystemProperties.get(
413 String.join(".",
414 "persist.device_config",
415 DeviceConfig.RuntimeNative.NAMESPACE,
416 propertyName),
417 defaultValue);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800418 }
419
Chris Wailes7e797b62019-02-22 18:29:22 -0800420 protected static void emptyUsapPool() {
421 nativeEmptyUsapPool();
Chris Wailesae937142019-01-24 12:57:33 -0800422 }
423
Chris Wailes7e797b62019-02-22 18:29:22 -0800424 private static native void nativeEmptyUsapPool();
Chris Wailesae937142019-01-24 12:57:33 -0800425
Chris Wailescb0b37f2019-01-11 17:04:41 -0800426 /**
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800427 * Returns the value of a system property converted to a boolean using specific logic.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800428 *
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800429 * Note that Device Config is not available without an application so SystemProperties is used
430 * instead.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800431 *
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800432 * @see SystemProperties.getBoolean
433 *
434 * TODO (chriswailes): Cache the system property location in native code and then write a JNI
435 * function to fetch it.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800436 */
Mathieu Chartier0bccbf72019-01-30 15:56:17 -0800437 public static boolean getSystemPropertyBoolean(String propertyName, Boolean defaultValue) {
438 return SystemProperties.getBoolean(
439 String.join(".",
440 "persist.device_config",
441 DeviceConfig.RuntimeNative.NAMESPACE,
442 propertyName),
443 defaultValue);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800444 }
445
446 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800447 * @return Number of unspecialized app processes currently in the pool
Chris Wailescb0b37f2019-01-11 17:04:41 -0800448 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800449 static int getUsapPoolCount() {
450 return nativeGetUsapPoolCount();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800451 }
452
Chris Wailes7e797b62019-02-22 18:29:22 -0800453 private static native int nativeGetUsapPoolCount();
Chris Wailesaa1c9622019-01-10 16:55:32 -0800454
Chris Wailescb0b37f2019-01-11 17:04:41 -0800455 /**
456 * @return The event FD used for communication between the signal handler and the ZygoteServer
457 * poll loop
458 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800459 static FileDescriptor getUsapPoolEventFD() {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800460 FileDescriptor fd = new FileDescriptor();
Chris Wailes7e797b62019-02-22 18:29:22 -0800461 fd.setInt$(nativeGetUsapPoolEventFD());
Chris Wailescb0b37f2019-01-11 17:04:41 -0800462
463 return fd;
464 }
465
Chris Wailes7e797b62019-02-22 18:29:22 -0800466 private static native int nativeGetUsapPoolEventFD();
Chris Wailesaa1c9622019-01-10 16:55:32 -0800467
Chris Wailescb0b37f2019-01-11 17:04:41 -0800468 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800469 * Fork a new unspecialized app process from the zygote
Chris Wailescb0b37f2019-01-11 17:04:41 -0800470 *
471 * @param sessionSocketRawFDs Anonymous session sockets that are currently open
Chris Wailes7e797b62019-02-22 18:29:22 -0800472 * @return In the Zygote process this function will always return null; in unspecialized app
473 * processes this function will return a Runnable object representing the new
474 * application that is passed up from usapMain.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800475 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800476 static Runnable forkUsap(LocalServerSocket usapPoolSocket,
477 int[] sessionSocketRawFDs) {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800478 FileDescriptor[] pipeFDs = null;
479
480 try {
481 pipeFDs = Os.pipe2(O_CLOEXEC);
482 } catch (ErrnoException errnoEx) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800483 throw new IllegalStateException("Unable to create USAP pipe.", errnoEx);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800484 }
485
486 int pid =
Chris Wailes7e797b62019-02-22 18:29:22 -0800487 nativeForkUsap(pipeFDs[0].getInt$(), pipeFDs[1].getInt$(), sessionSocketRawFDs);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800488
489 if (pid == 0) {
490 IoUtils.closeQuietly(pipeFDs[0]);
Chris Wailes7e797b62019-02-22 18:29:22 -0800491 return usapMain(usapPoolSocket, pipeFDs[1]);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800492 } else {
493 // The read-end of the pipe will be closed by the native code.
Chris Wailes7e797b62019-02-22 18:29:22 -0800494 // See removeUsapTableEntry();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800495 IoUtils.closeQuietly(pipeFDs[1]);
496 return null;
497 }
498 }
499
Chris Wailes7e797b62019-02-22 18:29:22 -0800500 private static native int nativeForkUsap(int readPipeFD,
Chris Wailesaa1c9622019-01-10 16:55:32 -0800501 int writePipeFD,
502 int[] sessionSocketRawFDs);
503
Chris Wailescb0b37f2019-01-11 17:04:41 -0800504 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800505 * This function is used by unspecialized app processes to wait for specialization requests from
506 * the system server.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800507 *
508 * @param writePipe The write end of the reporting pipe used to communicate with the poll loop
509 * of the ZygoteServer.
510 * @return A runnable oject representing the new application.
511 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800512 private static Runnable usapMain(LocalServerSocket usapPoolSocket,
513 FileDescriptor writePipe) {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800514 final int pid = Process.myPid();
515
516 LocalSocket sessionSocket = null;
Chris Wailes7e797b62019-02-22 18:29:22 -0800517 DataOutputStream usapOutputStream = null;
Chris Wailescb0b37f2019-01-11 17:04:41 -0800518 Credentials peerCredentials = null;
Chris Wailesae937142019-01-24 12:57:33 -0800519 ZygoteArguments args = null;
Chris Wailescb0b37f2019-01-11 17:04:41 -0800520
521 while (true) {
522 try {
Chris Wailes7e797b62019-02-22 18:29:22 -0800523 sessionSocket = usapPoolSocket.accept();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800524
Chris Wailes7e797b62019-02-22 18:29:22 -0800525 BufferedReader usapReader =
Chris Wailescb0b37f2019-01-11 17:04:41 -0800526 new BufferedReader(new InputStreamReader(sessionSocket.getInputStream()));
Chris Wailes7e797b62019-02-22 18:29:22 -0800527 usapOutputStream =
Chris Wailescb0b37f2019-01-11 17:04:41 -0800528 new DataOutputStream(sessionSocket.getOutputStream());
529
530 peerCredentials = sessionSocket.getPeerCredentials();
531
Chris Wailes7e797b62019-02-22 18:29:22 -0800532 String[] argStrings = readArgumentList(usapReader);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800533
534 if (argStrings != null) {
Chris Wailesae937142019-01-24 12:57:33 -0800535 args = new ZygoteArguments(argStrings);
536
537 // TODO (chriswailes): Should this only be run for debug builds?
Chris Wailes7e797b62019-02-22 18:29:22 -0800538 validateUsapCommand(args);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800539 break;
540 } else {
Chris Wailes7e797b62019-02-22 18:29:22 -0800541 Log.e("USAP", "Truncated command received.");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800542 IoUtils.closeQuietly(sessionSocket);
543 }
Chris Wailesae937142019-01-24 12:57:33 -0800544 } catch (Exception ex) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800545 Log.e("USAP", ex.getMessage());
Chris Wailescb0b37f2019-01-11 17:04:41 -0800546 IoUtils.closeQuietly(sessionSocket);
547 }
548 }
549
Chris Wailescb0b37f2019-01-11 17:04:41 -0800550 applyUidSecurityPolicy(args, peerCredentials);
551 applyDebuggerSystemProperty(args);
552
553 int[][] rlimits = null;
554
555 if (args.mRLimits != null) {
556 rlimits = args.mRLimits.toArray(INT_ARRAY_2D);
557 }
558
559 // This must happen before the SELinux policy for this process is
560 // changed when specializing.
561 try {
562 // Used by ZygoteProcess.zygoteSendArgsAndGetResult to fill in a
563 // Process.ProcessStartResult object.
Chris Wailes7e797b62019-02-22 18:29:22 -0800564 usapOutputStream.writeInt(pid);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800565 } catch (IOException ioEx) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800566 Log.e("USAP", "Failed to write response to session socket: " + ioEx.getMessage());
Chris Wailescb0b37f2019-01-11 17:04:41 -0800567 System.exit(-1);
568 } finally {
569 IoUtils.closeQuietly(sessionSocket);
Chris Wailes7e797b62019-02-22 18:29:22 -0800570 IoUtils.closeQuietly(usapPoolSocket);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800571 }
572
573 try {
574 ByteArrayOutputStream buffer =
Chris Wailes7e797b62019-02-22 18:29:22 -0800575 new ByteArrayOutputStream(Zygote.USAP_MANAGEMENT_MESSAGE_BYTES);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800576 DataOutputStream outputStream = new DataOutputStream(buffer);
577
Chris Wailes7e797b62019-02-22 18:29:22 -0800578 // This is written as a long so that the USAP reporting pipe and USAP pool event FD
579 // handlers in ZygoteServer.runSelectLoop can be unified. These two cases should both
580 // send/receive 8 bytes.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800581 outputStream.writeLong(pid);
582 outputStream.flush();
583
584 Os.write(writePipe, buffer.toByteArray(), 0, buffer.size());
585 } catch (Exception ex) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800586 Log.e("USAP",
Chris Wailescb0b37f2019-01-11 17:04:41 -0800587 String.format("Failed to write PID (%d) to pipe (%d): %s",
588 pid, writePipe.getInt$(), ex.getMessage()));
589 System.exit(-1);
590 } finally {
591 IoUtils.closeQuietly(writePipe);
592 }
593
Chris Wailes7e797b62019-02-22 18:29:22 -0800594 specializeAppProcess(args.mUid, args.mGid, args.mGids,
Chris Wailescb0b37f2019-01-11 17:04:41 -0800595 args.mRuntimeFlags, rlimits, args.mMountExternal,
596 args.mSeInfo, args.mNiceName, args.mStartChildZygote,
597 args.mInstructionSet, args.mAppDataDir, args.mPackageName,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800598 args.mPackagesForUid, args.mSandboxId);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800599
600 if (args.mNiceName != null) {
601 Process.setArgV0(args.mNiceName);
602 }
603
604 // End of the postFork event.
605 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
606
607 return ZygoteInit.zygoteInit(args.mTargetSdkVersion,
608 args.mRemainingArgs,
609 null /* classLoader */);
610 }
611
Chris Wailes7e797b62019-02-22 18:29:22 -0800612 private static final String USAP_ERROR_PREFIX = "Invalid command to USAP: ";
Chris Wailescb0b37f2019-01-11 17:04:41 -0800613
614 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800615 * 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 -0800616 * exception if an invalid arugment is encountered.
617 * @param args The arguments to test
618 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800619 private static void validateUsapCommand(ZygoteArguments args) {
Chris Wailescb0b37f2019-01-11 17:04:41 -0800620 if (args.mAbiListQuery) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800621 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--query-abi-list");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800622 } else if (args.mPidQuery) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800623 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--get-pid");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800624 } else if (args.mPreloadDefault) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800625 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--preload-default");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800626 } else if (args.mPreloadPackage != null) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800627 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--preload-package");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800628 } else if (args.mPreloadApp != null) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800629 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--preload-app");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800630 } else if (args.mStartChildZygote) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800631 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--start-child-zygote");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800632 } else if (args.mApiBlacklistExemptions != null) {
633 throw new IllegalArgumentException(
Chris Wailes7e797b62019-02-22 18:29:22 -0800634 USAP_ERROR_PREFIX + "--set-api-blacklist-exemptions");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800635 } else if (args.mHiddenApiAccessLogSampleRate != -1) {
636 throw new IllegalArgumentException(
Chris Wailes7e797b62019-02-22 18:29:22 -0800637 USAP_ERROR_PREFIX + "--hidden-api-log-sampling-rate=");
Andrei Oneae8e150d2019-02-18 18:27:11 +0000638 } else if (args.mHiddenApiAccessStatslogSampleRate != -1) {
639 throw new IllegalArgumentException(
Chris Wailes7e797b62019-02-22 18:29:22 -0800640 USAP_ERROR_PREFIX + "--hidden-api-statslog-sampling-rate=");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800641 } else if (args.mInvokeWith != null) {
Chris Wailes7e797b62019-02-22 18:29:22 -0800642 throw new IllegalArgumentException(USAP_ERROR_PREFIX + "--invoke-with");
Chris Wailescb0b37f2019-01-11 17:04:41 -0800643 } else if (args.mPermittedCapabilities != 0 || args.mEffectiveCapabilities != 0) {
644 throw new ZygoteSecurityException("Client may not specify capabilities: "
645 + "permitted=0x" + Long.toHexString(args.mPermittedCapabilities)
646 + ", effective=0x" + Long.toHexString(args.mEffectiveCapabilities));
647 }
648 }
649
650 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800651 * @return Raw file descriptors for the read-end of USAP reporting pipes.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800652 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800653 protected static int[] getUsapPipeFDs() {
654 return nativeGetUsapPipeFDs();
Chris Wailescb0b37f2019-01-11 17:04:41 -0800655 }
656
Chris Wailes7e797b62019-02-22 18:29:22 -0800657 private static native int[] nativeGetUsapPipeFDs();
Chris Wailesaa1c9622019-01-10 16:55:32 -0800658
Chris Wailescb0b37f2019-01-11 17:04:41 -0800659 /**
Chris Wailes7e797b62019-02-22 18:29:22 -0800660 * Remove the USAP table entry for the provided process ID.
Chris Wailescb0b37f2019-01-11 17:04:41 -0800661 *
Chris Wailes7e797b62019-02-22 18:29:22 -0800662 * @param usapPID Process ID of the entry to remove
Chris Wailescb0b37f2019-01-11 17:04:41 -0800663 * @return True if the entry was removed; false if it doesn't exist
664 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800665 protected static boolean removeUsapTableEntry(int usapPID) {
666 return nativeRemoveUsapTableEntry(usapPID);
Chris Wailescb0b37f2019-01-11 17:04:41 -0800667 }
668
Chris Wailes7e797b62019-02-22 18:29:22 -0800669 private static native boolean nativeRemoveUsapTableEntry(int usapPID);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800670
Chris Wailes2be26262019-01-11 16:14:43 -0800671 /**
672 * uid 1000 (Process.SYSTEM_UID) may specify any uid &gt; 1000 in normal
673 * operation. It may also specify any gid and setgroups() list it chooses.
674 * In factory test mode, it may specify any UID.
675 *
676 * @param args non-null; zygote spawner arguments
677 * @param peer non-null; peer credentials
678 * @throws ZygoteSecurityException
679 */
680 protected static void applyUidSecurityPolicy(ZygoteArguments args, Credentials peer)
681 throws ZygoteSecurityException {
682
683 if (peer.getUid() == Process.SYSTEM_UID) {
684 /* In normal operation, SYSTEM_UID can only specify a restricted
685 * set of UIDs. In factory test mode, SYSTEM_UID may specify any uid.
686 */
687 boolean uidRestricted = FactoryTest.getMode() == FactoryTest.FACTORY_TEST_OFF;
688
689 if (uidRestricted && args.mUidSpecified && (args.mUid < Process.SYSTEM_UID)) {
690 throw new ZygoteSecurityException(
691 "System UID may not launch process with UID < "
692 + Process.SYSTEM_UID);
693 }
694 }
695
696 // If not otherwise specified, uid and gid are inherited from peer
697 if (!args.mUidSpecified) {
698 args.mUid = peer.getUid();
699 args.mUidSpecified = true;
700 }
701 if (!args.mGidSpecified) {
702 args.mGid = peer.getGid();
703 args.mGidSpecified = true;
704 }
705 }
706
707 /**
708 * Applies debugger system properties to the zygote arguments.
709 *
710 * If "ro.debuggable" is "1", all apps are debuggable. Otherwise,
711 * the debugger state is specified via the "--enable-jdwp" flag
712 * in the spawn request.
713 *
714 * @param args non-null; zygote spawner args
715 */
716 protected static void applyDebuggerSystemProperty(ZygoteArguments args) {
717 if (RoSystemProperties.DEBUGGABLE) {
718 args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
719 }
720 }
721
722 /**
723 * Applies zygote security policy.
724 * Based on the credentials of the process issuing a zygote command:
725 * <ol>
726 * <li> uid 0 (root) may specify --invoke-with to launch Zygote with a
727 * wrapper command.
728 * <li> Any other uid may not specify any invoke-with argument.
729 * </ul>
730 *
731 * @param args non-null; zygote spawner arguments
732 * @param peer non-null; peer credentials
733 * @throws ZygoteSecurityException
734 */
735 protected static void applyInvokeWithSecurityPolicy(ZygoteArguments args, Credentials peer)
736 throws ZygoteSecurityException {
737 int peerUid = peer.getUid();
738
739 if (args.mInvokeWith != null && peerUid != 0
740 && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
Chris Wailesae937142019-01-24 12:57:33 -0800741 throw new ZygoteSecurityException("Peer is permitted to specify an "
742 + "explicit invoke-with wrapper command only for debuggable "
Chris Wailes2be26262019-01-11 16:14:43 -0800743 + "applications.");
744 }
745 }
746
747 /**
748 * Applies invoke-with system properties to the zygote arguments.
749 *
750 * @param args non-null; zygote args
751 */
752 protected static void applyInvokeWithSystemProperty(ZygoteArguments args) {
753 if (args.mInvokeWith == null && args.mNiceName != null) {
754 String property = "wrap." + args.mNiceName;
755 args.mInvokeWith = SystemProperties.get(property);
756 if (args.mInvokeWith != null && args.mInvokeWith.length() == 0) {
757 args.mInvokeWith = null;
758 }
759 }
760 }
761
762 /**
763 * Reads an argument list from the provided socket
764 * @return Argument list or null if EOF is reached
765 * @throws IOException passed straight through
766 */
767 static String[] readArgumentList(BufferedReader socketReader) throws IOException {
Chris Wailes2be26262019-01-11 16:14:43 -0800768 int argc;
769
770 try {
771 String argc_string = socketReader.readLine();
772
773 if (argc_string == null) {
774 // EOF reached.
775 return null;
776 }
777 argc = Integer.parseInt(argc_string);
778
779 } catch (NumberFormatException ex) {
780 Log.e("Zygote", "Invalid Zygote wire format: non-int at argc");
781 throw new IOException("Invalid wire format");
782 }
783
784 // See bug 1092107: large argc can be used for a DOS attack
785 if (argc > MAX_ZYGOTE_ARGC) {
786 throw new IOException("Max arg count exceeded");
787 }
788
789 String[] args = new String[argc];
790 for (int arg_index = 0; arg_index < argc; arg_index++) {
791 args[arg_index] = socketReader.readLine();
792 if (args[arg_index] == null) {
793 // We got an unexpected EOF.
794 throw new IOException("Truncated request");
795 }
796 }
797
798 return args;
799 }
800
Chris Wailescb0b37f2019-01-11 17:04:41 -0800801 /**
Chris Wailescb0b37f2019-01-11 17:04:41 -0800802 * Creates a managed LocalServerSocket object using a file descriptor
803 * created by an init.rc script. The init scripts that specify the
804 * sockets name can be found in system/core/rootdir. The socket is bound
805 * to the file system in the /dev/sockets/ directory, and the file
806 * descriptor is shared via the ANDROID_SOCKET_<socketName> environment
807 * variable.
808 */
809 static LocalServerSocket createManagedSocketFromInitSocket(String socketName) {
810 int fileDesc;
811 final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
812
813 try {
814 String env = System.getenv(fullSocketName);
815 fileDesc = Integer.parseInt(env);
816 } catch (RuntimeException ex) {
817 throw new RuntimeException("Socket unset or invalid: " + fullSocketName, ex);
818 }
819
820 try {
821 FileDescriptor fd = new FileDescriptor();
822 fd.setInt$(fileDesc);
823 return new LocalServerSocket(fd);
824 } catch (IOException ex) {
825 throw new RuntimeException(
826 "Error building socket from file descriptor: " + fileDesc, ex);
827 }
828 }
doheon1.lee885b7422016-01-20 13:07:27 +0900829
Orion Hodson46724e72018-10-19 13:05:33 +0100830 private static void callPostForkSystemServerHooks() {
831 // SystemServer specific post fork hooks run before child post fork hooks.
Neil Fuller555d8b72019-01-28 18:29:20 +0000832 ZygoteHooks.postForkSystemServer();
Orion Hodson46724e72018-10-19 13:05:33 +0100833 }
834
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100835 private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500836 boolean isZygote, String instructionSet) {
Neil Fuller555d8b72019-01-28 18:29:20 +0000837 ZygoteHooks.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100838 }
839
Narayan Kamathb49996d2017-02-06 20:24:08 +0000840 /**
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800841 * Resets the calling thread priority to the default value (Thread.NORM_PRIORITY
842 * or nice value 0). This updates both the priority value in java.lang.Thread and
843 * the nice value (setpriority).
Narayan Kamathb49996d2017-02-06 20:24:08 +0000844 */
Hiroshi Yamauchi1e3db872017-03-02 13:39:07 -0800845 static void resetNicePriority() {
846 Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
847 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100848
849 /**
850 * Executes "/system/bin/sh -c &lt;command&gt;" using the exec() system call.
851 * This method throws a runtime exception if exec() failed, otherwise, this
852 * method never returns.
853 *
854 * @param command The shell command to execute.
855 */
856 public static void execShell(String command) {
857 String[] args = { "/system/bin/sh", "-c", command };
858 try {
Elliott Hughes860c5912014-04-28 19:19:13 -0700859 Os.execv(args[0], args);
Narayan Kamath973b4662014-03-31 13:41:26 +0100860 } catch (ErrnoException e) {
861 throw new RuntimeException(e);
862 }
863 }
864
865 /**
866 * Appends quotes shell arguments to the specified string builder.
867 * The arguments are quoted using single-quotes, escaped if necessary,
868 * prefixed with a space, and appended to the command.
869 *
870 * @param command A string builder for the shell command being constructed.
871 * @param args An array of argument strings to be quoted and appended to the command.
872 * @see #execShell(String)
873 */
874 public static void appendQuotedShellArgs(StringBuilder command, String[] args) {
875 for (String arg : args) {
876 command.append(" '").append(arg.replace("'", "'\\''")).append("'");
877 }
878 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100879}