blob: b96b8ecfb5e7393aa721a1fc04ac33d0aa39e7d5 [file] [log] [blame]
Narayan Kamath973b4662014-03-31 13:41:26 +01001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Colin Cross18cd9f52014-06-13 12:58:55 -070017#define LOG_TAG "Zygote"
Narayan Kamath973b4662014-03-31 13:41:26 +010018
19// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
20#include <sys/mount.h>
21#include <linux/fs.h>
22
Chris Wailesefc65b22018-10-26 12:41:54 -070023#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070024#include <list>
Chris Wailesefc65b22018-10-26 12:41:54 -070025#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080026#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070027#include <string>
28
Josh Gaod7951102018-06-26 16:05:12 -070029#include <android/fdsan.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070030#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080031#include <grp.h>
32#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070033#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070034#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010035#include <paths.h>
36#include <signal.h>
37#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070038#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040039#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070040#include <sys/personality.h>
41#include <sys/prctl.h>
42#include <sys/resource.h>
43#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070044#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070045#include <sys/types.h>
46#include <sys/utsname.h>
47#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080048#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070049
Andreas Gampe8dfa1782017-01-05 12:45:58 -080050#include "android-base/logging.h"
Minchan Kim696873e2018-06-27 11:32:40 +090051#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080052#include <android-base/file.h>
53#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070054#include <cutils/fs.h>
55#include <cutils/multiuser.h>
56#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070057#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070058#include <utils/String8.h>
59#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080060#include <seccomp_policy.h>
Howard Ro65e48ec2018-10-02 12:08:28 -070061#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070062#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070063
Andreas Gampeed6b9df2014-11-20 22:02:20 -080064#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070065#include <nativehelper/JNIHelp.h>
66#include <nativehelper/ScopedLocalRef.h>
67#include <nativehelper/ScopedPrimitiveArray.h>
68#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050069#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010070
jgu212eacd062014-09-10 06:55:07 -040071#include "nativebridge/native_bridge.h"
72
Narayan Kamath973b4662014-03-31 13:41:26 +010073namespace {
74
Chris Wailesefc65b22018-10-26 12:41:54 -070075using namespace std::placeholders;
76
Narayan Kamath973b4662014-03-31 13:41:26 +010077using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080078using android::base::StringPrintf;
79using android::base::WriteStringToFile;
Minchan Kim696873e2018-06-27 11:32:40 +090080using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010081
Andreas Gamped5758f62018-03-12 12:08:55 -070082#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
83 append(StringPrintf(__VA_ARGS__))
84
Narayan Kamath973b4662014-03-31 13:41:26 +010085static pid_t gSystemServerPid = 0;
86
87static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
88static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +010089static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +010090static jmethodID gCallPostForkChildHooks;
91
Victor Hsiehc8176ef2018-01-08 12:43:00 -080092static bool g_is_security_enforced = true;
93
Narayan Kamath973b4662014-03-31 13:41:26 +010094// Must match values in com.android.internal.os.Zygote.
95enum MountExternalKind {
96 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070097 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070098 MOUNT_EXTERNAL_READ = 2,
99 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +0100100};
101
Andreas Gampeb053cce2015-11-17 16:38:59 -0800102static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
103 std::ostringstream oss;
104 oss << __FILE__ << ":" << line << ": " << msg;
105 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100106}
107
108// This signal handler is for zygote mode, since the zygote must reap its children
109static void SigChldHandler(int /*signal_number*/) {
110 pid_t pid;
111 int status;
112
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700113 // It's necessary to save and restore the errno during this function.
114 // Since errno is stored per thread, changing it here modifies the errno
115 // on the thread on which this signal handler executes. If a signal occurs
116 // between a call and an errno check, it's possible to get the errno set
117 // here.
118 // See b/23572286 for extra information.
119 int saved_errno = errno;
120
Narayan Kamath973b4662014-03-31 13:41:26 +0100121 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
122 // Log process-death status that we care about. In general it is
123 // not safe to call LOG(...) from a signal handler because of
124 // possible reentrancy. However, we know a priori that the
125 // current implementation of LOG() is safe to call from a SIGCHLD
126 // handler in the zygote process. If the LOG() implementation
127 // changes its locking strategy or its use of syscalls within the
128 // lazy-init critical section, its use here may become unsafe.
129 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700130 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100131 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700132 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100133 if (WCOREDUMP(status)) {
134 ALOGI("Process %d dumped core.", pid);
135 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100136 }
137
138 // If the just-crashed process is the system_server, bring down zygote
139 // so that it is restarted by init and system server will be restarted
140 // from there.
141 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800142 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100143 kill(getpid(), SIGKILL);
144 }
145 }
146
Narayan Kamath160992d2014-04-14 14:46:07 +0100147 // Note that we shouldn't consider ECHILD an error because
148 // the secondary zygote might have no children left to wait for.
149 if (pid < 0 && errno != ECHILD) {
150 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100151 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700152
153 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100154}
155
yuanhao435e84b2018-01-15 15:37:02 +0800156// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
157// configured very late, because earlier in the runtime we may fork() and
158// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100159// have them be harvested immediately.
160//
yuanhao435e84b2018-01-15 15:37:02 +0800161// Ignore SIGHUP because all processes forked by the zygote are in the same
162// process group as the zygote and we don't want to be notified if we become
163// an orphaned group and have one or more stopped processes. This is not a
164// theoretical concern :
165// - we can become an orphaned group if one of our direct descendants forks
166// and is subsequently killed before its children.
167// - crash_dump routinely STOPs the process it's tracing.
168//
169// See issues b/71965619 and b/25567761 for further details.
170//
Narayan Kamath973b4662014-03-31 13:41:26 +0100171// This ends up being called repeatedly before each fork(), but there's
172// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800173static void SetSignalHandlers() {
174 struct sigaction sig_chld = {};
175 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100176
yuanhao435e84b2018-01-15 15:37:02 +0800177 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700178 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100179 }
yuanhao435e84b2018-01-15 15:37:02 +0800180
181 struct sigaction sig_hup = {};
182 sig_hup.sa_handler = SIG_IGN;
183 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
184 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
185 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100186}
187
188// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800189static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100190 struct sigaction sa;
191 memset(&sa, 0, sizeof(sa));
192 sa.sa_handler = SIG_DFL;
193
yuanhao435e84b2018-01-15 15:37:02 +0800194 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700195 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100196 }
197}
198
199// Calls POSIX setgroups() using the int[] object as an argument.
200// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700201static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100202 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700203 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100204 }
205
206 ScopedIntArrayRO gids(env, javaGids);
207 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700208 *error_msg = CREATE_ERROR("Getting gids int array failed");
209 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100210 }
211 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
212 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700213 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
214 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100215 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700216
217 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100218}
219
220// Sets the resource limits via setrlimit(2) for the values in the
221// two-dimensional array of integers that's passed in. The second dimension
222// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
223// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700224static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100225 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700226 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100227 }
228
229 rlimit rlim;
230 memset(&rlim, 0, sizeof(rlim));
231
232 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
233 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
234 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
235 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700236 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
237 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100238 }
239
240 rlim.rlim_cur = javaRlimit[1];
241 rlim.rlim_max = javaRlimit[2];
242
243 int rc = setrlimit(javaRlimit[0], &rlim);
244 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700245 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800246 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700247 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100248 }
249 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700250
251 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100252}
253
Narayan Kamath973b4662014-03-31 13:41:26 +0100254// The debug malloc library needs to know whether it's the zygote or a child.
255extern "C" int gMallocLeakZygoteChild;
256
Christopher Ferris76de39e2017-06-20 16:13:40 -0700257static void PreApplicationInit() {
258 // The child process sets this to indicate it's not the zygote.
259 gMallocLeakZygoteChild = 1;
260
261 // Set the jemalloc decay time to 1.
262 mallopt(M_DECAY_TIME, 1);
263}
264
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800265static void SetUpSeccompFilter(uid_t uid) {
266 if (!g_is_security_enforced) {
267 ALOGI("seccomp disabled by setenforce 0");
268 return;
269 }
270
271 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700272 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800273 set_app_seccomp_filter();
274 } else {
275 set_system_seccomp_filter();
276 }
277}
278
Andreas Gamped5758f62018-03-12 12:08:55 -0700279static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100280 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
281 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700282 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
283 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100284 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700285 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100286}
287
Andreas Gamped5758f62018-03-12 12:08:55 -0700288static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100289 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
290 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
291 if (rc == -1) {
292 if (errno == EINVAL) {
293 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
294 "your kernel is compiled with file capabilities support");
295 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700296 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
297 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100298 }
299 }
300 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700301 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100302}
303
Andreas Gamped5758f62018-03-12 12:08:55 -0700304static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800305 __user_cap_header_struct capheader;
306 memset(&capheader, 0, sizeof(capheader));
307 capheader.version = _LINUX_CAPABILITY_VERSION_3;
308 capheader.pid = 0;
309
310 __user_cap_data_struct capdata[2];
311 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700312 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
313 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800314 }
315
316 capdata[0].inheritable = inheritable;
317 capdata[1].inheritable = inheritable >> 32;
318
319 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700320 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
321 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800322 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700323
324 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800325}
326
Andreas Gamped5758f62018-03-12 12:08:55 -0700327static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
328 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100329 __user_cap_header_struct capheader;
330 memset(&capheader, 0, sizeof(capheader));
331 capheader.version = _LINUX_CAPABILITY_VERSION_3;
332 capheader.pid = 0;
333
334 __user_cap_data_struct capdata[2];
335 memset(&capdata, 0, sizeof(capdata));
336 capdata[0].effective = effective;
337 capdata[1].effective = effective >> 32;
338 capdata[0].permitted = permitted;
339 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800340 capdata[0].inheritable = inheritable;
341 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100342
343 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700344 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
345 "failed: %s", permitted, effective, inheritable, 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
Andreas Gamped5758f62018-03-12 12:08:55 -0700351static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100352 errno = -set_sched_policy(0, SP_DEFAULT);
353 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700354 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
355 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100356 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700357 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100358}
359
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700360static int UnmountTree(const char* path) {
361 size_t path_len = strlen(path);
362
363 FILE* fp = setmntent("/proc/mounts", "r");
364 if (fp == NULL) {
365 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
366 return -errno;
367 }
368
369 // Some volumes can be stacked on each other, so force unmount in
370 // reverse order to give us the best chance of success.
371 std::list<std::string> toUnmount;
372 mntent* mentry;
373 while ((mentry = getmntent(fp)) != NULL) {
374 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
375 toUnmount.push_front(std::string(mentry->mnt_dir));
376 }
377 }
378 endmntent(fp);
379
380 for (auto path : toUnmount) {
381 if (umount2(path.c_str(), MNT_DETACH)) {
382 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
383 }
384 }
385 return 0;
386}
387
Narayan Kamath973b4662014-03-31 13:41:26 +0100388// Create a private mount namespace and bind mount appropriate emulated
389// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700390static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Andreas Gamped5758f62018-03-12 12:08:55 -0700391 bool force_mount_namespace, std::string* error_msg) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700392 // See storage config details at http://source.android.com/tech/storage/
393
Jeff Sharkey9527b222015-06-24 15:24:48 -0700394 String8 storageSource;
395 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700396 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700397 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700398 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700399 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700400 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500401 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700402 // Sane default of no storage visible
403 return true;
404 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400405
406 // Create a second private mount namespace for our process
407 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700408 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400409 return false;
410 }
411
Robert Sesek06f39302017-03-20 17:30:05 -0400412 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
413 if (mount_mode == MOUNT_EXTERNAL_NONE) {
414 return true;
415 }
416
Jeff Sharkey9527b222015-06-24 15:24:48 -0700417 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
418 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700419 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
420 storageSource.string(),
421 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700422 return false;
423 }
424
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700425 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700426 userid_t user_id = multiuser_get_user_id(uid);
427 const String8 userSource(String8::format("/mnt/user/%d", user_id));
428 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700429 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
Jeff Sharkey9527b222015-06-24 15:24:48 -0700430 return false;
431 }
432 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
433 NULL, MS_BIND, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700434 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
435 userSource.string(),
436 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700437 return false;
438 }
439
Narayan Kamath973b4662014-03-31 13:41:26 +0100440 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100441}
442
Narayan Kamath973b4662014-03-31 13:41:26 +0100443static bool NeedsNoRandomizeWorkaround() {
444#if !defined(__arm__)
445 return false;
446#else
447 int major;
448 int minor;
449 struct utsname uts;
450 if (uname(&uts) == -1) {
451 return false;
452 }
453
454 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
455 return false;
456 }
457
458 // Kernels before 3.4.* need the workaround.
459 return (major < 3) || ((major == 3) && (minor < 4));
460#endif
461}
Narayan Kamath973b4662014-03-31 13:41:26 +0100462
463// Utility to close down the Zygote socket file descriptors while
464// the child is still running as root with Zygote's privileges. Each
465// descriptor (if any) is closed via dup2(), replacing it with a valid
466// (open) descriptor to /dev/null.
467
Andreas Gamped5758f62018-03-12 12:08:55 -0700468static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100469 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700470 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100471 }
472 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200473 ScopedIntArrayRO ar(env, fdsToClose);
474 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700475 *error_msg = "Bad fd array";
476 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100477 }
478 jsize i;
479 int devnull;
480 for (i = 0; i < count; i++) {
481 devnull = open("/dev/null", O_RDWR);
482 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700483 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
484 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100485 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700486 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100487 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700488 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
489 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100490 }
491 close(devnull);
492 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700493 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100494}
495
496void SetThreadName(const char* thread_name) {
497 bool hasAt = false;
498 bool hasDot = false;
499 const char* s = thread_name;
500 while (*s) {
501 if (*s == '.') {
502 hasDot = true;
503 } else if (*s == '@') {
504 hasAt = true;
505 }
506 s++;
507 }
508 const int len = s - thread_name;
509 if (len < 15 || hasAt || !hasDot) {
510 s = thread_name;
511 } else {
512 s = thread_name + len - 15;
513 }
514 // pthread_setname_np fails rather than truncating long strings.
515 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
516 strlcpy(buf, s, sizeof(buf)-1);
517 errno = pthread_setname_np(pthread_self(), buf);
518 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700519 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100520 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800521 // Update base::logging default tag.
522 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100523}
524
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100525// The list of open zygote file descriptors.
526static FileDescriptorTable* gOpenFdTable = NULL;
527
Andreas Gamped5758f62018-03-12 12:08:55 -0700528static bool FillFileDescriptorVector(JNIEnv* env,
Chris Wailesefc65b22018-10-26 12:41:54 -0700529 jintArray managed_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700530 std::vector<int>* fds,
531 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800532 CHECK(fds != nullptr);
Chris Wailesefc65b22018-10-26 12:41:54 -0700533 if (managed_fds != nullptr) {
534 ScopedIntArrayRO ar(env, managed_fds);
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800535 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700536 *error_msg = "Bad fd array";
537 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800538 }
539 fds->reserve(ar.size());
540 for (size_t i = 0; i < ar.size(); ++i) {
541 fds->push_back(ar[i]);
542 }
543 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700544 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800545}
546
Chris Wailesefc65b22018-10-26 12:41:54 -0700547[[noreturn]]
548static void ZygoteFailure(JNIEnv* env,
549 const char* process_name,
550 jstring managed_process_name,
551 const std::string& msg) {
552 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
553 if (managed_process_name != nullptr) {
554 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
555 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
556 process_name = scoped_managed_process_name_ptr->c_str();
557 }
558 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700559
Chris Wailesefc65b22018-10-26 12:41:54 -0700560 const std::string& error_msg =
561 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
562
563 env->FatalError(error_msg.c_str());
564 __builtin_unreachable();
565}
566
567static std::optional<std::string> ExtractJString(JNIEnv* env,
568 const char* process_name,
569 jstring managed_process_name,
570 jstring managed_string) {
571 if (managed_string == nullptr) {
572 return std::optional<std::string>();
573 } else {
574 ScopedUtfChars scoped_string_chars(env, managed_string);
575
576 if (scoped_string_chars.c_str() != nullptr) {
577 return std::optional<std::string>(scoped_string_chars.c_str());
578 } else {
579 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700580 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700581 }
582}
583
584// Utility routine to fork a zygote.
585static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
586 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore) {
587 SetSignalHandlers();
588
589 // Block SIGCHLD prior to fork.
590 sigset_t sigchld;
591 sigemptyset(&sigchld);
592 sigaddset(&sigchld, SIGCHLD);
593
594 // Curry a failure function.
595 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
596 nullptr, _1);
597
598 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
599 // log, which would result in the logging FDs we close being reopened.
600 // This would cause failures because the FDs are not whitelisted.
601 //
602 // Note that the zygote process is single threaded at this point.
603 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
604 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
605 }
606
607 // Close any logging related FDs before we start evaluating the list of
608 // file descriptors.
609 __android_log_close();
610 stats_log_close();
611
612 // If this is the first fork for this zygote, create the open FD table. If
613 // it isn't, we just need to check whether the list of open files has changed
614 // (and it shouldn't in the normal case).
615 std::string error_msg;
616 std::vector<int> fds_to_ignore;
617 if (!FillFileDescriptorVector(env, managed_fds_to_ignore, &fds_to_ignore, &error_msg)) {
618 fail_fn(error_msg);
619 }
620
621 if (gOpenFdTable == nullptr) {
622 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
623 if (gOpenFdTable == nullptr) {
624 fail_fn(error_msg);
David Sehrde8d0bd2018-06-22 10:45:36 -0700625 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700626 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
627 fail_fn(error_msg);
628 }
629
630 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
631
632 pid_t pid = fork();
633
634 if (pid == 0) {
635 // The child process.
636 PreApplicationInit();
637
638 // Clean up any descriptors which must be closed immediately
639 if (!DetachDescriptors(env, managed_fds_to_close, &error_msg)) {
640 fail_fn(error_msg);
641 }
642
643 // Re-open all remaining open file descriptors so that they aren't shared
644 // with the zygote across a fork.
645 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
646 fail_fn(error_msg);
647 }
648
649 // Turn fdsan back on.
650 android_fdsan_set_error_level(fdsan_error_level);
651 }
652
653 // We blocked SIGCHLD prior to a fork, we unblock it here.
654 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
655 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
656 }
657 return pid;
658}
659
660// Utility routine to specialize a zygote child process.
661static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
662 jint runtime_flags, jobjectArray rlimits,
663 jlong permitted_capabilities, jlong effective_capabilities,
664 jint mount_external, jstring managed_se_info,
665 jstring managed_nice_name, bool is_system_server,
666 bool is_child_zygote, jstring managed_instruction_set,
667 jstring managed_app_data_dir) {
668 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
669 managed_nice_name, _1);
670 auto extract_fn = std::bind(ExtractJString, env, is_system_server ? "system_server" : "zygote",
671 managed_nice_name, _1);
672
673 auto se_info = extract_fn(managed_se_info);
674 auto nice_name = extract_fn(managed_nice_name);
675 auto instruction_set = extract_fn(managed_instruction_set);
676 auto app_data_dir = extract_fn(managed_app_data_dir);
677
678 std::string error_msg;
David Sehrde8d0bd2018-06-22 10:45:36 -0700679
680 // Keep capabilities across UID change, unless we're staying root.
681 if (uid != 0) {
682 if (!EnableKeepCapabilities(&error_msg)) {
683 fail_fn(error_msg);
684 }
685 }
686
Chris Wailesefc65b22018-10-26 12:41:54 -0700687 if (!SetInheritable(permitted_capabilities, &error_msg)) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700688 fail_fn(error_msg);
689 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700690
David Sehrde8d0bd2018-06-22 10:45:36 -0700691 if (!DropCapabilitiesBoundingSet(&error_msg)) {
692 fail_fn(error_msg);
693 }
694
Chris Wailesefc65b22018-10-26 12:41:54 -0700695 bool use_native_bridge = !is_system_server &&
696 instruction_set.has_value() &&
697 android::NativeBridgeAvailable() &&
698 android::NeedsNativeBridge(instruction_set.value().c_str());
699
700 if (use_native_bridge && !app_data_dir.has_value()) {
701 // The app_data_dir variable should never be empty if we need to use a
702 // native bridge. In general, app_data_dir will never be empty for normal
703 // applications. It can only happen in special cases (for isolated
704 // processes which are not associated with any app). These are launched by
705 // the framework and should not be emulated anyway.
David Sehrde8d0bd2018-06-22 10:45:36 -0700706 use_native_bridge = false;
Chris Wailesefc65b22018-10-26 12:41:54 -0700707 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700708 }
709
710 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg)) {
711 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
712 if (errno == ENOTCONN || errno == EROFS) {
713 // When device is actively encrypting, we get ENOTCONN here
714 // since FUSE was mounted before the framework restarted.
715 // When encrypted device is booting, we get EROFS since
716 // FUSE hasn't been created yet by init.
717 // In either case, continue without external storage.
718 } else {
719 fail_fn(error_msg);
720 }
721 }
722
723 // If this zygote isn't root, it won't be able to create a process group,
724 // since the directory is owned by root.
725 if (!is_system_server && getuid() == 0) {
726 int rc = createProcessGroup(uid, getpid());
727 if (rc != 0) {
728 if (rc == -EROFS) {
729 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
730 } else {
731 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
732 }
733 }
734 }
735
Chris Wailesefc65b22018-10-26 12:41:54 -0700736 if (!SetGids(env, gids, &error_msg)) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700737 fail_fn(error_msg);
738 }
739
Chris Wailesefc65b22018-10-26 12:41:54 -0700740 if (!SetRLimits(env, rlimits, &error_msg)) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700741 fail_fn(error_msg);
742 }
743
744 if (use_native_bridge) {
Chris Wailesefc65b22018-10-26 12:41:54 -0700745 // Due to the logic behind use_native_bridge we know that both app_data_dir
746 // and instruction_set contain values.
747 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
748 instruction_set.value().c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700749 }
750
Chris Wailesefc65b22018-10-26 12:41:54 -0700751 if (setresgid(gid, gid, gid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700752 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
753 }
754
Chris Wailesefc65b22018-10-26 12:41:54 -0700755 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
756 // before changing uid from 0, which clears capabilities. The other
757 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
758 // breaks SELinux domain transition (see b/71859146). As the result,
759 // privileged syscalls used below still need to be accessible in app process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700760 SetUpSeccompFilter(uid);
761
Chris Wailesefc65b22018-10-26 12:41:54 -0700762 if (setresuid(uid, uid, uid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700763 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
764 }
765
766 // The "dumpable" flag of a process, which controls core dump generation, is
767 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
768 // user or group ID changes. See proc(5) for possible values. In most cases,
769 // the value is 0, so core dumps are disabled for zygote children. However,
770 // when running in a Chrome OS container, the value is already set to 2,
771 // which allows the external crash reporter to collect all core dumps. Since
772 // only system crashes are interested, core dump is disabled for app
773 // processes. This also ensures compliance with CTS.
774 int dumpable = prctl(PR_GET_DUMPABLE);
775 if (dumpable == -1) {
776 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
777 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
778 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700779
David Sehrde8d0bd2018-06-22 10:45:36 -0700780 if (dumpable == 2 && uid >= AID_APP) {
781 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
782 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
783 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
784 }
785 }
786
787 if (NeedsNoRandomizeWorkaround()) {
788 // Work around ARM kernel ASLR lossage (http://b/5817320).
789 int old_personality = personality(0xffffffff);
790 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
791 if (new_personality == -1) {
792 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
793 }
794 }
795
Chris Wailesefc65b22018-10-26 12:41:54 -0700796 if (!SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities,
David Sehrde8d0bd2018-06-22 10:45:36 -0700797 &error_msg)) {
798 fail_fn(error_msg);
799 }
800
801 if (!SetSchedulerPolicy(&error_msg)) {
802 fail_fn(error_msg);
803 }
804
Chris Wailesefc65b22018-10-26 12:41:54 -0700805 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
806 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
807
808 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
809 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
810 uid, is_system_server, se_info_ptr, nice_name_ptr));
David Sehrde8d0bd2018-06-22 10:45:36 -0700811 }
812
813 // Make it easier to debug audit logs by setting the main thread's name to the
814 // nice name rather than "app_process".
Chris Wailesefc65b22018-10-26 12:41:54 -0700815 if (nice_name.has_value()) {
816 SetThreadName(nice_name.value().c_str());
817 } else if (is_system_server) {
818 SetThreadName("system_server");
David Sehrde8d0bd2018-06-22 10:45:36 -0700819 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700820
821 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
822 UnsetChldSignalHandler();
823
Orion Hodson46724e72018-10-19 13:05:33 +0100824 if (is_system_server) {
825 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
826 if (env->ExceptionCheck()) {
827 fail_fn("Error calling post fork system server hooks.");
828 }
829 // TODO(oth): Remove hardcoded label here (b/117874058).
830 static const char* kSystemServerLabel = "u:r:system_server:s0";
831 if (selinux_android_setcon(kSystemServerLabel) != 0) {
832 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
833 }
834 }
835
David Sehrde8d0bd2018-06-22 10:45:36 -0700836 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
Chris Wailesefc65b22018-10-26 12:41:54 -0700837 is_system_server, is_child_zygote, managed_instruction_set);
838
David Sehrde8d0bd2018-06-22 10:45:36 -0700839 if (env->ExceptionCheck()) {
840 fail_fn("Error calling post fork hooks.");
841 }
842}
843
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700844static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
845 __user_cap_header_struct capheader;
846 memset(&capheader, 0, sizeof(capheader));
847 capheader.version = _LINUX_CAPABILITY_VERSION_3;
848 capheader.pid = 0;
849
850 __user_cap_data_struct capdata[2];
851 if (capget(&capheader, &capdata[0]) == -1) {
852 ALOGE("capget failed: %s", strerror(errno));
853 RuntimeAbort(env, __LINE__, "capget failed");
854 }
855
Chris Wailesefc65b22018-10-26 12:41:54 -0700856 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
857}
858
859static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
860 bool is_child_zygote) {
861 jlong capabilities = 0;
862
863 /*
864 * Grant the following capabilities to the Bluetooth user:
865 * - CAP_WAKE_ALARM
866 * - CAP_NET_RAW
867 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
868 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
869 */
870
871 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
872 capabilities |= (1LL << CAP_WAKE_ALARM);
873 capabilities |= (1LL << CAP_NET_RAW);
874 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
875 capabilities |= (1LL << CAP_SYS_NICE);
876 }
877
878 /*
879 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
880 */
881
882 bool gid_wakelock_found = false;
883 if (gid == AID_WAKELOCK) {
884 gid_wakelock_found = true;
885 } else if (gids != nullptr) {
886 jsize gids_num = env->GetArrayLength(gids);
887 ScopedIntArrayRO native_gid_proxy(env, gids);
888
889 if (native_gid_proxy.get() == nullptr) {
890 RuntimeAbort(env, __LINE__, "Bad gids array");
891 }
892
893 for (int gid_index = gids_num; --gids_num >= 0;) {
894 if (native_gid_proxy[gid_index] == AID_WAKELOCK) {
895 gid_wakelock_found = true;
896 break;
897 }
898 }
899 }
900
901 if (gid_wakelock_found) {
902 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
903 }
904
905 /*
906 * Grant child Zygote processes the following capabilities:
907 * - CAP_SETUID (change UID of child processes)
908 * - CAP_SETGID (change GID of child processes)
909 * - CAP_SETPCAP (change capabilities of child processes)
910 */
911
912 if (is_child_zygote) {
913 capabilities |= (1LL << CAP_SETUID);
914 capabilities |= (1LL << CAP_SETGID);
915 capabilities |= (1LL << CAP_SETPCAP);
916 }
917
918 /*
919 * Containers run without some capabilities, so drop any caps that are not
920 * available.
921 */
922
923 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700924}
Narayan Kamath973b4662014-03-31 13:41:26 +0100925} // anonymous namespace
926
927namespace android {
928
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800929static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesefc65b22018-10-26 12:41:54 -0700930 // security_getenforce is not allowed on app process. Initialize and cache
931 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800932 g_is_security_enforced = security_getenforce();
933}
934
Christopher Ferris76de39e2017-06-20 16:13:40 -0700935static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
936 PreApplicationInit();
937}
938
Narayan Kamath973b4662014-03-31 13:41:26 +0100939static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
940 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100941 jint runtime_flags, jobjectArray rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -0700942 jint mount_external, jstring se_info, jstring nice_name,
943 jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote,
944 jstring instruction_set, jstring app_data_dir) {
945 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800946
Chris Wailesefc65b22018-10-26 12:41:54 -0700947 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -0700948 if (pid == 0) {
949 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
950 capabilities, capabilities,
Chris Wailesefc65b22018-10-26 12:41:54 -0700951 mount_external, se_info, nice_name, false,
952 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
David Sehrde8d0bd2018-06-22 10:45:36 -0700953 }
954 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100955}
956
957static jint com_android_internal_os_Zygote_nativeForkSystemServer(
958 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesefc65b22018-10-26 12:41:54 -0700959 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
960 jlong effective_capabilities) {
961 pid_t pid = ForkCommon(env, true,
962 /* managed_fds_to_close= */ nullptr,
963 /* managed_fds_to_ignore= */ nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -0700964 if (pid == 0) {
965 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -0700966 permitted_capabilities, effective_capabilities,
967 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
968 false, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -0700969 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100970 // The zygote process checks whether the child process has died or not.
971 ALOGI("System server process %d has been created", pid);
972 gSystemServerPid = pid;
973 // There is a slight window that the system server process has crashed
974 // but it went unnoticed because we haven't published its pid yet. So
975 // we recheck here just to make sure that all is well.
976 int status;
977 if (waitpid(pid, &status, WNOHANG) == pid) {
978 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800979 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100980 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800981
Minchan Kim696873e2018-06-27 11:32:40 +0900982 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
983 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
984 if (per_app_memcg) {
985 // Assign system_server to the correct memory cgroup.
986 // Not all devices mount /dev/memcg so check for the file first
987 // to avoid unnecessarily printing errors and denials in the logs.
988 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -0800989 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim696873e2018-06-27 11:32:40 +0900990 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
991 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800992 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100993 }
994 return pid;
995}
996
Robert Sesek54e387d2016-12-02 17:27:50 -0500997static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
998 JNIEnv* env, jclass, jstring path) {
999 ScopedUtfChars path_native(env, path);
1000 const char* path_cstr = path_native.c_str();
1001 if (!path_cstr) {
Chris Wailesefc65b22018-10-26 12:41:54 -07001002 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001003 }
1004 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1005}
1006
doheon1.lee885b7422016-01-20 13:07:27 +09001007static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1008 // Zygote process unmount root storage space initially before every child processes are forked.
1009 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001010 // and no need unmount storage operation in MountEmulatedStorage method.
1011 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1012
1013 // See storage config details at http://source.android.com/tech/storage/
1014 // Create private mount namespace shared by all children
1015 if (unshare(CLONE_NEWNS) == -1) {
1016 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1017 return;
1018 }
1019
1020 // Mark rootfs as being a slave so that changes from default
1021 // namespace only flow into our children.
1022 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1023 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1024 return;
1025 }
1026
1027 // Create a staging tmpfs that is shared by our children; they will
1028 // bind mount storage into their respective private namespaces, which
1029 // are isolated from each other.
1030 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1031 if (target_base != nullptr) {
1032#define STRINGIFY_UID(x) __STRING(x)
1033 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1034 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1035 ALOGE("Failed to mount tmpfs to %s", target_base);
1036 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1037 return;
1038 }
1039#undef STRINGIFY_UID
1040 }
doheon1.lee885b7422016-01-20 13:07:27 +09001041
1042 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001043}
1044
Daniel Micay76f6a862015-09-19 17:31:01 -04001045static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001046 { "nativeSecurityInit", "()V",
1047 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001048 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001049 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001050 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1051 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001052 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001053 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1054 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001055 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001056 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1057 { "nativePreApplicationInit", "()V",
1058 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001059};
1060
1061int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001062 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001063 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1064 "callPostForkSystemServerHooks",
1065 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001066 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001067 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001068
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001069 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001070}
1071} // namespace android