blob: e30a3e7adc0cd61530506738d4072701f27b561d [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"
Minchan Kim5fa8af22018-06-27 11:32:40 +090048#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080049#include <android-base/file.h>
50#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070051#include <cutils/fs.h>
52#include <cutils/multiuser.h>
53#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070054#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070055#include <utils/String8.h>
56#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080057#include <seccomp_policy.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070058#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070059
Andreas Gampeed6b9df2014-11-20 22:02:20 -080060#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070061#include <nativehelper/JNIHelp.h>
62#include <nativehelper/ScopedLocalRef.h>
63#include <nativehelper/ScopedPrimitiveArray.h>
64#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050065#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010066
jgu212eacd062014-09-10 06:55:07 -040067#include "nativebridge/native_bridge.h"
68
Narayan Kamath973b4662014-03-31 13:41:26 +010069namespace {
70
71using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080072using android::base::StringPrintf;
73using android::base::WriteStringToFile;
Minchan Kim5fa8af22018-06-27 11:32:40 +090074using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010075
Andreas Gamped5758f62018-03-12 12:08:55 -070076#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
77 append(StringPrintf(__VA_ARGS__))
78
Narayan Kamath973b4662014-03-31 13:41:26 +010079static pid_t gSystemServerPid = 0;
80
81static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
82static jclass gZygoteClass;
83static jmethodID gCallPostForkChildHooks;
84
Victor Hsiehc8176ef2018-01-08 12:43:00 -080085static bool g_is_security_enforced = true;
86
Narayan Kamath973b4662014-03-31 13:41:26 +010087// Must match values in com.android.internal.os.Zygote.
88enum MountExternalKind {
89 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070090 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070091 MOUNT_EXTERNAL_READ = 2,
92 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010093};
94
Andreas Gampeb053cce2015-11-17 16:38:59 -080095static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
96 std::ostringstream oss;
97 oss << __FILE__ << ":" << line << ": " << msg;
98 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +010099}
100
101// This signal handler is for zygote mode, since the zygote must reap its children
102static void SigChldHandler(int /*signal_number*/) {
103 pid_t pid;
104 int status;
105
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700106 // It's necessary to save and restore the errno during this function.
107 // Since errno is stored per thread, changing it here modifies the errno
108 // on the thread on which this signal handler executes. If a signal occurs
109 // between a call and an errno check, it's possible to get the errno set
110 // here.
111 // See b/23572286 for extra information.
112 int saved_errno = errno;
113
Narayan Kamath973b4662014-03-31 13:41:26 +0100114 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
115 // Log process-death status that we care about. In general it is
116 // not safe to call LOG(...) from a signal handler because of
117 // possible reentrancy. However, we know a priori that the
118 // current implementation of LOG() is safe to call from a SIGCHLD
119 // handler in the zygote process. If the LOG() implementation
120 // changes its locking strategy or its use of syscalls within the
121 // lazy-init critical section, its use here may become unsafe.
122 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700123 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100124 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700125 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100126 if (WCOREDUMP(status)) {
127 ALOGI("Process %d dumped core.", pid);
128 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100129 }
130
131 // If the just-crashed process is the system_server, bring down zygote
132 // so that it is restarted by init and system server will be restarted
133 // from there.
134 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800135 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100136 kill(getpid(), SIGKILL);
137 }
138 }
139
Narayan Kamath160992d2014-04-14 14:46:07 +0100140 // Note that we shouldn't consider ECHILD an error because
141 // the secondary zygote might have no children left to wait for.
142 if (pid < 0 && errno != ECHILD) {
143 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100144 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700145
146 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100147}
148
yuanhao435e84b2018-01-15 15:37:02 +0800149// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
150// configured very late, because earlier in the runtime we may fork() and
151// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100152// have them be harvested immediately.
153//
yuanhao435e84b2018-01-15 15:37:02 +0800154// Ignore SIGHUP because all processes forked by the zygote are in the same
155// process group as the zygote and we don't want to be notified if we become
156// an orphaned group and have one or more stopped processes. This is not a
157// theoretical concern :
158// - we can become an orphaned group if one of our direct descendants forks
159// and is subsequently killed before its children.
160// - crash_dump routinely STOPs the process it's tracing.
161//
162// See issues b/71965619 and b/25567761 for further details.
163//
Narayan Kamath973b4662014-03-31 13:41:26 +0100164// This ends up being called repeatedly before each fork(), but there's
165// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800166static void SetSignalHandlers() {
167 struct sigaction sig_chld = {};
168 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100169
yuanhao435e84b2018-01-15 15:37:02 +0800170 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700171 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100172 }
yuanhao435e84b2018-01-15 15:37:02 +0800173
174 struct sigaction sig_hup = {};
175 sig_hup.sa_handler = SIG_IGN;
176 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
177 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
178 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100179}
180
181// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800182static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100183 struct sigaction sa;
184 memset(&sa, 0, sizeof(sa));
185 sa.sa_handler = SIG_DFL;
186
yuanhao435e84b2018-01-15 15:37:02 +0800187 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700188 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100189 }
190}
191
192// Calls POSIX setgroups() using the int[] object as an argument.
193// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700194static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100195 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700196 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100197 }
198
199 ScopedIntArrayRO gids(env, javaGids);
200 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700201 *error_msg = CREATE_ERROR("Getting gids int array failed");
202 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100203 }
204 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
205 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700206 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
207 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100208 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700209
210 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100211}
212
213// Sets the resource limits via setrlimit(2) for the values in the
214// two-dimensional array of integers that's passed in. The second dimension
215// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
216// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700217static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100218 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700219 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100220 }
221
222 rlimit rlim;
223 memset(&rlim, 0, sizeof(rlim));
224
225 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
226 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
227 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
228 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700229 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
230 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100231 }
232
233 rlim.rlim_cur = javaRlimit[1];
234 rlim.rlim_max = javaRlimit[2];
235
236 int rc = setrlimit(javaRlimit[0], &rlim);
237 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700238 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800239 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700240 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100241 }
242 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700243
244 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100245}
246
Narayan Kamath973b4662014-03-31 13:41:26 +0100247// The debug malloc library needs to know whether it's the zygote or a child.
248extern "C" int gMallocLeakZygoteChild;
249
Christopher Ferris76de39e2017-06-20 16:13:40 -0700250static void PreApplicationInit() {
251 // The child process sets this to indicate it's not the zygote.
252 gMallocLeakZygoteChild = 1;
253
254 // Set the jemalloc decay time to 1.
255 mallopt(M_DECAY_TIME, 1);
256}
257
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800258static void SetUpSeccompFilter(uid_t uid) {
259 if (!g_is_security_enforced) {
260 ALOGI("seccomp disabled by setenforce 0");
261 return;
262 }
263
264 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700265 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800266 set_app_seccomp_filter();
267 } else {
268 set_system_seccomp_filter();
269 }
270}
271
Andreas Gamped5758f62018-03-12 12:08:55 -0700272static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100273 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
274 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700275 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
276 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100277 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700278 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100279}
280
Andreas Gamped5758f62018-03-12 12:08:55 -0700281static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100282 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
283 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
284 if (rc == -1) {
285 if (errno == EINVAL) {
286 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
287 "your kernel is compiled with file capabilities support");
288 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700289 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
290 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100291 }
292 }
293 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700294 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100295}
296
Andreas Gamped5758f62018-03-12 12:08:55 -0700297static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800298 __user_cap_header_struct capheader;
299 memset(&capheader, 0, sizeof(capheader));
300 capheader.version = _LINUX_CAPABILITY_VERSION_3;
301 capheader.pid = 0;
302
303 __user_cap_data_struct capdata[2];
304 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700305 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
306 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800307 }
308
309 capdata[0].inheritable = inheritable;
310 capdata[1].inheritable = inheritable >> 32;
311
312 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700313 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
314 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800315 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700316
317 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800318}
319
Andreas Gamped5758f62018-03-12 12:08:55 -0700320static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
321 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100322 __user_cap_header_struct capheader;
323 memset(&capheader, 0, sizeof(capheader));
324 capheader.version = _LINUX_CAPABILITY_VERSION_3;
325 capheader.pid = 0;
326
327 __user_cap_data_struct capdata[2];
328 memset(&capdata, 0, sizeof(capdata));
329 capdata[0].effective = effective;
330 capdata[1].effective = effective >> 32;
331 capdata[0].permitted = permitted;
332 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800333 capdata[0].inheritable = inheritable;
334 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100335
336 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700337 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
338 "failed: %s", permitted, effective, inheritable, strerror(errno));
339 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100340 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700341 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100342}
343
Andreas Gamped5758f62018-03-12 12:08:55 -0700344static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100345 errno = -set_sched_policy(0, SP_DEFAULT);
346 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700347 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
348 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100349 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700350 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100351}
352
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700353static int UnmountTree(const char* path) {
354 size_t path_len = strlen(path);
355
356 FILE* fp = setmntent("/proc/mounts", "r");
357 if (fp == NULL) {
358 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
359 return -errno;
360 }
361
362 // Some volumes can be stacked on each other, so force unmount in
363 // reverse order to give us the best chance of success.
364 std::list<std::string> toUnmount;
365 mntent* mentry;
366 while ((mentry = getmntent(fp)) != NULL) {
367 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
368 toUnmount.push_front(std::string(mentry->mnt_dir));
369 }
370 }
371 endmntent(fp);
372
373 for (auto path : toUnmount) {
374 if (umount2(path.c_str(), MNT_DETACH)) {
375 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
376 }
377 }
378 return 0;
379}
380
Narayan Kamath973b4662014-03-31 13:41:26 +0100381// Create a private mount namespace and bind mount appropriate emulated
382// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700383static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Andreas Gamped5758f62018-03-12 12:08:55 -0700384 bool force_mount_namespace, std::string* error_msg) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700385 // See storage config details at http://source.android.com/tech/storage/
386
Jeff Sharkey9527b222015-06-24 15:24:48 -0700387 String8 storageSource;
388 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700389 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700390 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700391 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700392 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700393 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500394 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700395 // Sane default of no storage visible
396 return true;
397 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400398
399 // Create a second private mount namespace for our process
400 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700401 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400402 return false;
403 }
404
Robert Sesek06f39302017-03-20 17:30:05 -0400405 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
406 if (mount_mode == MOUNT_EXTERNAL_NONE) {
407 return true;
408 }
409
Jeff Sharkey9527b222015-06-24 15:24:48 -0700410 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
411 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700412 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
413 storageSource.string(),
414 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700415 return false;
416 }
417
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700418 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700419 userid_t user_id = multiuser_get_user_id(uid);
420 const String8 userSource(String8::format("/mnt/user/%d", user_id));
421 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700422 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
Jeff Sharkey9527b222015-06-24 15:24:48 -0700423 return false;
424 }
425 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
426 NULL, MS_BIND, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700427 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
428 userSource.string(),
429 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700430 return false;
431 }
432
Narayan Kamath973b4662014-03-31 13:41:26 +0100433 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100434}
435
Narayan Kamath973b4662014-03-31 13:41:26 +0100436static bool NeedsNoRandomizeWorkaround() {
437#if !defined(__arm__)
438 return false;
439#else
440 int major;
441 int minor;
442 struct utsname uts;
443 if (uname(&uts) == -1) {
444 return false;
445 }
446
447 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
448 return false;
449 }
450
451 // Kernels before 3.4.* need the workaround.
452 return (major < 3) || ((major == 3) && (minor < 4));
453#endif
454}
Narayan Kamath973b4662014-03-31 13:41:26 +0100455
456// Utility to close down the Zygote socket file descriptors while
457// the child is still running as root with Zygote's privileges. Each
458// descriptor (if any) is closed via dup2(), replacing it with a valid
459// (open) descriptor to /dev/null.
460
Andreas Gamped5758f62018-03-12 12:08:55 -0700461static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100462 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700463 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100464 }
465 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200466 ScopedIntArrayRO ar(env, fdsToClose);
467 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700468 *error_msg = "Bad fd array";
469 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100470 }
471 jsize i;
472 int devnull;
473 for (i = 0; i < count; i++) {
474 devnull = open("/dev/null", O_RDWR);
475 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700476 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
477 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100478 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700479 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100480 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700481 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
482 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100483 }
484 close(devnull);
485 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700486 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100487}
488
489void SetThreadName(const char* thread_name) {
490 bool hasAt = false;
491 bool hasDot = false;
492 const char* s = thread_name;
493 while (*s) {
494 if (*s == '.') {
495 hasDot = true;
496 } else if (*s == '@') {
497 hasAt = true;
498 }
499 s++;
500 }
501 const int len = s - thread_name;
502 if (len < 15 || hasAt || !hasDot) {
503 s = thread_name;
504 } else {
505 s = thread_name + len - 15;
506 }
507 // pthread_setname_np fails rather than truncating long strings.
508 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
509 strlcpy(buf, s, sizeof(buf)-1);
510 errno = pthread_setname_np(pthread_self(), buf);
511 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700512 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100513 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800514 // Update base::logging default tag.
515 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100516}
517
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100518// The list of open zygote file descriptors.
519static FileDescriptorTable* gOpenFdTable = NULL;
520
Andreas Gamped5758f62018-03-12 12:08:55 -0700521static bool FillFileDescriptorVector(JNIEnv* env,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800522 jintArray java_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700523 std::vector<int>* fds,
524 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800525 CHECK(fds != nullptr);
526 if (java_fds != nullptr) {
527 ScopedIntArrayRO ar(env, java_fds);
528 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700529 *error_msg = "Bad fd array";
530 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800531 }
532 fds->reserve(ar.size());
533 for (size_t i = 0; i < ar.size(); ++i) {
534 fds->push_back(ar[i]);
535 }
536 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700537 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800538}
539
David Sehrde8d0bd2018-06-22 10:45:36 -0700540// Utility routine to specialize a zygote child process.
541static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
542 jint runtime_flags, jobjectArray javaRlimits,
543 jlong permittedCapabilities, jlong effectiveCapabilities,
544 jint mount_external, jstring java_se_info, jstring java_se_name,
545 bool is_system_server, bool is_child_zygote, jstring instructionSet,
546 jstring dataDir) {
547 std::string error_msg;
548
549 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
550 __attribute__ ((noreturn)) {
551 const char* se_name_c_str = nullptr;
552 std::unique_ptr<ScopedUtfChars> se_name;
553 if (java_se_name != nullptr) {
554 se_name.reset(new ScopedUtfChars(env, java_se_name));
555 se_name_c_str = se_name->c_str();
556 }
557 if (se_name_c_str == nullptr && is_system_server) {
558 se_name_c_str = "system_server";
559 }
560 const std::string& error_msg = (se_name_c_str == nullptr)
561 ? msg
562 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
563 env->FatalError(error_msg.c_str());
564 __builtin_unreachable();
565 };
566
567 // Keep capabilities across UID change, unless we're staying root.
568 if (uid != 0) {
569 if (!EnableKeepCapabilities(&error_msg)) {
570 fail_fn(error_msg);
571 }
572 }
573
574 if (!SetInheritable(permittedCapabilities, &error_msg)) {
575 fail_fn(error_msg);
576 }
577 if (!DropCapabilitiesBoundingSet(&error_msg)) {
578 fail_fn(error_msg);
579 }
580
581 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
582 && android::NativeBridgeAvailable();
583 if (use_native_bridge) {
584 ScopedUtfChars isa_string(env, instructionSet);
585 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
586 }
587 if (use_native_bridge && dataDir == NULL) {
588 // dataDir should never be null if we need to use a native bridge.
589 // In general, dataDir will never be null for normal applications. It can only happen in
590 // special cases (for isolated processes which are not associated with any app). These are
591 // launched by the framework and should not be emulated anyway.
592 use_native_bridge = false;
593 ALOGW("Native bridge will not be used because dataDir == NULL.");
594 }
595
596 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg)) {
597 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
598 if (errno == ENOTCONN || errno == EROFS) {
599 // When device is actively encrypting, we get ENOTCONN here
600 // since FUSE was mounted before the framework restarted.
601 // When encrypted device is booting, we get EROFS since
602 // FUSE hasn't been created yet by init.
603 // In either case, continue without external storage.
604 } else {
605 fail_fn(error_msg);
606 }
607 }
608
609 // If this zygote isn't root, it won't be able to create a process group,
610 // since the directory is owned by root.
611 if (!is_system_server && getuid() == 0) {
612 int rc = createProcessGroup(uid, getpid());
613 if (rc != 0) {
614 if (rc == -EROFS) {
615 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
616 } else {
617 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
618 }
619 }
620 }
621
622 if (!SetGids(env, javaGids, &error_msg)) {
623 fail_fn(error_msg);
624 }
625
626 if (!SetRLimits(env, javaRlimits, &error_msg)) {
627 fail_fn(error_msg);
628 }
629
630 if (use_native_bridge) {
631 ScopedUtfChars isa_string(env, instructionSet);
632 ScopedUtfChars data_dir(env, dataDir);
633 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
634 }
635
636 int rc = setresgid(gid, gid, gid);
637 if (rc == -1) {
638 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
639 }
640
641 // Must be called when the new process still has CAP_SYS_ADMIN, in this case, before changing
642 // uid from 0, which clears capabilities. The other alternative is to call
643 // prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that breaks SELinux domain transition (see
644 // b/71859146). As the result, privileged syscalls used below still need to be accessible in
645 // app process.
646 SetUpSeccompFilter(uid);
647
648 rc = setresuid(uid, uid, uid);
649 if (rc == -1) {
650 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
651 }
652
653 // The "dumpable" flag of a process, which controls core dump generation, is
654 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
655 // user or group ID changes. See proc(5) for possible values. In most cases,
656 // the value is 0, so core dumps are disabled for zygote children. However,
657 // when running in a Chrome OS container, the value is already set to 2,
658 // which allows the external crash reporter to collect all core dumps. Since
659 // only system crashes are interested, core dump is disabled for app
660 // processes. This also ensures compliance with CTS.
661 int dumpable = prctl(PR_GET_DUMPABLE);
662 if (dumpable == -1) {
663 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
664 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
665 }
666 if (dumpable == 2 && uid >= AID_APP) {
667 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
668 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
669 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
670 }
671 }
672
673 if (NeedsNoRandomizeWorkaround()) {
674 // Work around ARM kernel ASLR lossage (http://b/5817320).
675 int old_personality = personality(0xffffffff);
676 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
677 if (new_personality == -1) {
678 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
679 }
680 }
681
682 if (!SetCapabilities(permittedCapabilities, effectiveCapabilities, permittedCapabilities,
683 &error_msg)) {
684 fail_fn(error_msg);
685 }
686
687 if (!SetSchedulerPolicy(&error_msg)) {
688 fail_fn(error_msg);
689 }
690
691 const char* se_info_c_str = NULL;
692 ScopedUtfChars* se_info = NULL;
693 if (java_se_info != NULL) {
694 se_info = new ScopedUtfChars(env, java_se_info);
695 se_info_c_str = se_info->c_str();
696 if (se_info_c_str == NULL) {
697 fail_fn("se_info_c_str == NULL");
698 }
699 }
700 const char* se_name_c_str = NULL;
701 ScopedUtfChars* se_name = NULL;
702 if (java_se_name != NULL) {
703 se_name = new ScopedUtfChars(env, java_se_name);
704 se_name_c_str = se_name->c_str();
705 if (se_name_c_str == NULL) {
706 fail_fn("se_name_c_str == NULL");
707 }
708 }
709 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
710 if (rc == -1) {
711 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
712 is_system_server, se_info_c_str, se_name_c_str));
713 }
714
715 // Make it easier to debug audit logs by setting the main thread's name to the
716 // nice name rather than "app_process".
717 if (se_name_c_str == NULL && is_system_server) {
718 se_name_c_str = "system_server";
719 }
720 if (se_name_c_str != NULL) {
721 SetThreadName(se_name_c_str);
722 }
723
724 delete se_info;
725 delete se_name;
726
727 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
728 UnsetChldSignalHandler();
729
730 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
731 is_system_server, is_child_zygote, instructionSet);
732 if (env->ExceptionCheck()) {
733 fail_fn("Error calling post fork hooks.");
734 }
735}
736
Narayan Kamath973b4662014-03-31 13:41:26 +0100737// Utility routine to fork zygote and specialize the child process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700738static pid_t ForkCommon(JNIEnv* env, jstring java_se_name, bool is_system_server,
739 jintArray fdsToClose, jintArray fdsToIgnore) {
yuanhao435e84b2018-01-15 15:37:02 +0800740 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100741
David Sehrde8d0bd2018-06-22 10:45:36 -0700742 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000743 sigset_t sigchld;
744 sigemptyset(&sigchld);
745 sigaddset(&sigchld, SIGCHLD);
746
Andreas Gampe5f35c4e2018-03-12 12:17:25 -0700747 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
748 __attribute__ ((noreturn)) {
749 const char* se_name_c_str = nullptr;
750 std::unique_ptr<ScopedUtfChars> se_name;
751 if (java_se_name != nullptr) {
752 se_name.reset(new ScopedUtfChars(env, java_se_name));
753 se_name_c_str = se_name->c_str();
754 }
755 if (se_name_c_str == nullptr && is_system_server) {
756 se_name_c_str = "system_server";
757 }
758 const std::string& error_msg = (se_name_c_str == nullptr)
759 ? msg
760 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
761 env->FatalError(error_msg.c_str());
Andreas Gamped5758f62018-03-12 12:08:55 -0700762 __builtin_unreachable();
763 };
764
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000765 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
766 // log, which would result in the logging FDs we close being reopened.
767 // This would cause failures because the FDs are not whitelisted.
768 //
769 // Note that the zygote process is single threaded at this point.
770 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700771 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000772 }
773
Narayan Kamath3764a262016-08-30 15:36:19 +0100774 // Close any logging related FDs before we start evaluating the list of
775 // file descriptors.
776 __android_log_close();
777
Andreas Gamped5758f62018-03-12 12:08:55 -0700778 std::string error_msg;
779
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100780 // If this is the first fork for this zygote, create the open FD table.
781 // If it isn't, we just need to check whether the list of open files has
782 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800783 std::vector<int> fds_to_ignore;
Andreas Gamped5758f62018-03-12 12:08:55 -0700784 if (!FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore, &error_msg)) {
785 fail_fn(error_msg);
786 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100787 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700788 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100789 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700790 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100791 }
Andreas Gampec362a442018-03-12 14:53:34 -0700792 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
793 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100794 }
795
Narayan Kamath973b4662014-03-31 13:41:26 +0100796 pid_t pid = fork();
797
798 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700799 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700800 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700801
Narayan Kamath973b4662014-03-31 13:41:26 +0100802 // Clean up any descriptors which must be closed immediately
Andreas Gamped5758f62018-03-12 12:08:55 -0700803 if (!DetachDescriptors(env, fdsToClose, &error_msg)) {
804 fail_fn(error_msg);
805 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100806
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100807 // Re-open all remaining open file descriptors so that they aren't shared
808 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700809 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
810 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100811 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700812 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100813
David Sehrde8d0bd2018-06-22 10:45:36 -0700814 // We blocked SIGCHLD prior to a fork, we unblock it here.
815 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
816 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100817 }
818 return pid;
819}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700820
821static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
822 __user_cap_header_struct capheader;
823 memset(&capheader, 0, sizeof(capheader));
824 capheader.version = _LINUX_CAPABILITY_VERSION_3;
825 capheader.pid = 0;
826
827 __user_cap_data_struct capdata[2];
828 if (capget(&capheader, &capdata[0]) == -1) {
829 ALOGE("capget failed: %s", strerror(errno));
830 RuntimeAbort(env, __LINE__, "capget failed");
831 }
832
833 return capdata[0].effective |
834 (static_cast<uint64_t>(capdata[1].effective) << 32);
835}
Narayan Kamath973b4662014-03-31 13:41:26 +0100836} // anonymous namespace
837
838namespace android {
839
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800840static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
841 // security_getenforce is not allowed on app process. Initialize and cache the value before
842 // zygote forks.
843 g_is_security_enforced = security_getenforce();
844}
845
Christopher Ferris76de39e2017-06-20 16:13:40 -0700846static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
847 PreApplicationInit();
848}
849
Narayan Kamath973b4662014-03-31 13:41:26 +0100850static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
851 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100852 jint runtime_flags, jobjectArray rlimits,
Narayan Kamath973b4662014-03-31 13:41:26 +0100853 jint mount_external, jstring se_info, jstring se_name,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500854 jintArray fdsToClose, jintArray fdsToIgnore, jboolean is_child_zygote,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800855 jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700856 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800857
858 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900859 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
Philip Cuadra0fabba32017-04-26 13:49:37 -0700860 // Grant CAP_SYS_NICE to allow Bluetooth to set RT priority for
861 // audio-related threads.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900862 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800863 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800864 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900865 capabilities |= (1LL << CAP_NET_RAW);
866 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Philip Cuadra0fabba32017-04-26 13:49:37 -0700867 capabilities |= (1LL << CAP_SYS_NICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800868 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700869
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800870 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
871 bool gid_wakelock_found = false;
872 if (gid == AID_WAKELOCK) {
873 gid_wakelock_found = true;
874 } else if (gids != NULL) {
875 jsize gids_num = env->GetArrayLength(gids);
876 ScopedIntArrayRO ar(env, gids);
877 if (ar.get() == NULL) {
878 RuntimeAbort(env, __LINE__, "Bad gids array");
879 }
880 for (int i = 0; i < gids_num; i++) {
881 if (ar[i] == AID_WAKELOCK) {
882 gid_wakelock_found = true;
883 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700884 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800885 }
886 }
887 if (gid_wakelock_found) {
888 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700889 }
890
Robert Sesekd0a190df2018-02-12 18:46:01 -0500891 // If forking a child zygote process, that zygote will need to be able to change
892 // the UID and GID of processes it forks, as well as drop those capabilities.
893 if (is_child_zygote) {
894 capabilities |= (1LL << CAP_SETUID);
895 capabilities |= (1LL << CAP_SETGID);
896 capabilities |= (1LL << CAP_SETPCAP);
897 }
898
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700899 // Containers run without some capabilities, so drop any caps that are not
900 // available.
901 capabilities &= GetEffectiveCapabilityMask(env);
902
David Sehrde8d0bd2018-06-22 10:45:36 -0700903 pid_t pid = ForkCommon(env, se_name, false, fdsToClose, fdsToIgnore);
904 if (pid == 0) {
905 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
906 capabilities, capabilities,
907 mount_external, se_info, se_name, false,
908 is_child_zygote == JNI_TRUE, instructionSet, appDataDir);
909 }
910 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100911}
912
913static jint com_android_internal_os_Zygote_nativeForkSystemServer(
914 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100915 jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities,
Narayan Kamath973b4662014-03-31 13:41:26 +0100916 jlong effectiveCapabilities) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700917 pid_t pid = ForkCommon(env, NULL, true, NULL, NULL);
918 if (pid == 0) {
919 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
920 permittedCapabilities, effectiveCapabilities,
921 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true,
922 false, NULL, NULL);
923 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100924 // The zygote process checks whether the child process has died or not.
925 ALOGI("System server process %d has been created", pid);
926 gSystemServerPid = pid;
927 // There is a slight window that the system server process has crashed
928 // but it went unnoticed because we haven't published its pid yet. So
929 // we recheck here just to make sure that all is well.
930 int status;
931 if (waitpid(pid, &status, WNOHANG) == pid) {
932 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800933 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100934 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800935
Minchan Kim5fa8af22018-06-27 11:32:40 +0900936 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
937 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
938 if (per_app_memcg) {
939 // Assign system_server to the correct memory cgroup.
940 // Not all devices mount /dev/memcg so check for the file first
941 // to avoid unnecessarily printing errors and denials in the logs.
942 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -0800943 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim5fa8af22018-06-27 11:32:40 +0900944 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
945 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800946 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100947 }
948 return pid;
949}
950
Robert Sesek54e387d2016-12-02 17:27:50 -0500951static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
952 JNIEnv* env, jclass, jstring path) {
953 ScopedUtfChars path_native(env, path);
954 const char* path_cstr = path_native.c_str();
955 if (!path_cstr) {
956 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
957 }
958 FileDescriptorWhitelist::Get()->Allow(path_cstr);
959}
960
doheon1.lee885b7422016-01-20 13:07:27 +0900961static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
962 // Zygote process unmount root storage space initially before every child processes are forked.
963 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400964 // and no need unmount storage operation in MountEmulatedStorage method.
965 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
966
967 // See storage config details at http://source.android.com/tech/storage/
968 // Create private mount namespace shared by all children
969 if (unshare(CLONE_NEWNS) == -1) {
970 RuntimeAbort(env, __LINE__, "Failed to unshare()");
971 return;
972 }
973
974 // Mark rootfs as being a slave so that changes from default
975 // namespace only flow into our children.
976 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
977 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
978 return;
979 }
980
981 // Create a staging tmpfs that is shared by our children; they will
982 // bind mount storage into their respective private namespaces, which
983 // are isolated from each other.
984 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
985 if (target_base != nullptr) {
986#define STRINGIFY_UID(x) __STRING(x)
987 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
988 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
989 ALOGE("Failed to mount tmpfs to %s", target_base);
990 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
991 return;
992 }
993#undef STRINGIFY_UID
994 }
doheon1.lee885b7422016-01-20 13:07:27 +0900995
996 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +0900997}
998
Daniel Micay76f6a862015-09-19 17:31:01 -0400999static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001000 { "nativeSecurityInit", "()V",
1001 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001002 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001003 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001004 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1005 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001006 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001007 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1008 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001009 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001010 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1011 { "nativePreApplicationInit", "()V",
1012 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001013};
1014
1015int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001016 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
1017 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001018 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001019
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001020 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001021}
1022} // namespace android