blob: 7a3f49a3efac3540f9990bafcc1d242521a4dbe7 [file] [log] [blame]
Narayan Kamath973b4662014-03-31 13:41:26 +01001/*
2 * Copyright (C) 2008 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
Colin Cross18cd9f52014-06-13 12:58:55 -070017#define LOG_TAG "Zygote"
Narayan Kamath973b4662014-03-31 13:41:26 +010018
19// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
20#include <sys/mount.h>
21#include <linux/fs.h>
22
Chris Wailesefc65b22018-10-26 12:41:54 -070023#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070024#include <list>
Chris Wailesefc65b22018-10-26 12:41:54 -070025#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080026#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070027#include <string>
28
Josh Gaod7951102018-06-26 16:05:12 -070029#include <android/fdsan.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070030#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080031#include <grp.h>
32#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070033#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070034#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010035#include <paths.h>
36#include <signal.h>
37#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070038#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040039#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070040#include <sys/personality.h>
41#include <sys/prctl.h>
42#include <sys/resource.h>
43#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070044#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070045#include <sys/types.h>
46#include <sys/utsname.h>
47#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080048#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070049
Andreas Gampe8dfa1782017-01-05 12:45:58 -080050#include "android-base/logging.h"
Minchan Kim696873e2018-06-27 11:32:40 +090051#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080052#include <android-base/file.h>
53#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070054#include <cutils/fs.h>
55#include <cutils/multiuser.h>
56#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070057#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070058#include <utils/String8.h>
59#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080060#include <seccomp_policy.h>
Howard Ro65e48ec2018-10-02 12:08:28 -070061#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070062#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070063
Andreas Gampeed6b9df2014-11-20 22:02:20 -080064#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070065#include <nativehelper/JNIHelp.h>
66#include <nativehelper/ScopedLocalRef.h>
67#include <nativehelper/ScopedPrimitiveArray.h>
68#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050069#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010070
jgu212eacd062014-09-10 06:55:07 -040071#include "nativebridge/native_bridge.h"
72
Narayan Kamath973b4662014-03-31 13:41:26 +010073namespace {
74
Chris Wailesefc65b22018-10-26 12:41:54 -070075using namespace std::placeholders;
76
Narayan Kamath973b4662014-03-31 13:41:26 +010077using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080078using android::base::StringPrintf;
79using android::base::WriteStringToFile;
Minchan Kim696873e2018-06-27 11:32:40 +090080using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010081
Andreas Gamped5758f62018-03-12 12:08:55 -070082#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
83 append(StringPrintf(__VA_ARGS__))
84
Narayan Kamath973b4662014-03-31 13:41:26 +010085static pid_t gSystemServerPid = 0;
86
87static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
88static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +010089static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +010090static jmethodID gCallPostForkChildHooks;
91
Victor Hsiehc8176ef2018-01-08 12:43:00 -080092static bool g_is_security_enforced = true;
93
Narayan Kamath973b4662014-03-31 13:41:26 +010094// Must match values in com.android.internal.os.Zygote.
95enum MountExternalKind {
96 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070097 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070098 MOUNT_EXTERNAL_READ = 2,
99 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +0100100};
101
Orion Hodson8d005a62018-12-05 12:28:53 +0000102// Must match values in com.android.internal.os.Zygote.
103enum RuntimeFlags : uint32_t {
104 DEBUG_ENABLE_JDWP = 1,
105};
106
Andreas Gampeb053cce2015-11-17 16:38:59 -0800107static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
108 std::ostringstream oss;
109 oss << __FILE__ << ":" << line << ": " << msg;
110 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100111}
112
113// This signal handler is for zygote mode, since the zygote must reap its children
114static void SigChldHandler(int /*signal_number*/) {
115 pid_t pid;
116 int status;
117
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700118 // It's necessary to save and restore the errno during this function.
119 // Since errno is stored per thread, changing it here modifies the errno
120 // on the thread on which this signal handler executes. If a signal occurs
121 // between a call and an errno check, it's possible to get the errno set
122 // here.
123 // See b/23572286 for extra information.
124 int saved_errno = errno;
125
Narayan Kamath973b4662014-03-31 13:41:26 +0100126 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
127 // Log process-death status that we care about. In general it is
128 // not safe to call LOG(...) from a signal handler because of
129 // possible reentrancy. However, we know a priori that the
130 // current implementation of LOG() is safe to call from a SIGCHLD
131 // handler in the zygote process. If the LOG() implementation
132 // changes its locking strategy or its use of syscalls within the
133 // lazy-init critical section, its use here may become unsafe.
134 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700135 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100136 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700137 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100138 if (WCOREDUMP(status)) {
139 ALOGI("Process %d dumped core.", pid);
140 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100141 }
142
143 // If the just-crashed process is the system_server, bring down zygote
144 // so that it is restarted by init and system server will be restarted
145 // from there.
146 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800147 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100148 kill(getpid(), SIGKILL);
149 }
150 }
151
Narayan Kamath160992d2014-04-14 14:46:07 +0100152 // Note that we shouldn't consider ECHILD an error because
153 // the secondary zygote might have no children left to wait for.
154 if (pid < 0 && errno != ECHILD) {
155 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100156 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700157
158 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100159}
160
yuanhao435e84b2018-01-15 15:37:02 +0800161// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
162// configured very late, because earlier in the runtime we may fork() and
163// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100164// have them be harvested immediately.
165//
yuanhao435e84b2018-01-15 15:37:02 +0800166// Ignore SIGHUP because all processes forked by the zygote are in the same
167// process group as the zygote and we don't want to be notified if we become
168// an orphaned group and have one or more stopped processes. This is not a
169// theoretical concern :
170// - we can become an orphaned group if one of our direct descendants forks
171// and is subsequently killed before its children.
172// - crash_dump routinely STOPs the process it's tracing.
173//
174// See issues b/71965619 and b/25567761 for further details.
175//
Narayan Kamath973b4662014-03-31 13:41:26 +0100176// This ends up being called repeatedly before each fork(), but there's
177// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800178static void SetSignalHandlers() {
179 struct sigaction sig_chld = {};
180 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100181
yuanhao435e84b2018-01-15 15:37:02 +0800182 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700183 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100184 }
yuanhao435e84b2018-01-15 15:37:02 +0800185
186 struct sigaction sig_hup = {};
187 sig_hup.sa_handler = SIG_IGN;
188 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
189 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
190 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100191}
192
193// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800194static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100195 struct sigaction sa;
196 memset(&sa, 0, sizeof(sa));
197 sa.sa_handler = SIG_DFL;
198
yuanhao435e84b2018-01-15 15:37:02 +0800199 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700200 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100201 }
202}
203
204// Calls POSIX setgroups() using the int[] object as an argument.
205// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700206static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100207 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700208 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100209 }
210
211 ScopedIntArrayRO gids(env, javaGids);
212 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700213 *error_msg = CREATE_ERROR("Getting gids int array failed");
214 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100215 }
216 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
217 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700218 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
219 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100220 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700221
222 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100223}
224
225// Sets the resource limits via setrlimit(2) for the values in the
226// two-dimensional array of integers that's passed in. The second dimension
227// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
228// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700229static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100230 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700231 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100232 }
233
234 rlimit rlim;
235 memset(&rlim, 0, sizeof(rlim));
236
237 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
238 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
239 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
240 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700241 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
242 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100243 }
244
245 rlim.rlim_cur = javaRlimit[1];
246 rlim.rlim_max = javaRlimit[2];
247
248 int rc = setrlimit(javaRlimit[0], &rlim);
249 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700250 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800251 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700252 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100253 }
254 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700255
256 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100257}
258
Orion Hodson8d005a62018-12-05 12:28:53 +0000259static void EnableDebugger() {
260 // To let a non-privileged gdbserver attach to this
261 // process, we must set our dumpable flag.
262 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
263 ALOGE("prctl(PR_SET_DUMPABLE) failed");
264 }
265
266 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
267 // is enabled (see kernel/Documentation/security/Yama.txt).
268 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
269 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
270 // case since it's expected behaviour.
271 if (errno != EINVAL) {
272 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
273 }
274 }
275
276 // We don't want core dumps, though, so set the soft limit on core dump size
277 // to 0 without changing the hard limit.
278 rlimit rl;
279 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
280 ALOGE("getrlimit(RLIMIT_CORE) failed");
281 } else {
282 rl.rlim_cur = 0;
283 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
284 ALOGE("setrlimit(RLIMIT_CORE) failed");
285 }
286 }
287}
288
Narayan Kamath973b4662014-03-31 13:41:26 +0100289// The debug malloc library needs to know whether it's the zygote or a child.
290extern "C" int gMallocLeakZygoteChild;
291
Christopher Ferris76de39e2017-06-20 16:13:40 -0700292static void PreApplicationInit() {
293 // The child process sets this to indicate it's not the zygote.
294 gMallocLeakZygoteChild = 1;
295
296 // Set the jemalloc decay time to 1.
297 mallopt(M_DECAY_TIME, 1);
298}
299
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800300static void SetUpSeccompFilter(uid_t uid) {
301 if (!g_is_security_enforced) {
302 ALOGI("seccomp disabled by setenforce 0");
303 return;
304 }
305
306 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700307 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800308 set_app_seccomp_filter();
309 } else {
310 set_system_seccomp_filter();
311 }
312}
313
Andreas Gamped5758f62018-03-12 12:08:55 -0700314static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100315 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
316 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700317 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
318 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100319 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700320 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100321}
322
Andreas Gamped5758f62018-03-12 12:08:55 -0700323static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100324 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
325 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
326 if (rc == -1) {
327 if (errno == EINVAL) {
328 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
329 "your kernel is compiled with file capabilities support");
330 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700331 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
332 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100333 }
334 }
335 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700336 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100337}
338
Andreas Gamped5758f62018-03-12 12:08:55 -0700339static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800340 __user_cap_header_struct capheader;
341 memset(&capheader, 0, sizeof(capheader));
342 capheader.version = _LINUX_CAPABILITY_VERSION_3;
343 capheader.pid = 0;
344
345 __user_cap_data_struct capdata[2];
346 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700347 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
348 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800349 }
350
351 capdata[0].inheritable = inheritable;
352 capdata[1].inheritable = inheritable >> 32;
353
354 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700355 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
356 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800357 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700358
359 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800360}
361
Andreas Gamped5758f62018-03-12 12:08:55 -0700362static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
363 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100364 __user_cap_header_struct capheader;
365 memset(&capheader, 0, sizeof(capheader));
366 capheader.version = _LINUX_CAPABILITY_VERSION_3;
367 capheader.pid = 0;
368
369 __user_cap_data_struct capdata[2];
370 memset(&capdata, 0, sizeof(capdata));
371 capdata[0].effective = effective;
372 capdata[1].effective = effective >> 32;
373 capdata[0].permitted = permitted;
374 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800375 capdata[0].inheritable = inheritable;
376 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100377
378 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700379 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
380 "failed: %s", permitted, effective, inheritable, strerror(errno));
381 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100382 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700383 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100384}
385
Andreas Gamped5758f62018-03-12 12:08:55 -0700386static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100387 errno = -set_sched_policy(0, SP_DEFAULT);
388 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700389 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
390 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100391 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700392 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100393}
394
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700395static int UnmountTree(const char* path) {
396 size_t path_len = strlen(path);
397
398 FILE* fp = setmntent("/proc/mounts", "r");
399 if (fp == NULL) {
400 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
401 return -errno;
402 }
403
404 // Some volumes can be stacked on each other, so force unmount in
405 // reverse order to give us the best chance of success.
406 std::list<std::string> toUnmount;
407 mntent* mentry;
408 while ((mentry = getmntent(fp)) != NULL) {
409 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
410 toUnmount.push_front(std::string(mentry->mnt_dir));
411 }
412 }
413 endmntent(fp);
414
415 for (auto path : toUnmount) {
416 if (umount2(path.c_str(), MNT_DETACH)) {
417 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
418 }
419 }
420 return 0;
421}
422
Narayan Kamath973b4662014-03-31 13:41:26 +0100423// Create a private mount namespace and bind mount appropriate emulated
424// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700425static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Andreas Gamped5758f62018-03-12 12:08:55 -0700426 bool force_mount_namespace, std::string* error_msg) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700427 // See storage config details at http://source.android.com/tech/storage/
428
Jeff Sharkey9527b222015-06-24 15:24:48 -0700429 String8 storageSource;
430 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700431 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700432 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700433 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700434 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700435 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500436 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700437 // Sane default of no storage visible
438 return true;
439 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400440
441 // Create a second private mount namespace for our process
442 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700443 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400444 return false;
445 }
446
Robert Sesek06f39302017-03-20 17:30:05 -0400447 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
448 if (mount_mode == MOUNT_EXTERNAL_NONE) {
449 return true;
450 }
451
Jeff Sharkey9527b222015-06-24 15:24:48 -0700452 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
453 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700454 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
455 storageSource.string(),
456 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700457 return false;
458 }
459
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700460 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700461 userid_t user_id = multiuser_get_user_id(uid);
462 const String8 userSource(String8::format("/mnt/user/%d", user_id));
463 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700464 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
Jeff Sharkey9527b222015-06-24 15:24:48 -0700465 return false;
466 }
467 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
468 NULL, MS_BIND, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700469 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
470 userSource.string(),
471 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700472 return false;
473 }
474
Narayan Kamath973b4662014-03-31 13:41:26 +0100475 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100476}
477
Narayan Kamath973b4662014-03-31 13:41:26 +0100478static bool NeedsNoRandomizeWorkaround() {
479#if !defined(__arm__)
480 return false;
481#else
482 int major;
483 int minor;
484 struct utsname uts;
485 if (uname(&uts) == -1) {
486 return false;
487 }
488
489 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
490 return false;
491 }
492
493 // Kernels before 3.4.* need the workaround.
494 return (major < 3) || ((major == 3) && (minor < 4));
495#endif
496}
Narayan Kamath973b4662014-03-31 13:41:26 +0100497
498// Utility to close down the Zygote socket file descriptors while
499// the child is still running as root with Zygote's privileges. Each
500// descriptor (if any) is closed via dup2(), replacing it with a valid
501// (open) descriptor to /dev/null.
502
Andreas Gamped5758f62018-03-12 12:08:55 -0700503static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100504 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700505 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100506 }
507 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200508 ScopedIntArrayRO ar(env, fdsToClose);
509 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700510 *error_msg = "Bad fd array";
511 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100512 }
513 jsize i;
514 int devnull;
515 for (i = 0; i < count; i++) {
516 devnull = open("/dev/null", O_RDWR);
517 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700518 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
519 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100520 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700521 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100522 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700523 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
524 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100525 }
526 close(devnull);
527 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700528 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100529}
530
531void SetThreadName(const char* thread_name) {
532 bool hasAt = false;
533 bool hasDot = false;
534 const char* s = thread_name;
535 while (*s) {
536 if (*s == '.') {
537 hasDot = true;
538 } else if (*s == '@') {
539 hasAt = true;
540 }
541 s++;
542 }
543 const int len = s - thread_name;
544 if (len < 15 || hasAt || !hasDot) {
545 s = thread_name;
546 } else {
547 s = thread_name + len - 15;
548 }
549 // pthread_setname_np fails rather than truncating long strings.
550 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
551 strlcpy(buf, s, sizeof(buf)-1);
552 errno = pthread_setname_np(pthread_self(), buf);
553 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700554 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100555 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800556 // Update base::logging default tag.
557 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100558}
559
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100560// The list of open zygote file descriptors.
561static FileDescriptorTable* gOpenFdTable = NULL;
562
Andreas Gamped5758f62018-03-12 12:08:55 -0700563static bool FillFileDescriptorVector(JNIEnv* env,
Chris Wailesefc65b22018-10-26 12:41:54 -0700564 jintArray managed_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700565 std::vector<int>* fds,
566 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800567 CHECK(fds != nullptr);
Chris Wailesefc65b22018-10-26 12:41:54 -0700568 if (managed_fds != nullptr) {
569 ScopedIntArrayRO ar(env, managed_fds);
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800570 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700571 *error_msg = "Bad fd array";
572 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800573 }
574 fds->reserve(ar.size());
575 for (size_t i = 0; i < ar.size(); ++i) {
576 fds->push_back(ar[i]);
577 }
578 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700579 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800580}
581
Chris Wailesefc65b22018-10-26 12:41:54 -0700582[[noreturn]]
583static void ZygoteFailure(JNIEnv* env,
584 const char* process_name,
585 jstring managed_process_name,
586 const std::string& msg) {
587 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
588 if (managed_process_name != nullptr) {
589 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
590 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
591 process_name = scoped_managed_process_name_ptr->c_str();
592 }
593 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700594
Chris Wailesefc65b22018-10-26 12:41:54 -0700595 const std::string& error_msg =
596 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
597
598 env->FatalError(error_msg.c_str());
599 __builtin_unreachable();
600}
601
602static std::optional<std::string> ExtractJString(JNIEnv* env,
603 const char* process_name,
604 jstring managed_process_name,
605 jstring managed_string) {
606 if (managed_string == nullptr) {
607 return std::optional<std::string>();
608 } else {
609 ScopedUtfChars scoped_string_chars(env, managed_string);
610
611 if (scoped_string_chars.c_str() != nullptr) {
612 return std::optional<std::string>(scoped_string_chars.c_str());
613 } else {
614 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700615 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700616 }
617}
618
619// Utility routine to fork a zygote.
620static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
621 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore) {
622 SetSignalHandlers();
623
624 // Block SIGCHLD prior to fork.
625 sigset_t sigchld;
626 sigemptyset(&sigchld);
627 sigaddset(&sigchld, SIGCHLD);
628
629 // Curry a failure function.
630 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
631 nullptr, _1);
632
633 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
634 // log, which would result in the logging FDs we close being reopened.
635 // This would cause failures because the FDs are not whitelisted.
636 //
637 // Note that the zygote process is single threaded at this point.
638 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
639 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
640 }
641
642 // Close any logging related FDs before we start evaluating the list of
643 // file descriptors.
644 __android_log_close();
645 stats_log_close();
646
647 // If this is the first fork for this zygote, create the open FD table. If
648 // it isn't, we just need to check whether the list of open files has changed
649 // (and it shouldn't in the normal case).
650 std::string error_msg;
651 std::vector<int> fds_to_ignore;
652 if (!FillFileDescriptorVector(env, managed_fds_to_ignore, &fds_to_ignore, &error_msg)) {
653 fail_fn(error_msg);
654 }
655
656 if (gOpenFdTable == nullptr) {
657 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
658 if (gOpenFdTable == nullptr) {
659 fail_fn(error_msg);
David Sehrde8d0bd2018-06-22 10:45:36 -0700660 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700661 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
662 fail_fn(error_msg);
663 }
664
665 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
666
667 pid_t pid = fork();
668
669 if (pid == 0) {
670 // The child process.
671 PreApplicationInit();
672
673 // Clean up any descriptors which must be closed immediately
674 if (!DetachDescriptors(env, managed_fds_to_close, &error_msg)) {
675 fail_fn(error_msg);
676 }
677
678 // Re-open all remaining open file descriptors so that they aren't shared
679 // with the zygote across a fork.
680 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
681 fail_fn(error_msg);
682 }
683
684 // Turn fdsan back on.
685 android_fdsan_set_error_level(fdsan_error_level);
686 }
687
688 // We blocked SIGCHLD prior to a fork, we unblock it here.
689 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
690 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
691 }
692 return pid;
693}
694
695// Utility routine to specialize a zygote child process.
696static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
697 jint runtime_flags, jobjectArray rlimits,
698 jlong permitted_capabilities, jlong effective_capabilities,
699 jint mount_external, jstring managed_se_info,
700 jstring managed_nice_name, bool is_system_server,
701 bool is_child_zygote, jstring managed_instruction_set,
702 jstring managed_app_data_dir) {
703 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
704 managed_nice_name, _1);
705 auto extract_fn = std::bind(ExtractJString, env, is_system_server ? "system_server" : "zygote",
706 managed_nice_name, _1);
707
708 auto se_info = extract_fn(managed_se_info);
709 auto nice_name = extract_fn(managed_nice_name);
710 auto instruction_set = extract_fn(managed_instruction_set);
711 auto app_data_dir = extract_fn(managed_app_data_dir);
712
713 std::string error_msg;
David Sehrde8d0bd2018-06-22 10:45:36 -0700714
715 // Keep capabilities across UID change, unless we're staying root.
716 if (uid != 0) {
717 if (!EnableKeepCapabilities(&error_msg)) {
718 fail_fn(error_msg);
719 }
720 }
721
Chris Wailesefc65b22018-10-26 12:41:54 -0700722 if (!SetInheritable(permitted_capabilities, &error_msg)) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700723 fail_fn(error_msg);
724 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700725
David Sehrde8d0bd2018-06-22 10:45:36 -0700726 if (!DropCapabilitiesBoundingSet(&error_msg)) {
727 fail_fn(error_msg);
728 }
729
Chris Wailesefc65b22018-10-26 12:41:54 -0700730 bool use_native_bridge = !is_system_server &&
731 instruction_set.has_value() &&
732 android::NativeBridgeAvailable() &&
733 android::NeedsNativeBridge(instruction_set.value().c_str());
734
735 if (use_native_bridge && !app_data_dir.has_value()) {
736 // The app_data_dir variable should never be empty if we need to use a
737 // native bridge. In general, app_data_dir will never be empty for normal
738 // applications. It can only happen in special cases (for isolated
739 // processes which are not associated with any app). These are launched by
740 // the framework and should not be emulated anyway.
David Sehrde8d0bd2018-06-22 10:45:36 -0700741 use_native_bridge = false;
Chris Wailesefc65b22018-10-26 12:41:54 -0700742 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700743 }
744
745 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg)) {
746 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
747 if (errno == ENOTCONN || errno == EROFS) {
748 // When device is actively encrypting, we get ENOTCONN here
749 // since FUSE was mounted before the framework restarted.
750 // When encrypted device is booting, we get EROFS since
751 // FUSE hasn't been created yet by init.
752 // In either case, continue without external storage.
753 } else {
754 fail_fn(error_msg);
755 }
756 }
757
758 // If this zygote isn't root, it won't be able to create a process group,
759 // since the directory is owned by root.
760 if (!is_system_server && getuid() == 0) {
761 int rc = createProcessGroup(uid, getpid());
762 if (rc != 0) {
763 if (rc == -EROFS) {
764 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
765 } else {
766 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
767 }
768 }
769 }
770
Chris Wailesefc65b22018-10-26 12:41:54 -0700771 if (!SetGids(env, gids, &error_msg)) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700772 fail_fn(error_msg);
773 }
774
Chris Wailesefc65b22018-10-26 12:41:54 -0700775 if (!SetRLimits(env, rlimits, &error_msg)) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700776 fail_fn(error_msg);
777 }
778
779 if (use_native_bridge) {
Chris Wailesefc65b22018-10-26 12:41:54 -0700780 // Due to the logic behind use_native_bridge we know that both app_data_dir
781 // and instruction_set contain values.
782 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
783 instruction_set.value().c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700784 }
785
Chris Wailesefc65b22018-10-26 12:41:54 -0700786 if (setresgid(gid, gid, gid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700787 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
788 }
789
Chris Wailesefc65b22018-10-26 12:41:54 -0700790 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
791 // before changing uid from 0, which clears capabilities. The other
792 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
793 // breaks SELinux domain transition (see b/71859146). As the result,
794 // privileged syscalls used below still need to be accessible in app process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700795 SetUpSeccompFilter(uid);
796
Chris Wailesefc65b22018-10-26 12:41:54 -0700797 if (setresuid(uid, uid, uid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700798 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
799 }
800
801 // The "dumpable" flag of a process, which controls core dump generation, is
802 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
803 // user or group ID changes. See proc(5) for possible values. In most cases,
804 // the value is 0, so core dumps are disabled for zygote children. However,
805 // when running in a Chrome OS container, the value is already set to 2,
806 // which allows the external crash reporter to collect all core dumps. Since
807 // only system crashes are interested, core dump is disabled for app
808 // processes. This also ensures compliance with CTS.
809 int dumpable = prctl(PR_GET_DUMPABLE);
810 if (dumpable == -1) {
811 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
812 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
813 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700814
David Sehrde8d0bd2018-06-22 10:45:36 -0700815 if (dumpable == 2 && uid >= AID_APP) {
816 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
817 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
818 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
819 }
820 }
821
Orion Hodson8d005a62018-12-05 12:28:53 +0000822 // Set process properties to enable debugging if required.
823 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
824 EnableDebugger();
825 }
826
David Sehrde8d0bd2018-06-22 10:45:36 -0700827 if (NeedsNoRandomizeWorkaround()) {
828 // Work around ARM kernel ASLR lossage (http://b/5817320).
829 int old_personality = personality(0xffffffff);
830 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
831 if (new_personality == -1) {
832 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
833 }
834 }
835
Chris Wailesefc65b22018-10-26 12:41:54 -0700836 if (!SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities,
David Sehrde8d0bd2018-06-22 10:45:36 -0700837 &error_msg)) {
838 fail_fn(error_msg);
839 }
840
841 if (!SetSchedulerPolicy(&error_msg)) {
842 fail_fn(error_msg);
843 }
844
Chris Wailesefc65b22018-10-26 12:41:54 -0700845 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
846 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
847
848 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
849 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
850 uid, is_system_server, se_info_ptr, nice_name_ptr));
David Sehrde8d0bd2018-06-22 10:45:36 -0700851 }
852
853 // Make it easier to debug audit logs by setting the main thread's name to the
854 // nice name rather than "app_process".
Chris Wailesefc65b22018-10-26 12:41:54 -0700855 if (nice_name.has_value()) {
856 SetThreadName(nice_name.value().c_str());
857 } else if (is_system_server) {
858 SetThreadName("system_server");
David Sehrde8d0bd2018-06-22 10:45:36 -0700859 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700860
861 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
862 UnsetChldSignalHandler();
863
Orion Hodson46724e72018-10-19 13:05:33 +0100864 if (is_system_server) {
865 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
866 if (env->ExceptionCheck()) {
867 fail_fn("Error calling post fork system server hooks.");
868 }
869 // TODO(oth): Remove hardcoded label here (b/117874058).
870 static const char* kSystemServerLabel = "u:r:system_server:s0";
871 if (selinux_android_setcon(kSystemServerLabel) != 0) {
872 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
873 }
874 }
875
David Sehrde8d0bd2018-06-22 10:45:36 -0700876 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
Chris Wailesefc65b22018-10-26 12:41:54 -0700877 is_system_server, is_child_zygote, managed_instruction_set);
878
David Sehrde8d0bd2018-06-22 10:45:36 -0700879 if (env->ExceptionCheck()) {
880 fail_fn("Error calling post fork hooks.");
881 }
882}
883
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700884static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
885 __user_cap_header_struct capheader;
886 memset(&capheader, 0, sizeof(capheader));
887 capheader.version = _LINUX_CAPABILITY_VERSION_3;
888 capheader.pid = 0;
889
890 __user_cap_data_struct capdata[2];
891 if (capget(&capheader, &capdata[0]) == -1) {
892 ALOGE("capget failed: %s", strerror(errno));
893 RuntimeAbort(env, __LINE__, "capget failed");
894 }
895
Chris Wailesefc65b22018-10-26 12:41:54 -0700896 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
897}
898
899static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
900 bool is_child_zygote) {
901 jlong capabilities = 0;
902
903 /*
904 * Grant the following capabilities to the Bluetooth user:
905 * - CAP_WAKE_ALARM
906 * - CAP_NET_RAW
907 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
908 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
909 */
910
911 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
912 capabilities |= (1LL << CAP_WAKE_ALARM);
913 capabilities |= (1LL << CAP_NET_RAW);
914 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
915 capabilities |= (1LL << CAP_SYS_NICE);
916 }
917
918 /*
919 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
920 */
921
922 bool gid_wakelock_found = false;
923 if (gid == AID_WAKELOCK) {
924 gid_wakelock_found = true;
925 } else if (gids != nullptr) {
926 jsize gids_num = env->GetArrayLength(gids);
927 ScopedIntArrayRO native_gid_proxy(env, gids);
928
929 if (native_gid_proxy.get() == nullptr) {
930 RuntimeAbort(env, __LINE__, "Bad gids array");
931 }
932
933 for (int gid_index = gids_num; --gids_num >= 0;) {
934 if (native_gid_proxy[gid_index] == AID_WAKELOCK) {
935 gid_wakelock_found = true;
936 break;
937 }
938 }
939 }
940
941 if (gid_wakelock_found) {
942 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
943 }
944
945 /*
946 * Grant child Zygote processes the following capabilities:
947 * - CAP_SETUID (change UID of child processes)
948 * - CAP_SETGID (change GID of child processes)
949 * - CAP_SETPCAP (change capabilities of child processes)
950 */
951
952 if (is_child_zygote) {
953 capabilities |= (1LL << CAP_SETUID);
954 capabilities |= (1LL << CAP_SETGID);
955 capabilities |= (1LL << CAP_SETPCAP);
956 }
957
958 /*
959 * Containers run without some capabilities, so drop any caps that are not
960 * available.
961 */
962
963 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700964}
Narayan Kamath973b4662014-03-31 13:41:26 +0100965} // anonymous namespace
966
967namespace android {
968
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800969static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesefc65b22018-10-26 12:41:54 -0700970 // security_getenforce is not allowed on app process. Initialize and cache
971 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800972 g_is_security_enforced = security_getenforce();
973}
974
Christopher Ferris76de39e2017-06-20 16:13:40 -0700975static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
976 PreApplicationInit();
977}
978
Narayan Kamath973b4662014-03-31 13:41:26 +0100979static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
980 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100981 jint runtime_flags, jobjectArray rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -0700982 jint mount_external, jstring se_info, jstring nice_name,
983 jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote,
984 jstring instruction_set, jstring app_data_dir) {
985 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800986
Chris Wailesefc65b22018-10-26 12:41:54 -0700987 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -0700988 if (pid == 0) {
989 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
990 capabilities, capabilities,
Chris Wailesefc65b22018-10-26 12:41:54 -0700991 mount_external, se_info, nice_name, false,
992 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
David Sehrde8d0bd2018-06-22 10:45:36 -0700993 }
994 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100995}
996
997static jint com_android_internal_os_Zygote_nativeForkSystemServer(
998 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesefc65b22018-10-26 12:41:54 -0700999 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1000 jlong effective_capabilities) {
1001 pid_t pid = ForkCommon(env, true,
1002 /* managed_fds_to_close= */ nullptr,
1003 /* managed_fds_to_ignore= */ nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001004 if (pid == 0) {
1005 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -07001006 permitted_capabilities, effective_capabilities,
1007 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1008 false, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001009 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001010 // The zygote process checks whether the child process has died or not.
1011 ALOGI("System server process %d has been created", pid);
1012 gSystemServerPid = pid;
1013 // There is a slight window that the system server process has crashed
1014 // but it went unnoticed because we haven't published its pid yet. So
1015 // we recheck here just to make sure that all is well.
1016 int status;
1017 if (waitpid(pid, &status, WNOHANG) == pid) {
1018 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001019 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001020 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001021
Minchan Kim696873e2018-06-27 11:32:40 +09001022 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
1023 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
1024 if (per_app_memcg) {
1025 // Assign system_server to the correct memory cgroup.
1026 // Not all devices mount /dev/memcg so check for the file first
1027 // to avoid unnecessarily printing errors and denials in the logs.
1028 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -08001029 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim696873e2018-06-27 11:32:40 +09001030 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
1031 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001032 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001033 }
1034 return pid;
1035}
1036
Robert Sesek54e387d2016-12-02 17:27:50 -05001037static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1038 JNIEnv* env, jclass, jstring path) {
1039 ScopedUtfChars path_native(env, path);
1040 const char* path_cstr = path_native.c_str();
1041 if (!path_cstr) {
Chris Wailesefc65b22018-10-26 12:41:54 -07001042 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001043 }
1044 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1045}
1046
doheon1.lee885b7422016-01-20 13:07:27 +09001047static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1048 // Zygote process unmount root storage space initially before every child processes are forked.
1049 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001050 // and no need unmount storage operation in MountEmulatedStorage method.
1051 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1052
1053 // See storage config details at http://source.android.com/tech/storage/
1054 // Create private mount namespace shared by all children
1055 if (unshare(CLONE_NEWNS) == -1) {
1056 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1057 return;
1058 }
1059
1060 // Mark rootfs as being a slave so that changes from default
1061 // namespace only flow into our children.
1062 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1063 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1064 return;
1065 }
1066
1067 // Create a staging tmpfs that is shared by our children; they will
1068 // bind mount storage into their respective private namespaces, which
1069 // are isolated from each other.
1070 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1071 if (target_base != nullptr) {
1072#define STRINGIFY_UID(x) __STRING(x)
1073 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1074 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1075 ALOGE("Failed to mount tmpfs to %s", target_base);
1076 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1077 return;
1078 }
1079#undef STRINGIFY_UID
1080 }
doheon1.lee885b7422016-01-20 13:07:27 +09001081
1082 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001083}
1084
Daniel Micay76f6a862015-09-19 17:31:01 -04001085static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001086 { "nativeSecurityInit", "()V",
1087 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001088 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001089 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001090 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1091 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001092 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001093 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1094 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001095 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001096 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1097 { "nativePreApplicationInit", "()V",
1098 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001099};
1100
1101int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001102 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001103 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1104 "callPostForkSystemServerHooks",
1105 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001106 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001107 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001108
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001109 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001110}
1111} // namespace android