blob: 0022cf88909846715b82da3079e4df4bb216f768 [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
Josh Gaod7951102018-06-26 16:05:12 -070027#include <android/fdsan.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070028#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080029#include <grp.h>
30#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070031#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070032#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010033#include <paths.h>
34#include <signal.h>
35#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070036#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040037#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070038#include <sys/personality.h>
39#include <sys/prctl.h>
40#include <sys/resource.h>
41#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070042#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070043#include <sys/types.h>
44#include <sys/utsname.h>
45#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080046#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070047
Andreas Gampe8dfa1782017-01-05 12:45:58 -080048#include "android-base/logging.h"
Minchan Kim696873e2018-06-27 11:32:40 +090049#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080050#include <android-base/file.h>
51#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070052#include <cutils/fs.h>
53#include <cutils/multiuser.h>
54#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070055#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070056#include <utils/String8.h>
57#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080058#include <seccomp_policy.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070059#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070060
Andreas Gampeed6b9df2014-11-20 22:02:20 -080061#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070062#include <nativehelper/JNIHelp.h>
63#include <nativehelper/ScopedLocalRef.h>
64#include <nativehelper/ScopedPrimitiveArray.h>
65#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050066#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010067
jgu212eacd062014-09-10 06:55:07 -040068#include "nativebridge/native_bridge.h"
69
Narayan Kamath973b4662014-03-31 13:41:26 +010070namespace {
71
72using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080073using android::base::StringPrintf;
74using android::base::WriteStringToFile;
Minchan Kim696873e2018-06-27 11:32:40 +090075using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010076
Andreas Gamped5758f62018-03-12 12:08:55 -070077#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
78 append(StringPrintf(__VA_ARGS__))
79
Narayan Kamath973b4662014-03-31 13:41:26 +010080static pid_t gSystemServerPid = 0;
81
82static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
83static jclass gZygoteClass;
84static jmethodID gCallPostForkChildHooks;
85
Victor Hsiehc8176ef2018-01-08 12:43:00 -080086static bool g_is_security_enforced = true;
87
Narayan Kamath973b4662014-03-31 13:41:26 +010088// Must match values in com.android.internal.os.Zygote.
89enum MountExternalKind {
90 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070091 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070092 MOUNT_EXTERNAL_READ = 2,
93 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010094};
95
Andreas Gampeb053cce2015-11-17 16:38:59 -080096static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
97 std::ostringstream oss;
98 oss << __FILE__ << ":" << line << ": " << msg;
99 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100100}
101
102// This signal handler is for zygote mode, since the zygote must reap its children
103static void SigChldHandler(int /*signal_number*/) {
104 pid_t pid;
105 int status;
106
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700107 // It's necessary to save and restore the errno during this function.
108 // Since errno is stored per thread, changing it here modifies the errno
109 // on the thread on which this signal handler executes. If a signal occurs
110 // between a call and an errno check, it's possible to get the errno set
111 // here.
112 // See b/23572286 for extra information.
113 int saved_errno = errno;
114
Narayan Kamath973b4662014-03-31 13:41:26 +0100115 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
116 // Log process-death status that we care about. In general it is
117 // not safe to call LOG(...) from a signal handler because of
118 // possible reentrancy. However, we know a priori that the
119 // current implementation of LOG() is safe to call from a SIGCHLD
120 // handler in the zygote process. If the LOG() implementation
121 // changes its locking strategy or its use of syscalls within the
122 // lazy-init critical section, its use here may become unsafe.
123 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700124 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100125 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700126 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100127 if (WCOREDUMP(status)) {
128 ALOGI("Process %d dumped core.", pid);
129 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100130 }
131
132 // If the just-crashed process is the system_server, bring down zygote
133 // so that it is restarted by init and system server will be restarted
134 // from there.
135 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800136 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100137 kill(getpid(), SIGKILL);
138 }
139 }
140
Narayan Kamath160992d2014-04-14 14:46:07 +0100141 // Note that we shouldn't consider ECHILD an error because
142 // the secondary zygote might have no children left to wait for.
143 if (pid < 0 && errno != ECHILD) {
144 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100145 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700146
147 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100148}
149
yuanhao435e84b2018-01-15 15:37:02 +0800150// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
151// configured very late, because earlier in the runtime we may fork() and
152// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100153// have them be harvested immediately.
154//
yuanhao435e84b2018-01-15 15:37:02 +0800155// Ignore SIGHUP because all processes forked by the zygote are in the same
156// process group as the zygote and we don't want to be notified if we become
157// an orphaned group and have one or more stopped processes. This is not a
158// theoretical concern :
159// - we can become an orphaned group if one of our direct descendants forks
160// and is subsequently killed before its children.
161// - crash_dump routinely STOPs the process it's tracing.
162//
163// See issues b/71965619 and b/25567761 for further details.
164//
Narayan Kamath973b4662014-03-31 13:41:26 +0100165// This ends up being called repeatedly before each fork(), but there's
166// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800167static void SetSignalHandlers() {
168 struct sigaction sig_chld = {};
169 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100170
yuanhao435e84b2018-01-15 15:37:02 +0800171 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700172 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100173 }
yuanhao435e84b2018-01-15 15:37:02 +0800174
175 struct sigaction sig_hup = {};
176 sig_hup.sa_handler = SIG_IGN;
177 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
178 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
179 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100180}
181
182// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800183static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100184 struct sigaction sa;
185 memset(&sa, 0, sizeof(sa));
186 sa.sa_handler = SIG_DFL;
187
yuanhao435e84b2018-01-15 15:37:02 +0800188 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700189 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100190 }
191}
192
193// Calls POSIX setgroups() using the int[] object as an argument.
194// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700195static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100196 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700197 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100198 }
199
200 ScopedIntArrayRO gids(env, javaGids);
201 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700202 *error_msg = CREATE_ERROR("Getting gids int array failed");
203 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100204 }
205 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
206 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700207 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
208 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100209 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700210
211 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100212}
213
214// Sets the resource limits via setrlimit(2) for the values in the
215// two-dimensional array of integers that's passed in. The second dimension
216// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
217// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700218static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100219 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700220 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100221 }
222
223 rlimit rlim;
224 memset(&rlim, 0, sizeof(rlim));
225
226 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
227 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
228 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
229 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700230 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
231 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100232 }
233
234 rlim.rlim_cur = javaRlimit[1];
235 rlim.rlim_max = javaRlimit[2];
236
237 int rc = setrlimit(javaRlimit[0], &rlim);
238 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700239 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800240 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700241 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100242 }
243 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700244
245 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100246}
247
Narayan Kamath973b4662014-03-31 13:41:26 +0100248// The debug malloc library needs to know whether it's the zygote or a child.
249extern "C" int gMallocLeakZygoteChild;
250
Christopher Ferris76de39e2017-06-20 16:13:40 -0700251static void PreApplicationInit() {
252 // The child process sets this to indicate it's not the zygote.
253 gMallocLeakZygoteChild = 1;
254
255 // Set the jemalloc decay time to 1.
256 mallopt(M_DECAY_TIME, 1);
257}
258
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800259static void SetUpSeccompFilter(uid_t uid) {
260 if (!g_is_security_enforced) {
261 ALOGI("seccomp disabled by setenforce 0");
262 return;
263 }
264
265 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700266 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800267 set_app_seccomp_filter();
268 } else {
269 set_system_seccomp_filter();
270 }
271}
272
Andreas Gamped5758f62018-03-12 12:08:55 -0700273static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100274 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
275 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700276 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
277 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100278 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700279 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100280}
281
Andreas Gamped5758f62018-03-12 12:08:55 -0700282static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100283 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
284 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
285 if (rc == -1) {
286 if (errno == EINVAL) {
287 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
288 "your kernel is compiled with file capabilities support");
289 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700290 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
291 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100292 }
293 }
294 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700295 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100296}
297
Andreas Gamped5758f62018-03-12 12:08:55 -0700298static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800299 __user_cap_header_struct capheader;
300 memset(&capheader, 0, sizeof(capheader));
301 capheader.version = _LINUX_CAPABILITY_VERSION_3;
302 capheader.pid = 0;
303
304 __user_cap_data_struct capdata[2];
305 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700306 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
307 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800308 }
309
310 capdata[0].inheritable = inheritable;
311 capdata[1].inheritable = inheritable >> 32;
312
313 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700314 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
315 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800316 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700317
318 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800319}
320
Andreas Gamped5758f62018-03-12 12:08:55 -0700321static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
322 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100323 __user_cap_header_struct capheader;
324 memset(&capheader, 0, sizeof(capheader));
325 capheader.version = _LINUX_CAPABILITY_VERSION_3;
326 capheader.pid = 0;
327
328 __user_cap_data_struct capdata[2];
329 memset(&capdata, 0, sizeof(capdata));
330 capdata[0].effective = effective;
331 capdata[1].effective = effective >> 32;
332 capdata[0].permitted = permitted;
333 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800334 capdata[0].inheritable = inheritable;
335 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100336
337 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700338 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
339 "failed: %s", permitted, effective, inheritable, strerror(errno));
340 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100341 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700342 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100343}
344
Andreas Gamped5758f62018-03-12 12:08:55 -0700345static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100346 errno = -set_sched_policy(0, SP_DEFAULT);
347 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700348 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
349 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100350 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700351 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100352}
353
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700354static int UnmountTree(const char* path) {
355 size_t path_len = strlen(path);
356
357 FILE* fp = setmntent("/proc/mounts", "r");
358 if (fp == NULL) {
359 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
360 return -errno;
361 }
362
363 // Some volumes can be stacked on each other, so force unmount in
364 // reverse order to give us the best chance of success.
365 std::list<std::string> toUnmount;
366 mntent* mentry;
367 while ((mentry = getmntent(fp)) != NULL) {
368 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
369 toUnmount.push_front(std::string(mentry->mnt_dir));
370 }
371 }
372 endmntent(fp);
373
374 for (auto path : toUnmount) {
375 if (umount2(path.c_str(), MNT_DETACH)) {
376 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
377 }
378 }
379 return 0;
380}
381
Narayan Kamath973b4662014-03-31 13:41:26 +0100382// Create a private mount namespace and bind mount appropriate emulated
383// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700384static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Andreas Gamped5758f62018-03-12 12:08:55 -0700385 bool force_mount_namespace, std::string* error_msg) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700386 // See storage config details at http://source.android.com/tech/storage/
387
Jeff Sharkey9527b222015-06-24 15:24:48 -0700388 String8 storageSource;
389 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700390 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700391 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700392 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700393 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700394 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500395 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700396 // Sane default of no storage visible
397 return true;
398 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400399
400 // Create a second private mount namespace for our process
401 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700402 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400403 return false;
404 }
405
Robert Sesek06f39302017-03-20 17:30:05 -0400406 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
407 if (mount_mode == MOUNT_EXTERNAL_NONE) {
408 return true;
409 }
410
Jeff Sharkey9527b222015-06-24 15:24:48 -0700411 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
412 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700413 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
414 storageSource.string(),
415 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700416 return false;
417 }
418
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700419 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700420 userid_t user_id = multiuser_get_user_id(uid);
421 const String8 userSource(String8::format("/mnt/user/%d", user_id));
422 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700423 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
Jeff Sharkey9527b222015-06-24 15:24:48 -0700424 return false;
425 }
426 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
427 NULL, MS_BIND, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700428 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
429 userSource.string(),
430 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700431 return false;
432 }
433
Narayan Kamath973b4662014-03-31 13:41:26 +0100434 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100435}
436
Narayan Kamath973b4662014-03-31 13:41:26 +0100437static bool NeedsNoRandomizeWorkaround() {
438#if !defined(__arm__)
439 return false;
440#else
441 int major;
442 int minor;
443 struct utsname uts;
444 if (uname(&uts) == -1) {
445 return false;
446 }
447
448 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
449 return false;
450 }
451
452 // Kernels before 3.4.* need the workaround.
453 return (major < 3) || ((major == 3) && (minor < 4));
454#endif
455}
Narayan Kamath973b4662014-03-31 13:41:26 +0100456
457// Utility to close down the Zygote socket file descriptors while
458// the child is still running as root with Zygote's privileges. Each
459// descriptor (if any) is closed via dup2(), replacing it with a valid
460// (open) descriptor to /dev/null.
461
Andreas Gamped5758f62018-03-12 12:08:55 -0700462static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100463 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700464 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100465 }
466 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200467 ScopedIntArrayRO ar(env, fdsToClose);
468 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700469 *error_msg = "Bad fd array";
470 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100471 }
472 jsize i;
473 int devnull;
474 for (i = 0; i < count; i++) {
475 devnull = open("/dev/null", O_RDWR);
476 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700477 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
478 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100479 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700480 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100481 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700482 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
483 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100484 }
485 close(devnull);
486 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700487 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100488}
489
490void SetThreadName(const char* thread_name) {
491 bool hasAt = false;
492 bool hasDot = false;
493 const char* s = thread_name;
494 while (*s) {
495 if (*s == '.') {
496 hasDot = true;
497 } else if (*s == '@') {
498 hasAt = true;
499 }
500 s++;
501 }
502 const int len = s - thread_name;
503 if (len < 15 || hasAt || !hasDot) {
504 s = thread_name;
505 } else {
506 s = thread_name + len - 15;
507 }
508 // pthread_setname_np fails rather than truncating long strings.
509 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
510 strlcpy(buf, s, sizeof(buf)-1);
511 errno = pthread_setname_np(pthread_self(), buf);
512 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700513 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100514 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800515 // Update base::logging default tag.
516 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100517}
518
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100519// The list of open zygote file descriptors.
520static FileDescriptorTable* gOpenFdTable = NULL;
521
Andreas Gamped5758f62018-03-12 12:08:55 -0700522static bool FillFileDescriptorVector(JNIEnv* env,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800523 jintArray java_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700524 std::vector<int>* fds,
525 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800526 CHECK(fds != nullptr);
527 if (java_fds != nullptr) {
528 ScopedIntArrayRO ar(env, java_fds);
529 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700530 *error_msg = "Bad fd array";
531 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800532 }
533 fds->reserve(ar.size());
534 for (size_t i = 0; i < ar.size(); ++i) {
535 fds->push_back(ar[i]);
536 }
537 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700538 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800539}
540
David Sehrde8d0bd2018-06-22 10:45:36 -0700541// Utility routine to specialize a zygote child process.
542static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
543 jint runtime_flags, jobjectArray javaRlimits,
544 jlong permittedCapabilities, jlong effectiveCapabilities,
545 jint mount_external, jstring java_se_info, jstring java_se_name,
546 bool is_system_server, bool is_child_zygote, jstring instructionSet,
547 jstring dataDir) {
548 std::string error_msg;
549
550 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
551 __attribute__ ((noreturn)) {
552 const char* se_name_c_str = nullptr;
553 std::unique_ptr<ScopedUtfChars> se_name;
554 if (java_se_name != nullptr) {
555 se_name.reset(new ScopedUtfChars(env, java_se_name));
556 se_name_c_str = se_name->c_str();
557 }
558 if (se_name_c_str == nullptr && is_system_server) {
559 se_name_c_str = "system_server";
560 }
561 const std::string& error_msg = (se_name_c_str == nullptr)
562 ? msg
563 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
564 env->FatalError(error_msg.c_str());
565 __builtin_unreachable();
566 };
567
568 // Keep capabilities across UID change, unless we're staying root.
569 if (uid != 0) {
570 if (!EnableKeepCapabilities(&error_msg)) {
571 fail_fn(error_msg);
572 }
573 }
574
575 if (!SetInheritable(permittedCapabilities, &error_msg)) {
576 fail_fn(error_msg);
577 }
578 if (!DropCapabilitiesBoundingSet(&error_msg)) {
579 fail_fn(error_msg);
580 }
581
582 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
583 && android::NativeBridgeAvailable();
584 if (use_native_bridge) {
585 ScopedUtfChars isa_string(env, instructionSet);
586 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
587 }
588 if (use_native_bridge && dataDir == NULL) {
589 // dataDir should never be null if we need to use a native bridge.
590 // In general, dataDir will never be null for normal applications. It can only happen in
591 // special cases (for isolated processes which are not associated with any app). These are
592 // launched by the framework and should not be emulated anyway.
593 use_native_bridge = false;
594 ALOGW("Native bridge will not be used because dataDir == NULL.");
595 }
596
597 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg)) {
598 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
599 if (errno == ENOTCONN || errno == EROFS) {
600 // When device is actively encrypting, we get ENOTCONN here
601 // since FUSE was mounted before the framework restarted.
602 // When encrypted device is booting, we get EROFS since
603 // FUSE hasn't been created yet by init.
604 // In either case, continue without external storage.
605 } else {
606 fail_fn(error_msg);
607 }
608 }
609
610 // If this zygote isn't root, it won't be able to create a process group,
611 // since the directory is owned by root.
612 if (!is_system_server && getuid() == 0) {
613 int rc = createProcessGroup(uid, getpid());
614 if (rc != 0) {
615 if (rc == -EROFS) {
616 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
617 } else {
618 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
619 }
620 }
621 }
622
623 if (!SetGids(env, javaGids, &error_msg)) {
624 fail_fn(error_msg);
625 }
626
627 if (!SetRLimits(env, javaRlimits, &error_msg)) {
628 fail_fn(error_msg);
629 }
630
631 if (use_native_bridge) {
632 ScopedUtfChars isa_string(env, instructionSet);
633 ScopedUtfChars data_dir(env, dataDir);
634 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
635 }
636
637 int rc = setresgid(gid, gid, gid);
638 if (rc == -1) {
639 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
640 }
641
642 // Must be called when the new process still has CAP_SYS_ADMIN, in this case, before changing
643 // uid from 0, which clears capabilities. The other alternative is to call
644 // prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that breaks SELinux domain transition (see
645 // b/71859146). As the result, privileged syscalls used below still need to be accessible in
646 // app process.
647 SetUpSeccompFilter(uid);
648
649 rc = setresuid(uid, uid, uid);
650 if (rc == -1) {
651 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
652 }
653
654 // The "dumpable" flag of a process, which controls core dump generation, is
655 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
656 // user or group ID changes. See proc(5) for possible values. In most cases,
657 // the value is 0, so core dumps are disabled for zygote children. However,
658 // when running in a Chrome OS container, the value is already set to 2,
659 // which allows the external crash reporter to collect all core dumps. Since
660 // only system crashes are interested, core dump is disabled for app
661 // processes. This also ensures compliance with CTS.
662 int dumpable = prctl(PR_GET_DUMPABLE);
663 if (dumpable == -1) {
664 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
665 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
666 }
667 if (dumpable == 2 && uid >= AID_APP) {
668 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
669 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
670 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
671 }
672 }
673
674 if (NeedsNoRandomizeWorkaround()) {
675 // Work around ARM kernel ASLR lossage (http://b/5817320).
676 int old_personality = personality(0xffffffff);
677 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
678 if (new_personality == -1) {
679 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
680 }
681 }
682
683 if (!SetCapabilities(permittedCapabilities, effectiveCapabilities, permittedCapabilities,
684 &error_msg)) {
685 fail_fn(error_msg);
686 }
687
688 if (!SetSchedulerPolicy(&error_msg)) {
689 fail_fn(error_msg);
690 }
691
692 const char* se_info_c_str = NULL;
693 ScopedUtfChars* se_info = NULL;
694 if (java_se_info != NULL) {
695 se_info = new ScopedUtfChars(env, java_se_info);
696 se_info_c_str = se_info->c_str();
697 if (se_info_c_str == NULL) {
698 fail_fn("se_info_c_str == NULL");
699 }
700 }
701 const char* se_name_c_str = NULL;
702 ScopedUtfChars* se_name = NULL;
703 if (java_se_name != NULL) {
704 se_name = new ScopedUtfChars(env, java_se_name);
705 se_name_c_str = se_name->c_str();
706 if (se_name_c_str == NULL) {
707 fail_fn("se_name_c_str == NULL");
708 }
709 }
710 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
711 if (rc == -1) {
712 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
713 is_system_server, se_info_c_str, se_name_c_str));
714 }
715
716 // Make it easier to debug audit logs by setting the main thread's name to the
717 // nice name rather than "app_process".
718 if (se_name_c_str == NULL && is_system_server) {
719 se_name_c_str = "system_server";
720 }
721 if (se_name_c_str != NULL) {
722 SetThreadName(se_name_c_str);
723 }
724
725 delete se_info;
726 delete se_name;
727
728 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
729 UnsetChldSignalHandler();
730
731 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
732 is_system_server, is_child_zygote, instructionSet);
733 if (env->ExceptionCheck()) {
734 fail_fn("Error calling post fork hooks.");
735 }
736}
737
Narayan Kamath973b4662014-03-31 13:41:26 +0100738// Utility routine to fork zygote and specialize the child process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700739static pid_t ForkCommon(JNIEnv* env, jstring java_se_name, bool is_system_server,
740 jintArray fdsToClose, jintArray fdsToIgnore) {
yuanhao435e84b2018-01-15 15:37:02 +0800741 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100742
David Sehrde8d0bd2018-06-22 10:45:36 -0700743 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000744 sigset_t sigchld;
745 sigemptyset(&sigchld);
746 sigaddset(&sigchld, SIGCHLD);
747
Andreas Gampe5f35c4e2018-03-12 12:17:25 -0700748 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
749 __attribute__ ((noreturn)) {
750 const char* se_name_c_str = nullptr;
751 std::unique_ptr<ScopedUtfChars> se_name;
752 if (java_se_name != nullptr) {
753 se_name.reset(new ScopedUtfChars(env, java_se_name));
754 se_name_c_str = se_name->c_str();
755 }
756 if (se_name_c_str == nullptr && is_system_server) {
757 se_name_c_str = "system_server";
758 }
759 const std::string& error_msg = (se_name_c_str == nullptr)
760 ? msg
761 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
762 env->FatalError(error_msg.c_str());
Andreas Gamped5758f62018-03-12 12:08:55 -0700763 __builtin_unreachable();
764 };
765
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000766 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
767 // log, which would result in the logging FDs we close being reopened.
768 // This would cause failures because the FDs are not whitelisted.
769 //
770 // Note that the zygote process is single threaded at this point.
771 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700772 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000773 }
774
Narayan Kamath3764a262016-08-30 15:36:19 +0100775 // Close any logging related FDs before we start evaluating the list of
776 // file descriptors.
777 __android_log_close();
778
Andreas Gamped5758f62018-03-12 12:08:55 -0700779 std::string error_msg;
780
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100781 // If this is the first fork for this zygote, create the open FD table.
782 // If it isn't, we just need to check whether the list of open files has
783 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800784 std::vector<int> fds_to_ignore;
Andreas Gamped5758f62018-03-12 12:08:55 -0700785 if (!FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore, &error_msg)) {
786 fail_fn(error_msg);
787 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100788 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700789 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100790 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700791 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100792 }
Andreas Gampec362a442018-03-12 14:53:34 -0700793 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
794 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100795 }
796
Josh Gaod7951102018-06-26 16:05:12 -0700797 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
798
Narayan Kamath973b4662014-03-31 13:41:26 +0100799 pid_t pid = fork();
800
801 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700802 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700803 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700804
Narayan Kamath973b4662014-03-31 13:41:26 +0100805 // Clean up any descriptors which must be closed immediately
Andreas Gamped5758f62018-03-12 12:08:55 -0700806 if (!DetachDescriptors(env, fdsToClose, &error_msg)) {
807 fail_fn(error_msg);
808 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100809
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100810 // Re-open all remaining open file descriptors so that they aren't shared
811 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700812 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
813 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100814 }
Josh Gaod7951102018-06-26 16:05:12 -0700815
816 // Turn fdsan back on.
817 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -0700818 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100819
David Sehrde8d0bd2018-06-22 10:45:36 -0700820 // We blocked SIGCHLD prior to a fork, we unblock it here.
821 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
822 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100823 }
824 return pid;
825}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700826
827static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
828 __user_cap_header_struct capheader;
829 memset(&capheader, 0, sizeof(capheader));
830 capheader.version = _LINUX_CAPABILITY_VERSION_3;
831 capheader.pid = 0;
832
833 __user_cap_data_struct capdata[2];
834 if (capget(&capheader, &capdata[0]) == -1) {
835 ALOGE("capget failed: %s", strerror(errno));
836 RuntimeAbort(env, __LINE__, "capget failed");
837 }
838
839 return capdata[0].effective |
840 (static_cast<uint64_t>(capdata[1].effective) << 32);
841}
Narayan Kamath973b4662014-03-31 13:41:26 +0100842} // anonymous namespace
843
844namespace android {
845
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800846static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
847 // security_getenforce is not allowed on app process. Initialize and cache the value before
848 // zygote forks.
849 g_is_security_enforced = security_getenforce();
850}
851
Christopher Ferris76de39e2017-06-20 16:13:40 -0700852static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
853 PreApplicationInit();
854}
855
Narayan Kamath973b4662014-03-31 13:41:26 +0100856static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
857 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100858 jint runtime_flags, jobjectArray rlimits,
Narayan Kamath973b4662014-03-31 13:41:26 +0100859 jint mount_external, jstring se_info, jstring se_name,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500860 jintArray fdsToClose, jintArray fdsToIgnore, jboolean is_child_zygote,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800861 jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700862 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800863
864 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900865 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
Philip Cuadra0fabba32017-04-26 13:49:37 -0700866 // Grant CAP_SYS_NICE to allow Bluetooth to set RT priority for
867 // audio-related threads.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900868 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800869 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800870 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900871 capabilities |= (1LL << CAP_NET_RAW);
872 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Philip Cuadra0fabba32017-04-26 13:49:37 -0700873 capabilities |= (1LL << CAP_SYS_NICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800874 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700875
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800876 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
877 bool gid_wakelock_found = false;
878 if (gid == AID_WAKELOCK) {
879 gid_wakelock_found = true;
880 } else if (gids != NULL) {
881 jsize gids_num = env->GetArrayLength(gids);
882 ScopedIntArrayRO ar(env, gids);
883 if (ar.get() == NULL) {
884 RuntimeAbort(env, __LINE__, "Bad gids array");
885 }
886 for (int i = 0; i < gids_num; i++) {
887 if (ar[i] == AID_WAKELOCK) {
888 gid_wakelock_found = true;
889 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700890 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800891 }
892 }
893 if (gid_wakelock_found) {
894 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700895 }
896
Robert Sesekd0a190df2018-02-12 18:46:01 -0500897 // If forking a child zygote process, that zygote will need to be able to change
898 // the UID and GID of processes it forks, as well as drop those capabilities.
899 if (is_child_zygote) {
900 capabilities |= (1LL << CAP_SETUID);
901 capabilities |= (1LL << CAP_SETGID);
902 capabilities |= (1LL << CAP_SETPCAP);
903 }
904
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700905 // Containers run without some capabilities, so drop any caps that are not
906 // available.
907 capabilities &= GetEffectiveCapabilityMask(env);
908
David Sehrde8d0bd2018-06-22 10:45:36 -0700909 pid_t pid = ForkCommon(env, se_name, false, fdsToClose, fdsToIgnore);
910 if (pid == 0) {
911 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
912 capabilities, capabilities,
913 mount_external, se_info, se_name, false,
914 is_child_zygote == JNI_TRUE, instructionSet, appDataDir);
915 }
916 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100917}
918
919static jint com_android_internal_os_Zygote_nativeForkSystemServer(
920 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100921 jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities,
Narayan Kamath973b4662014-03-31 13:41:26 +0100922 jlong effectiveCapabilities) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700923 pid_t pid = ForkCommon(env, NULL, true, NULL, NULL);
924 if (pid == 0) {
925 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
926 permittedCapabilities, effectiveCapabilities,
927 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true,
928 false, NULL, NULL);
929 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100930 // The zygote process checks whether the child process has died or not.
931 ALOGI("System server process %d has been created", pid);
932 gSystemServerPid = pid;
933 // There is a slight window that the system server process has crashed
934 // but it went unnoticed because we haven't published its pid yet. So
935 // we recheck here just to make sure that all is well.
936 int status;
937 if (waitpid(pid, &status, WNOHANG) == pid) {
938 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800939 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100940 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800941
Minchan Kim696873e2018-06-27 11:32:40 +0900942 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
943 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
944 if (per_app_memcg) {
945 // Assign system_server to the correct memory cgroup.
946 // Not all devices mount /dev/memcg so check for the file first
947 // to avoid unnecessarily printing errors and denials in the logs.
948 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -0800949 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim696873e2018-06-27 11:32:40 +0900950 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
951 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800952 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100953 }
954 return pid;
955}
956
Robert Sesek54e387d2016-12-02 17:27:50 -0500957static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
958 JNIEnv* env, jclass, jstring path) {
959 ScopedUtfChars path_native(env, path);
960 const char* path_cstr = path_native.c_str();
961 if (!path_cstr) {
962 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
963 }
964 FileDescriptorWhitelist::Get()->Allow(path_cstr);
965}
966
doheon1.lee885b7422016-01-20 13:07:27 +0900967static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
968 // Zygote process unmount root storage space initially before every child processes are forked.
969 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400970 // and no need unmount storage operation in MountEmulatedStorage method.
971 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
972
973 // See storage config details at http://source.android.com/tech/storage/
974 // Create private mount namespace shared by all children
975 if (unshare(CLONE_NEWNS) == -1) {
976 RuntimeAbort(env, __LINE__, "Failed to unshare()");
977 return;
978 }
979
980 // Mark rootfs as being a slave so that changes from default
981 // namespace only flow into our children.
982 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
983 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
984 return;
985 }
986
987 // Create a staging tmpfs that is shared by our children; they will
988 // bind mount storage into their respective private namespaces, which
989 // are isolated from each other.
990 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
991 if (target_base != nullptr) {
992#define STRINGIFY_UID(x) __STRING(x)
993 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
994 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
995 ALOGE("Failed to mount tmpfs to %s", target_base);
996 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
997 return;
998 }
999#undef STRINGIFY_UID
1000 }
doheon1.lee885b7422016-01-20 13:07:27 +09001001
1002 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001003}
1004
Daniel Micay76f6a862015-09-19 17:31:01 -04001005static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001006 { "nativeSecurityInit", "()V",
1007 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001008 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001009 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001010 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1011 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001012 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001013 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1014 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001015 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001016 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1017 { "nativePreApplicationInit", "()V",
1018 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001019};
1020
1021int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001022 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
1023 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001024 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001025
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001026 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001027}
1028} // namespace android