blob: caf4e4b48e61c43930adc0573677ff8bfed66614 [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
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070023#include <list>
Andreas Gampeb053cce2015-11-17 16:38:59 -080024#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070025#include <string>
26
Colin Cross18cd9f52014-06-13 12:58:55 -070027#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080028#include <grp.h>
29#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070030#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070031#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010032#include <paths.h>
33#include <signal.h>
34#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070035#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040036#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070037#include <sys/personality.h>
38#include <sys/prctl.h>
39#include <sys/resource.h>
40#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070041#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070042#include <sys/types.h>
43#include <sys/utsname.h>
44#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080045#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070046
Andreas Gampe8dfa1782017-01-05 12:45:58 -080047#include "android-base/logging.h"
Carmen Jacksondd401252017-02-23 15:21:10 -080048#include <android-base/file.h>
49#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070050#include <cutils/fs.h>
51#include <cutils/multiuser.h>
52#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070053#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070054#include <utils/String8.h>
55#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080056#include <seccomp_policy.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070057#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070058
Andreas Gampeed6b9df2014-11-20 22:02:20 -080059#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070060#include <nativehelper/JNIHelp.h>
61#include <nativehelper/ScopedLocalRef.h>
62#include <nativehelper/ScopedPrimitiveArray.h>
63#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050064#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010065
jgu212eacd062014-09-10 06:55:07 -040066#include "nativebridge/native_bridge.h"
67
Narayan Kamath973b4662014-03-31 13:41:26 +010068namespace {
69
70using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080071using android::base::StringPrintf;
72using android::base::WriteStringToFile;
Narayan Kamath973b4662014-03-31 13:41:26 +010073
Andreas Gamped5758f62018-03-12 12:08:55 -070074#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
75 append(StringPrintf(__VA_ARGS__))
76
Narayan Kamath973b4662014-03-31 13:41:26 +010077static pid_t gSystemServerPid = 0;
78
79static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
80static jclass gZygoteClass;
81static jmethodID gCallPostForkChildHooks;
82
Victor Hsiehc8176ef2018-01-08 12:43:00 -080083static bool g_is_security_enforced = true;
84
Narayan Kamath973b4662014-03-31 13:41:26 +010085// Must match values in com.android.internal.os.Zygote.
86enum MountExternalKind {
87 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070088 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070089 MOUNT_EXTERNAL_READ = 2,
90 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010091};
92
Andreas Gampeb053cce2015-11-17 16:38:59 -080093static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
94 std::ostringstream oss;
95 oss << __FILE__ << ":" << line << ": " << msg;
96 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +010097}
98
99// This signal handler is for zygote mode, since the zygote must reap its children
100static void SigChldHandler(int /*signal_number*/) {
101 pid_t pid;
102 int status;
103
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700104 // It's necessary to save and restore the errno during this function.
105 // Since errno is stored per thread, changing it here modifies the errno
106 // on the thread on which this signal handler executes. If a signal occurs
107 // between a call and an errno check, it's possible to get the errno set
108 // here.
109 // See b/23572286 for extra information.
110 int saved_errno = errno;
111
Narayan Kamath973b4662014-03-31 13:41:26 +0100112 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
113 // Log process-death status that we care about. In general it is
114 // not safe to call LOG(...) from a signal handler because of
115 // possible reentrancy. However, we know a priori that the
116 // current implementation of LOG() is safe to call from a SIGCHLD
117 // handler in the zygote process. If the LOG() implementation
118 // changes its locking strategy or its use of syscalls within the
119 // lazy-init critical section, its use here may become unsafe.
120 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700121 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100122 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700123 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100124 if (WCOREDUMP(status)) {
125 ALOGI("Process %d dumped core.", pid);
126 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100127 }
128
129 // If the just-crashed process is the system_server, bring down zygote
130 // so that it is restarted by init and system server will be restarted
131 // from there.
132 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800133 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100134 kill(getpid(), SIGKILL);
135 }
136 }
137
Narayan Kamath160992d2014-04-14 14:46:07 +0100138 // Note that we shouldn't consider ECHILD an error because
139 // the secondary zygote might have no children left to wait for.
140 if (pid < 0 && errno != ECHILD) {
141 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100142 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700143
144 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100145}
146
yuanhao435e84b2018-01-15 15:37:02 +0800147// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
148// configured very late, because earlier in the runtime we may fork() and
149// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100150// have them be harvested immediately.
151//
yuanhao435e84b2018-01-15 15:37:02 +0800152// Ignore SIGHUP because all processes forked by the zygote are in the same
153// process group as the zygote and we don't want to be notified if we become
154// an orphaned group and have one or more stopped processes. This is not a
155// theoretical concern :
156// - we can become an orphaned group if one of our direct descendants forks
157// and is subsequently killed before its children.
158// - crash_dump routinely STOPs the process it's tracing.
159//
160// See issues b/71965619 and b/25567761 for further details.
161//
Narayan Kamath973b4662014-03-31 13:41:26 +0100162// This ends up being called repeatedly before each fork(), but there's
163// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800164static void SetSignalHandlers() {
165 struct sigaction sig_chld = {};
166 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100167
yuanhao435e84b2018-01-15 15:37:02 +0800168 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700169 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100170 }
yuanhao435e84b2018-01-15 15:37:02 +0800171
172 struct sigaction sig_hup = {};
173 sig_hup.sa_handler = SIG_IGN;
174 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
175 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
176 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100177}
178
179// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800180static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100181 struct sigaction sa;
182 memset(&sa, 0, sizeof(sa));
183 sa.sa_handler = SIG_DFL;
184
yuanhao435e84b2018-01-15 15:37:02 +0800185 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700186 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100187 }
188}
189
190// Calls POSIX setgroups() using the int[] object as an argument.
191// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700192static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100193 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700194 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100195 }
196
197 ScopedIntArrayRO gids(env, javaGids);
198 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700199 *error_msg = CREATE_ERROR("Getting gids int array failed");
200 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100201 }
202 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
203 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700204 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
205 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100206 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700207
208 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100209}
210
211// Sets the resource limits via setrlimit(2) for the values in the
212// two-dimensional array of integers that's passed in. The second dimension
213// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
214// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700215static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100216 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700217 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100218 }
219
220 rlimit rlim;
221 memset(&rlim, 0, sizeof(rlim));
222
223 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
224 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
225 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
226 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700227 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
228 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100229 }
230
231 rlim.rlim_cur = javaRlimit[1];
232 rlim.rlim_max = javaRlimit[2];
233
234 int rc = setrlimit(javaRlimit[0], &rlim);
235 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700236 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800237 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700238 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100239 }
240 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700241
242 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100243}
244
Narayan Kamath973b4662014-03-31 13:41:26 +0100245// The debug malloc library needs to know whether it's the zygote or a child.
246extern "C" int gMallocLeakZygoteChild;
247
Christopher Ferris76de39e2017-06-20 16:13:40 -0700248static void PreApplicationInit() {
249 // The child process sets this to indicate it's not the zygote.
250 gMallocLeakZygoteChild = 1;
251
252 // Set the jemalloc decay time to 1.
253 mallopt(M_DECAY_TIME, 1);
254}
255
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800256static void SetUpSeccompFilter(uid_t uid) {
257 if (!g_is_security_enforced) {
258 ALOGI("seccomp disabled by setenforce 0");
259 return;
260 }
261
262 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700263 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800264 set_app_seccomp_filter();
265 } else {
266 set_system_seccomp_filter();
267 }
268}
269
Andreas Gamped5758f62018-03-12 12:08:55 -0700270static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100271 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
272 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700273 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
274 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100275 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700276 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100277}
278
Andreas Gamped5758f62018-03-12 12:08:55 -0700279static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100280 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
281 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
282 if (rc == -1) {
283 if (errno == EINVAL) {
284 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
285 "your kernel is compiled with file capabilities support");
286 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700287 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
288 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100289 }
290 }
291 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700292 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100293}
294
Andreas Gamped5758f62018-03-12 12:08:55 -0700295static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800296 __user_cap_header_struct capheader;
297 memset(&capheader, 0, sizeof(capheader));
298 capheader.version = _LINUX_CAPABILITY_VERSION_3;
299 capheader.pid = 0;
300
301 __user_cap_data_struct capdata[2];
302 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700303 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
304 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800305 }
306
307 capdata[0].inheritable = inheritable;
308 capdata[1].inheritable = inheritable >> 32;
309
310 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700311 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
312 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800313 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700314
315 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800316}
317
Andreas Gamped5758f62018-03-12 12:08:55 -0700318static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
319 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100320 __user_cap_header_struct capheader;
321 memset(&capheader, 0, sizeof(capheader));
322 capheader.version = _LINUX_CAPABILITY_VERSION_3;
323 capheader.pid = 0;
324
325 __user_cap_data_struct capdata[2];
326 memset(&capdata, 0, sizeof(capdata));
327 capdata[0].effective = effective;
328 capdata[1].effective = effective >> 32;
329 capdata[0].permitted = permitted;
330 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800331 capdata[0].inheritable = inheritable;
332 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100333
334 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700335 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
336 "failed: %s", permitted, effective, inheritable, strerror(errno));
337 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100338 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700339 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100340}
341
Andreas Gamped5758f62018-03-12 12:08:55 -0700342static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100343 errno = -set_sched_policy(0, SP_DEFAULT);
344 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700345 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
346 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100347 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700348 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100349}
350
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700351static int UnmountTree(const char* path) {
352 size_t path_len = strlen(path);
353
354 FILE* fp = setmntent("/proc/mounts", "r");
355 if (fp == NULL) {
356 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
357 return -errno;
358 }
359
360 // Some volumes can be stacked on each other, so force unmount in
361 // reverse order to give us the best chance of success.
362 std::list<std::string> toUnmount;
363 mntent* mentry;
364 while ((mentry = getmntent(fp)) != NULL) {
365 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
366 toUnmount.push_front(std::string(mentry->mnt_dir));
367 }
368 }
369 endmntent(fp);
370
371 for (auto path : toUnmount) {
372 if (umount2(path.c_str(), MNT_DETACH)) {
373 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
374 }
375 }
376 return 0;
377}
378
Narayan Kamath973b4662014-03-31 13:41:26 +0100379// Create a private mount namespace and bind mount appropriate emulated
380// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700381static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Andreas Gamped5758f62018-03-12 12:08:55 -0700382 bool force_mount_namespace, std::string* error_msg) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700383 // See storage config details at http://source.android.com/tech/storage/
384
Jeff Sharkey9527b222015-06-24 15:24:48 -0700385 String8 storageSource;
386 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700387 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700388 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700389 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700390 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700391 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500392 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700393 // Sane default of no storage visible
394 return true;
395 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400396
397 // Create a second private mount namespace for our process
398 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700399 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400400 return false;
401 }
402
Robert Sesek06f39302017-03-20 17:30:05 -0400403 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
404 if (mount_mode == MOUNT_EXTERNAL_NONE) {
405 return true;
406 }
407
Jeff Sharkey9527b222015-06-24 15:24:48 -0700408 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
409 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700410 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
411 storageSource.string(),
412 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700413 return false;
414 }
415
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700416 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700417 userid_t user_id = multiuser_get_user_id(uid);
418 const String8 userSource(String8::format("/mnt/user/%d", user_id));
419 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700420 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
Jeff Sharkey9527b222015-06-24 15:24:48 -0700421 return false;
422 }
423 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
424 NULL, MS_BIND, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700425 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
426 userSource.string(),
427 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700428 return false;
429 }
430
Narayan Kamath973b4662014-03-31 13:41:26 +0100431 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100432}
433
Narayan Kamath973b4662014-03-31 13:41:26 +0100434static bool NeedsNoRandomizeWorkaround() {
435#if !defined(__arm__)
436 return false;
437#else
438 int major;
439 int minor;
440 struct utsname uts;
441 if (uname(&uts) == -1) {
442 return false;
443 }
444
445 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
446 return false;
447 }
448
449 // Kernels before 3.4.* need the workaround.
450 return (major < 3) || ((major == 3) && (minor < 4));
451#endif
452}
Narayan Kamath973b4662014-03-31 13:41:26 +0100453
454// Utility to close down the Zygote socket file descriptors while
455// the child is still running as root with Zygote's privileges. Each
456// descriptor (if any) is closed via dup2(), replacing it with a valid
457// (open) descriptor to /dev/null.
458
Andreas Gamped5758f62018-03-12 12:08:55 -0700459static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100460 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700461 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100462 }
463 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200464 ScopedIntArrayRO ar(env, fdsToClose);
465 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700466 *error_msg = "Bad fd array";
467 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100468 }
469 jsize i;
470 int devnull;
471 for (i = 0; i < count; i++) {
472 devnull = open("/dev/null", O_RDWR);
473 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700474 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
475 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100476 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700477 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100478 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700479 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
480 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100481 }
482 close(devnull);
483 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700484 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100485}
486
487void SetThreadName(const char* thread_name) {
488 bool hasAt = false;
489 bool hasDot = false;
490 const char* s = thread_name;
491 while (*s) {
492 if (*s == '.') {
493 hasDot = true;
494 } else if (*s == '@') {
495 hasAt = true;
496 }
497 s++;
498 }
499 const int len = s - thread_name;
500 if (len < 15 || hasAt || !hasDot) {
501 s = thread_name;
502 } else {
503 s = thread_name + len - 15;
504 }
505 // pthread_setname_np fails rather than truncating long strings.
506 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
507 strlcpy(buf, s, sizeof(buf)-1);
508 errno = pthread_setname_np(pthread_self(), buf);
509 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700510 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100511 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800512 // Update base::logging default tag.
513 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100514}
515
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100516// The list of open zygote file descriptors.
517static FileDescriptorTable* gOpenFdTable = NULL;
518
Andreas Gamped5758f62018-03-12 12:08:55 -0700519static bool FillFileDescriptorVector(JNIEnv* env,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800520 jintArray java_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700521 std::vector<int>* fds,
522 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800523 CHECK(fds != nullptr);
524 if (java_fds != nullptr) {
525 ScopedIntArrayRO ar(env, java_fds);
526 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700527 *error_msg = "Bad fd array";
528 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800529 }
530 fds->reserve(ar.size());
531 for (size_t i = 0; i < ar.size(); ++i) {
532 fds->push_back(ar[i]);
533 }
534 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700535 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800536}
537
David Sehrde8d0bd2018-06-22 10:45:36 -0700538// Utility routine to specialize a zygote child process.
539static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
540 jint runtime_flags, jobjectArray javaRlimits,
541 jlong permittedCapabilities, jlong effectiveCapabilities,
542 jint mount_external, jstring java_se_info, jstring java_se_name,
543 bool is_system_server, bool is_child_zygote, jstring instructionSet,
544 jstring dataDir) {
545 std::string error_msg;
546
547 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
548 __attribute__ ((noreturn)) {
549 const char* se_name_c_str = nullptr;
550 std::unique_ptr<ScopedUtfChars> se_name;
551 if (java_se_name != nullptr) {
552 se_name.reset(new ScopedUtfChars(env, java_se_name));
553 se_name_c_str = se_name->c_str();
554 }
555 if (se_name_c_str == nullptr && is_system_server) {
556 se_name_c_str = "system_server";
557 }
558 const std::string& error_msg = (se_name_c_str == nullptr)
559 ? msg
560 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
561 env->FatalError(error_msg.c_str());
562 __builtin_unreachable();
563 };
564
565 // Keep capabilities across UID change, unless we're staying root.
566 if (uid != 0) {
567 if (!EnableKeepCapabilities(&error_msg)) {
568 fail_fn(error_msg);
569 }
570 }
571
572 if (!SetInheritable(permittedCapabilities, &error_msg)) {
573 fail_fn(error_msg);
574 }
575 if (!DropCapabilitiesBoundingSet(&error_msg)) {
576 fail_fn(error_msg);
577 }
578
579 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
580 && android::NativeBridgeAvailable();
581 if (use_native_bridge) {
582 ScopedUtfChars isa_string(env, instructionSet);
583 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
584 }
585 if (use_native_bridge && dataDir == NULL) {
586 // dataDir should never be null if we need to use a native bridge.
587 // In general, dataDir will never be null for normal applications. It can only happen in
588 // special cases (for isolated processes which are not associated with any app). These are
589 // launched by the framework and should not be emulated anyway.
590 use_native_bridge = false;
591 ALOGW("Native bridge will not be used because dataDir == NULL.");
592 }
593
594 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg)) {
595 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
596 if (errno == ENOTCONN || errno == EROFS) {
597 // When device is actively encrypting, we get ENOTCONN here
598 // since FUSE was mounted before the framework restarted.
599 // When encrypted device is booting, we get EROFS since
600 // FUSE hasn't been created yet by init.
601 // In either case, continue without external storage.
602 } else {
603 fail_fn(error_msg);
604 }
605 }
606
607 // If this zygote isn't root, it won't be able to create a process group,
608 // since the directory is owned by root.
609 if (!is_system_server && getuid() == 0) {
610 int rc = createProcessGroup(uid, getpid());
611 if (rc != 0) {
612 if (rc == -EROFS) {
613 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
614 } else {
615 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
616 }
617 }
618 }
619
620 if (!SetGids(env, javaGids, &error_msg)) {
621 fail_fn(error_msg);
622 }
623
624 if (!SetRLimits(env, javaRlimits, &error_msg)) {
625 fail_fn(error_msg);
626 }
627
628 if (use_native_bridge) {
629 ScopedUtfChars isa_string(env, instructionSet);
630 ScopedUtfChars data_dir(env, dataDir);
631 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
632 }
633
634 int rc = setresgid(gid, gid, gid);
635 if (rc == -1) {
636 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
637 }
638
639 // Must be called when the new process still has CAP_SYS_ADMIN, in this case, before changing
640 // uid from 0, which clears capabilities. The other alternative is to call
641 // prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that breaks SELinux domain transition (see
642 // b/71859146). As the result, privileged syscalls used below still need to be accessible in
643 // app process.
644 SetUpSeccompFilter(uid);
645
646 rc = setresuid(uid, uid, uid);
647 if (rc == -1) {
648 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
649 }
650
651 // The "dumpable" flag of a process, which controls core dump generation, is
652 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
653 // user or group ID changes. See proc(5) for possible values. In most cases,
654 // the value is 0, so core dumps are disabled for zygote children. However,
655 // when running in a Chrome OS container, the value is already set to 2,
656 // which allows the external crash reporter to collect all core dumps. Since
657 // only system crashes are interested, core dump is disabled for app
658 // processes. This also ensures compliance with CTS.
659 int dumpable = prctl(PR_GET_DUMPABLE);
660 if (dumpable == -1) {
661 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
662 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
663 }
664 if (dumpable == 2 && uid >= AID_APP) {
665 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
666 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
667 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
668 }
669 }
670
671 if (NeedsNoRandomizeWorkaround()) {
672 // Work around ARM kernel ASLR lossage (http://b/5817320).
673 int old_personality = personality(0xffffffff);
674 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
675 if (new_personality == -1) {
676 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
677 }
678 }
679
680 if (!SetCapabilities(permittedCapabilities, effectiveCapabilities, permittedCapabilities,
681 &error_msg)) {
682 fail_fn(error_msg);
683 }
684
685 if (!SetSchedulerPolicy(&error_msg)) {
686 fail_fn(error_msg);
687 }
688
689 const char* se_info_c_str = NULL;
690 ScopedUtfChars* se_info = NULL;
691 if (java_se_info != NULL) {
692 se_info = new ScopedUtfChars(env, java_se_info);
693 se_info_c_str = se_info->c_str();
694 if (se_info_c_str == NULL) {
695 fail_fn("se_info_c_str == NULL");
696 }
697 }
698 const char* se_name_c_str = NULL;
699 ScopedUtfChars* se_name = NULL;
700 if (java_se_name != NULL) {
701 se_name = new ScopedUtfChars(env, java_se_name);
702 se_name_c_str = se_name->c_str();
703 if (se_name_c_str == NULL) {
704 fail_fn("se_name_c_str == NULL");
705 }
706 }
707 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
708 if (rc == -1) {
709 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
710 is_system_server, se_info_c_str, se_name_c_str));
711 }
712
713 // Make it easier to debug audit logs by setting the main thread's name to the
714 // nice name rather than "app_process".
715 if (se_name_c_str == NULL && is_system_server) {
716 se_name_c_str = "system_server";
717 }
718 if (se_name_c_str != NULL) {
719 SetThreadName(se_name_c_str);
720 }
721
722 delete se_info;
723 delete se_name;
724
725 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
726 UnsetChldSignalHandler();
727
728 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
729 is_system_server, is_child_zygote, instructionSet);
730 if (env->ExceptionCheck()) {
731 fail_fn("Error calling post fork hooks.");
732 }
733}
734
Narayan Kamath973b4662014-03-31 13:41:26 +0100735// Utility routine to fork zygote and specialize the child process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700736static pid_t ForkCommon(JNIEnv* env, jstring java_se_name, bool is_system_server,
737 jintArray fdsToClose, jintArray fdsToIgnore) {
yuanhao435e84b2018-01-15 15:37:02 +0800738 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100739
David Sehrde8d0bd2018-06-22 10:45:36 -0700740 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000741 sigset_t sigchld;
742 sigemptyset(&sigchld);
743 sigaddset(&sigchld, SIGCHLD);
744
Andreas Gampe5f35c4e2018-03-12 12:17:25 -0700745 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
746 __attribute__ ((noreturn)) {
747 const char* se_name_c_str = nullptr;
748 std::unique_ptr<ScopedUtfChars> se_name;
749 if (java_se_name != nullptr) {
750 se_name.reset(new ScopedUtfChars(env, java_se_name));
751 se_name_c_str = se_name->c_str();
752 }
753 if (se_name_c_str == nullptr && is_system_server) {
754 se_name_c_str = "system_server";
755 }
756 const std::string& error_msg = (se_name_c_str == nullptr)
757 ? msg
758 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
759 env->FatalError(error_msg.c_str());
Andreas Gamped5758f62018-03-12 12:08:55 -0700760 __builtin_unreachable();
761 };
762
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000763 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
764 // log, which would result in the logging FDs we close being reopened.
765 // This would cause failures because the FDs are not whitelisted.
766 //
767 // Note that the zygote process is single threaded at this point.
768 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700769 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000770 }
771
Narayan Kamath3764a262016-08-30 15:36:19 +0100772 // Close any logging related FDs before we start evaluating the list of
773 // file descriptors.
774 __android_log_close();
775
Andreas Gamped5758f62018-03-12 12:08:55 -0700776 std::string error_msg;
777
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100778 // If this is the first fork for this zygote, create the open FD table.
779 // If it isn't, we just need to check whether the list of open files has
780 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800781 std::vector<int> fds_to_ignore;
Andreas Gamped5758f62018-03-12 12:08:55 -0700782 if (!FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore, &error_msg)) {
783 fail_fn(error_msg);
784 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100785 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700786 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100787 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700788 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100789 }
Andreas Gampec362a442018-03-12 14:53:34 -0700790 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
791 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100792 }
793
Narayan Kamath973b4662014-03-31 13:41:26 +0100794 pid_t pid = fork();
795
796 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700797 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700798 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700799
Narayan Kamath973b4662014-03-31 13:41:26 +0100800 // Clean up any descriptors which must be closed immediately
Andreas Gamped5758f62018-03-12 12:08:55 -0700801 if (!DetachDescriptors(env, fdsToClose, &error_msg)) {
802 fail_fn(error_msg);
803 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100804
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100805 // Re-open all remaining open file descriptors so that they aren't shared
806 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700807 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
808 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100809 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700810 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100811
David Sehrde8d0bd2018-06-22 10:45:36 -0700812 // We blocked SIGCHLD prior to a fork, we unblock it here.
813 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
814 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100815 }
816 return pid;
817}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700818
819static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
820 __user_cap_header_struct capheader;
821 memset(&capheader, 0, sizeof(capheader));
822 capheader.version = _LINUX_CAPABILITY_VERSION_3;
823 capheader.pid = 0;
824
825 __user_cap_data_struct capdata[2];
826 if (capget(&capheader, &capdata[0]) == -1) {
827 ALOGE("capget failed: %s", strerror(errno));
828 RuntimeAbort(env, __LINE__, "capget failed");
829 }
830
831 return capdata[0].effective |
832 (static_cast<uint64_t>(capdata[1].effective) << 32);
833}
Narayan Kamath973b4662014-03-31 13:41:26 +0100834} // anonymous namespace
835
836namespace android {
837
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800838static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
839 // security_getenforce is not allowed on app process. Initialize and cache the value before
840 // zygote forks.
841 g_is_security_enforced = security_getenforce();
842}
843
Christopher Ferris76de39e2017-06-20 16:13:40 -0700844static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
845 PreApplicationInit();
846}
847
Narayan Kamath973b4662014-03-31 13:41:26 +0100848static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
849 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100850 jint runtime_flags, jobjectArray rlimits,
Narayan Kamath973b4662014-03-31 13:41:26 +0100851 jint mount_external, jstring se_info, jstring se_name,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500852 jintArray fdsToClose, jintArray fdsToIgnore, jboolean is_child_zygote,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800853 jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700854 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800855
856 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900857 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
Philip Cuadra0fabba32017-04-26 13:49:37 -0700858 // Grant CAP_SYS_NICE to allow Bluetooth to set RT priority for
859 // audio-related threads.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900860 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800861 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800862 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900863 capabilities |= (1LL << CAP_NET_RAW);
864 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Philip Cuadra0fabba32017-04-26 13:49:37 -0700865 capabilities |= (1LL << CAP_SYS_NICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800866 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700867
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800868 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
869 bool gid_wakelock_found = false;
870 if (gid == AID_WAKELOCK) {
871 gid_wakelock_found = true;
872 } else if (gids != NULL) {
873 jsize gids_num = env->GetArrayLength(gids);
874 ScopedIntArrayRO ar(env, gids);
875 if (ar.get() == NULL) {
876 RuntimeAbort(env, __LINE__, "Bad gids array");
877 }
878 for (int i = 0; i < gids_num; i++) {
879 if (ar[i] == AID_WAKELOCK) {
880 gid_wakelock_found = true;
881 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700882 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800883 }
884 }
885 if (gid_wakelock_found) {
886 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700887 }
888
Robert Sesekd0a190df2018-02-12 18:46:01 -0500889 // If forking a child zygote process, that zygote will need to be able to change
890 // the UID and GID of processes it forks, as well as drop those capabilities.
891 if (is_child_zygote) {
892 capabilities |= (1LL << CAP_SETUID);
893 capabilities |= (1LL << CAP_SETGID);
894 capabilities |= (1LL << CAP_SETPCAP);
895 }
896
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700897 // Containers run without some capabilities, so drop any caps that are not
898 // available.
899 capabilities &= GetEffectiveCapabilityMask(env);
900
David Sehrde8d0bd2018-06-22 10:45:36 -0700901 pid_t pid = ForkCommon(env, se_name, false, fdsToClose, fdsToIgnore);
902 if (pid == 0) {
903 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
904 capabilities, capabilities,
905 mount_external, se_info, se_name, false,
906 is_child_zygote == JNI_TRUE, instructionSet, appDataDir);
907 }
908 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100909}
910
911static jint com_android_internal_os_Zygote_nativeForkSystemServer(
912 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100913 jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities,
Narayan Kamath973b4662014-03-31 13:41:26 +0100914 jlong effectiveCapabilities) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700915 pid_t pid = ForkCommon(env, NULL, true, NULL, NULL);
916 if (pid == 0) {
917 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
918 permittedCapabilities, effectiveCapabilities,
919 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true,
920 false, NULL, NULL);
921 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100922 // The zygote process checks whether the child process has died or not.
923 ALOGI("System server process %d has been created", pid);
924 gSystemServerPid = pid;
925 // There is a slight window that the system server process has crashed
926 // but it went unnoticed because we haven't published its pid yet. So
927 // we recheck here just to make sure that all is well.
928 int status;
929 if (waitpid(pid, &status, WNOHANG) == pid) {
930 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800931 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100932 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800933
934 // Assign system_server to the correct memory cgroup.
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -0800935 // Not all devices mount /dev/memcg so check for the file first
936 // to avoid unnecessarily printing errors and denials in the logs.
937 if (!access("/dev/memcg/system/tasks", F_OK) &&
938 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Carmen Jacksondd401252017-02-23 15:21:10 -0800939 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
940 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100941 }
942 return pid;
943}
944
Robert Sesek54e387d2016-12-02 17:27:50 -0500945static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
946 JNIEnv* env, jclass, jstring path) {
947 ScopedUtfChars path_native(env, path);
948 const char* path_cstr = path_native.c_str();
949 if (!path_cstr) {
950 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
951 }
952 FileDescriptorWhitelist::Get()->Allow(path_cstr);
953}
954
doheon1.lee885b7422016-01-20 13:07:27 +0900955static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
956 // Zygote process unmount root storage space initially before every child processes are forked.
957 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400958 // and no need unmount storage operation in MountEmulatedStorage method.
959 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
960
961 // See storage config details at http://source.android.com/tech/storage/
962 // Create private mount namespace shared by all children
963 if (unshare(CLONE_NEWNS) == -1) {
964 RuntimeAbort(env, __LINE__, "Failed to unshare()");
965 return;
966 }
967
968 // Mark rootfs as being a slave so that changes from default
969 // namespace only flow into our children.
970 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
971 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
972 return;
973 }
974
975 // Create a staging tmpfs that is shared by our children; they will
976 // bind mount storage into their respective private namespaces, which
977 // are isolated from each other.
978 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
979 if (target_base != nullptr) {
980#define STRINGIFY_UID(x) __STRING(x)
981 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
982 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
983 ALOGE("Failed to mount tmpfs to %s", target_base);
984 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
985 return;
986 }
987#undef STRINGIFY_UID
988 }
doheon1.lee885b7422016-01-20 13:07:27 +0900989
990 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +0900991}
992
Daniel Micay76f6a862015-09-19 17:31:01 -0400993static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800994 { "nativeSecurityInit", "()V",
995 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700996 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -0500997 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +0100998 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
999 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001000 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001001 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1002 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001003 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001004 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1005 { "nativePreApplicationInit", "()V",
1006 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001007};
1008
1009int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001010 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
1011 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001012 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001013
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001014 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001015}
1016} // namespace android