blob: 6f400c42bcbe37aa682cfb93824b1f5476e7ff72 [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>
Howard Ro65e48ec2018-10-02 12:08:28 -070059#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070060#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070061
Andreas Gampeed6b9df2014-11-20 22:02:20 -080062#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070063#include <nativehelper/JNIHelp.h>
64#include <nativehelper/ScopedLocalRef.h>
65#include <nativehelper/ScopedPrimitiveArray.h>
66#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050067#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010068
jgu212eacd062014-09-10 06:55:07 -040069#include "nativebridge/native_bridge.h"
70
Narayan Kamath973b4662014-03-31 13:41:26 +010071namespace {
72
73using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080074using android::base::StringPrintf;
75using android::base::WriteStringToFile;
Minchan Kim696873e2018-06-27 11:32:40 +090076using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010077
Andreas Gamped5758f62018-03-12 12:08:55 -070078#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
79 append(StringPrintf(__VA_ARGS__))
80
Narayan Kamath973b4662014-03-31 13:41:26 +010081static pid_t gSystemServerPid = 0;
82
83static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
84static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +010085static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +010086static jmethodID gCallPostForkChildHooks;
87
Victor Hsiehc8176ef2018-01-08 12:43:00 -080088static bool g_is_security_enforced = true;
89
Narayan Kamath973b4662014-03-31 13:41:26 +010090// Must match values in com.android.internal.os.Zygote.
91enum MountExternalKind {
92 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070093 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070094 MOUNT_EXTERNAL_READ = 2,
95 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010096};
97
Andreas Gampeb053cce2015-11-17 16:38:59 -080098static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
99 std::ostringstream oss;
100 oss << __FILE__ << ":" << line << ": " << msg;
101 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100102}
103
104// This signal handler is for zygote mode, since the zygote must reap its children
105static void SigChldHandler(int /*signal_number*/) {
106 pid_t pid;
107 int status;
108
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700109 // It's necessary to save and restore the errno during this function.
110 // Since errno is stored per thread, changing it here modifies the errno
111 // on the thread on which this signal handler executes. If a signal occurs
112 // between a call and an errno check, it's possible to get the errno set
113 // here.
114 // See b/23572286 for extra information.
115 int saved_errno = errno;
116
Narayan Kamath973b4662014-03-31 13:41:26 +0100117 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
118 // Log process-death status that we care about. In general it is
119 // not safe to call LOG(...) from a signal handler because of
120 // possible reentrancy. However, we know a priori that the
121 // current implementation of LOG() is safe to call from a SIGCHLD
122 // handler in the zygote process. If the LOG() implementation
123 // changes its locking strategy or its use of syscalls within the
124 // lazy-init critical section, its use here may become unsafe.
125 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700126 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100127 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700128 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100129 if (WCOREDUMP(status)) {
130 ALOGI("Process %d dumped core.", pid);
131 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100132 }
133
134 // If the just-crashed process is the system_server, bring down zygote
135 // so that it is restarted by init and system server will be restarted
136 // from there.
137 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800138 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100139 kill(getpid(), SIGKILL);
140 }
141 }
142
Narayan Kamath160992d2014-04-14 14:46:07 +0100143 // Note that we shouldn't consider ECHILD an error because
144 // the secondary zygote might have no children left to wait for.
145 if (pid < 0 && errno != ECHILD) {
146 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100147 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700148
149 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100150}
151
yuanhao435e84b2018-01-15 15:37:02 +0800152// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
153// configured very late, because earlier in the runtime we may fork() and
154// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100155// have them be harvested immediately.
156//
yuanhao435e84b2018-01-15 15:37:02 +0800157// Ignore SIGHUP because all processes forked by the zygote are in the same
158// process group as the zygote and we don't want to be notified if we become
159// an orphaned group and have one or more stopped processes. This is not a
160// theoretical concern :
161// - we can become an orphaned group if one of our direct descendants forks
162// and is subsequently killed before its children.
163// - crash_dump routinely STOPs the process it's tracing.
164//
165// See issues b/71965619 and b/25567761 for further details.
166//
Narayan Kamath973b4662014-03-31 13:41:26 +0100167// This ends up being called repeatedly before each fork(), but there's
168// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800169static void SetSignalHandlers() {
170 struct sigaction sig_chld = {};
171 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100172
yuanhao435e84b2018-01-15 15:37:02 +0800173 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700174 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100175 }
yuanhao435e84b2018-01-15 15:37:02 +0800176
177 struct sigaction sig_hup = {};
178 sig_hup.sa_handler = SIG_IGN;
179 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
180 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
181 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100182}
183
184// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800185static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100186 struct sigaction sa;
187 memset(&sa, 0, sizeof(sa));
188 sa.sa_handler = SIG_DFL;
189
yuanhao435e84b2018-01-15 15:37:02 +0800190 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700191 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100192 }
193}
194
195// Calls POSIX setgroups() using the int[] object as an argument.
196// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700197static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100198 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700199 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100200 }
201
202 ScopedIntArrayRO gids(env, javaGids);
203 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700204 *error_msg = CREATE_ERROR("Getting gids int array failed");
205 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100206 }
207 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
208 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700209 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
210 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100211 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700212
213 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100214}
215
216// Sets the resource limits via setrlimit(2) for the values in the
217// two-dimensional array of integers that's passed in. The second dimension
218// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
219// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700220static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100221 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700222 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100223 }
224
225 rlimit rlim;
226 memset(&rlim, 0, sizeof(rlim));
227
228 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
229 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
230 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
231 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700232 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
233 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100234 }
235
236 rlim.rlim_cur = javaRlimit[1];
237 rlim.rlim_max = javaRlimit[2];
238
239 int rc = setrlimit(javaRlimit[0], &rlim);
240 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700241 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800242 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700243 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100244 }
245 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700246
247 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100248}
249
Narayan Kamath973b4662014-03-31 13:41:26 +0100250// The debug malloc library needs to know whether it's the zygote or a child.
251extern "C" int gMallocLeakZygoteChild;
252
Christopher Ferris76de39e2017-06-20 16:13:40 -0700253static void PreApplicationInit() {
254 // The child process sets this to indicate it's not the zygote.
255 gMallocLeakZygoteChild = 1;
256
257 // Set the jemalloc decay time to 1.
258 mallopt(M_DECAY_TIME, 1);
259}
260
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800261static void SetUpSeccompFilter(uid_t uid) {
262 if (!g_is_security_enforced) {
263 ALOGI("seccomp disabled by setenforce 0");
264 return;
265 }
266
267 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700268 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800269 set_app_seccomp_filter();
270 } else {
271 set_system_seccomp_filter();
272 }
273}
274
Andreas Gamped5758f62018-03-12 12:08:55 -0700275static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100276 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
277 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700278 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
279 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100280 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700281 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100282}
283
Andreas Gamped5758f62018-03-12 12:08:55 -0700284static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100285 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
286 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
287 if (rc == -1) {
288 if (errno == EINVAL) {
289 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
290 "your kernel is compiled with file capabilities support");
291 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700292 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
293 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100294 }
295 }
296 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700297 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100298}
299
Andreas Gamped5758f62018-03-12 12:08:55 -0700300static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800301 __user_cap_header_struct capheader;
302 memset(&capheader, 0, sizeof(capheader));
303 capheader.version = _LINUX_CAPABILITY_VERSION_3;
304 capheader.pid = 0;
305
306 __user_cap_data_struct capdata[2];
307 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700308 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
309 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800310 }
311
312 capdata[0].inheritable = inheritable;
313 capdata[1].inheritable = inheritable >> 32;
314
315 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700316 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
317 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800318 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700319
320 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800321}
322
Andreas Gamped5758f62018-03-12 12:08:55 -0700323static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
324 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100325 __user_cap_header_struct capheader;
326 memset(&capheader, 0, sizeof(capheader));
327 capheader.version = _LINUX_CAPABILITY_VERSION_3;
328 capheader.pid = 0;
329
330 __user_cap_data_struct capdata[2];
331 memset(&capdata, 0, sizeof(capdata));
332 capdata[0].effective = effective;
333 capdata[1].effective = effective >> 32;
334 capdata[0].permitted = permitted;
335 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800336 capdata[0].inheritable = inheritable;
337 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100338
339 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700340 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
341 "failed: %s", permitted, effective, inheritable, strerror(errno));
342 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100343 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700344 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100345}
346
Andreas Gamped5758f62018-03-12 12:08:55 -0700347static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100348 errno = -set_sched_policy(0, SP_DEFAULT);
349 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700350 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
351 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100352 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700353 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100354}
355
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700356static int UnmountTree(const char* path) {
357 size_t path_len = strlen(path);
358
359 FILE* fp = setmntent("/proc/mounts", "r");
360 if (fp == NULL) {
361 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
362 return -errno;
363 }
364
365 // Some volumes can be stacked on each other, so force unmount in
366 // reverse order to give us the best chance of success.
367 std::list<std::string> toUnmount;
368 mntent* mentry;
369 while ((mentry = getmntent(fp)) != NULL) {
370 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
371 toUnmount.push_front(std::string(mentry->mnt_dir));
372 }
373 }
374 endmntent(fp);
375
376 for (auto path : toUnmount) {
377 if (umount2(path.c_str(), MNT_DETACH)) {
378 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
379 }
380 }
381 return 0;
382}
383
Narayan Kamath973b4662014-03-31 13:41:26 +0100384// Create a private mount namespace and bind mount appropriate emulated
385// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700386static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Andreas Gamped5758f62018-03-12 12:08:55 -0700387 bool force_mount_namespace, std::string* error_msg) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700388 // See storage config details at http://source.android.com/tech/storage/
389
Jeff Sharkey9527b222015-06-24 15:24:48 -0700390 String8 storageSource;
391 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700392 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700393 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700394 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700395 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700396 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500397 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700398 // Sane default of no storage visible
399 return true;
400 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400401
402 // Create a second private mount namespace for our process
403 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700404 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400405 return false;
406 }
407
Robert Sesek06f39302017-03-20 17:30:05 -0400408 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
409 if (mount_mode == MOUNT_EXTERNAL_NONE) {
410 return true;
411 }
412
Jeff Sharkey9527b222015-06-24 15:24:48 -0700413 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
414 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700415 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
416 storageSource.string(),
417 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700418 return false;
419 }
420
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700421 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700422 userid_t user_id = multiuser_get_user_id(uid);
423 const String8 userSource(String8::format("/mnt/user/%d", user_id));
424 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700425 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
Jeff Sharkey9527b222015-06-24 15:24:48 -0700426 return false;
427 }
428 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
429 NULL, MS_BIND, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700430 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
431 userSource.string(),
432 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700433 return false;
434 }
435
Narayan Kamath973b4662014-03-31 13:41:26 +0100436 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100437}
438
Narayan Kamath973b4662014-03-31 13:41:26 +0100439static bool NeedsNoRandomizeWorkaround() {
440#if !defined(__arm__)
441 return false;
442#else
443 int major;
444 int minor;
445 struct utsname uts;
446 if (uname(&uts) == -1) {
447 return false;
448 }
449
450 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
451 return false;
452 }
453
454 // Kernels before 3.4.* need the workaround.
455 return (major < 3) || ((major == 3) && (minor < 4));
456#endif
457}
Narayan Kamath973b4662014-03-31 13:41:26 +0100458
459// Utility to close down the Zygote socket file descriptors while
460// the child is still running as root with Zygote's privileges. Each
461// descriptor (if any) is closed via dup2(), replacing it with a valid
462// (open) descriptor to /dev/null.
463
Andreas Gamped5758f62018-03-12 12:08:55 -0700464static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100465 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700466 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100467 }
468 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200469 ScopedIntArrayRO ar(env, fdsToClose);
470 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700471 *error_msg = "Bad fd array";
472 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100473 }
474 jsize i;
475 int devnull;
476 for (i = 0; i < count; i++) {
477 devnull = open("/dev/null", O_RDWR);
478 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700479 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
480 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100481 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700482 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100483 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700484 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
485 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100486 }
487 close(devnull);
488 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700489 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100490}
491
492void SetThreadName(const char* thread_name) {
493 bool hasAt = false;
494 bool hasDot = false;
495 const char* s = thread_name;
496 while (*s) {
497 if (*s == '.') {
498 hasDot = true;
499 } else if (*s == '@') {
500 hasAt = true;
501 }
502 s++;
503 }
504 const int len = s - thread_name;
505 if (len < 15 || hasAt || !hasDot) {
506 s = thread_name;
507 } else {
508 s = thread_name + len - 15;
509 }
510 // pthread_setname_np fails rather than truncating long strings.
511 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
512 strlcpy(buf, s, sizeof(buf)-1);
513 errno = pthread_setname_np(pthread_self(), buf);
514 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700515 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100516 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800517 // Update base::logging default tag.
518 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100519}
520
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100521// The list of open zygote file descriptors.
522static FileDescriptorTable* gOpenFdTable = NULL;
523
Andreas Gamped5758f62018-03-12 12:08:55 -0700524static bool FillFileDescriptorVector(JNIEnv* env,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800525 jintArray java_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700526 std::vector<int>* fds,
527 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800528 CHECK(fds != nullptr);
529 if (java_fds != nullptr) {
530 ScopedIntArrayRO ar(env, java_fds);
531 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700532 *error_msg = "Bad fd array";
533 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800534 }
535 fds->reserve(ar.size());
536 for (size_t i = 0; i < ar.size(); ++i) {
537 fds->push_back(ar[i]);
538 }
539 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700540 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800541}
542
David Sehrde8d0bd2018-06-22 10:45:36 -0700543// Utility routine to specialize a zygote child process.
544static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
545 jint runtime_flags, jobjectArray javaRlimits,
546 jlong permittedCapabilities, jlong effectiveCapabilities,
547 jint mount_external, jstring java_se_info, jstring java_se_name,
548 bool is_system_server, bool is_child_zygote, jstring instructionSet,
549 jstring dataDir) {
550 std::string error_msg;
551
552 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
553 __attribute__ ((noreturn)) {
554 const char* se_name_c_str = nullptr;
555 std::unique_ptr<ScopedUtfChars> se_name;
556 if (java_se_name != nullptr) {
557 se_name.reset(new ScopedUtfChars(env, java_se_name));
558 se_name_c_str = se_name->c_str();
559 }
560 if (se_name_c_str == nullptr && is_system_server) {
561 se_name_c_str = "system_server";
562 }
563 const std::string& error_msg = (se_name_c_str == nullptr)
564 ? msg
565 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
566 env->FatalError(error_msg.c_str());
567 __builtin_unreachable();
568 };
569
570 // Keep capabilities across UID change, unless we're staying root.
571 if (uid != 0) {
572 if (!EnableKeepCapabilities(&error_msg)) {
573 fail_fn(error_msg);
574 }
575 }
576
577 if (!SetInheritable(permittedCapabilities, &error_msg)) {
578 fail_fn(error_msg);
579 }
580 if (!DropCapabilitiesBoundingSet(&error_msg)) {
581 fail_fn(error_msg);
582 }
583
584 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
585 && android::NativeBridgeAvailable();
586 if (use_native_bridge) {
587 ScopedUtfChars isa_string(env, instructionSet);
588 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
589 }
590 if (use_native_bridge && dataDir == NULL) {
591 // dataDir should never be null if we need to use a native bridge.
592 // In general, dataDir will never be null for normal applications. It can only happen in
593 // special cases (for isolated processes which are not associated with any app). These are
594 // launched by the framework and should not be emulated anyway.
595 use_native_bridge = false;
596 ALOGW("Native bridge will not be used because dataDir == NULL.");
597 }
598
599 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg)) {
600 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
601 if (errno == ENOTCONN || errno == EROFS) {
602 // When device is actively encrypting, we get ENOTCONN here
603 // since FUSE was mounted before the framework restarted.
604 // When encrypted device is booting, we get EROFS since
605 // FUSE hasn't been created yet by init.
606 // In either case, continue without external storage.
607 } else {
608 fail_fn(error_msg);
609 }
610 }
611
612 // If this zygote isn't root, it won't be able to create a process group,
613 // since the directory is owned by root.
614 if (!is_system_server && getuid() == 0) {
615 int rc = createProcessGroup(uid, getpid());
616 if (rc != 0) {
617 if (rc == -EROFS) {
618 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
619 } else {
620 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
621 }
622 }
623 }
624
625 if (!SetGids(env, javaGids, &error_msg)) {
626 fail_fn(error_msg);
627 }
628
629 if (!SetRLimits(env, javaRlimits, &error_msg)) {
630 fail_fn(error_msg);
631 }
632
633 if (use_native_bridge) {
634 ScopedUtfChars isa_string(env, instructionSet);
635 ScopedUtfChars data_dir(env, dataDir);
636 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
637 }
638
639 int rc = setresgid(gid, gid, gid);
640 if (rc == -1) {
641 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
642 }
643
644 // Must be called when the new process still has CAP_SYS_ADMIN, in this case, before changing
645 // uid from 0, which clears capabilities. The other alternative is to call
646 // prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that breaks SELinux domain transition (see
647 // b/71859146). As the result, privileged syscalls used below still need to be accessible in
648 // app process.
649 SetUpSeccompFilter(uid);
650
651 rc = setresuid(uid, uid, uid);
652 if (rc == -1) {
653 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
654 }
655
656 // The "dumpable" flag of a process, which controls core dump generation, is
657 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
658 // user or group ID changes. See proc(5) for possible values. In most cases,
659 // the value is 0, so core dumps are disabled for zygote children. However,
660 // when running in a Chrome OS container, the value is already set to 2,
661 // which allows the external crash reporter to collect all core dumps. Since
662 // only system crashes are interested, core dump is disabled for app
663 // processes. This also ensures compliance with CTS.
664 int dumpable = prctl(PR_GET_DUMPABLE);
665 if (dumpable == -1) {
666 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
667 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
668 }
669 if (dumpable == 2 && uid >= AID_APP) {
670 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
671 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
672 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
673 }
674 }
675
676 if (NeedsNoRandomizeWorkaround()) {
677 // Work around ARM kernel ASLR lossage (http://b/5817320).
678 int old_personality = personality(0xffffffff);
679 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
680 if (new_personality == -1) {
681 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
682 }
683 }
684
685 if (!SetCapabilities(permittedCapabilities, effectiveCapabilities, permittedCapabilities,
686 &error_msg)) {
687 fail_fn(error_msg);
688 }
689
690 if (!SetSchedulerPolicy(&error_msg)) {
691 fail_fn(error_msg);
692 }
693
694 const char* se_info_c_str = NULL;
695 ScopedUtfChars* se_info = NULL;
696 if (java_se_info != NULL) {
697 se_info = new ScopedUtfChars(env, java_se_info);
698 se_info_c_str = se_info->c_str();
699 if (se_info_c_str == NULL) {
700 fail_fn("se_info_c_str == NULL");
701 }
702 }
703 const char* se_name_c_str = NULL;
704 ScopedUtfChars* se_name = NULL;
705 if (java_se_name != NULL) {
706 se_name = new ScopedUtfChars(env, java_se_name);
707 se_name_c_str = se_name->c_str();
708 if (se_name_c_str == NULL) {
709 fail_fn("se_name_c_str == NULL");
710 }
711 }
712 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
713 if (rc == -1) {
714 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
715 is_system_server, se_info_c_str, se_name_c_str));
716 }
717
718 // Make it easier to debug audit logs by setting the main thread's name to the
719 // nice name rather than "app_process".
720 if (se_name_c_str == NULL && is_system_server) {
721 se_name_c_str = "system_server";
722 }
723 if (se_name_c_str != NULL) {
724 SetThreadName(se_name_c_str);
725 }
726
727 delete se_info;
728 delete se_name;
729
730 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
731 UnsetChldSignalHandler();
732
Orion Hodson46724e72018-10-19 13:05:33 +0100733 if (is_system_server) {
734 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
735 if (env->ExceptionCheck()) {
736 fail_fn("Error calling post fork system server hooks.");
737 }
738 // TODO(oth): Remove hardcoded label here (b/117874058).
739 static const char* kSystemServerLabel = "u:r:system_server:s0";
740 if (selinux_android_setcon(kSystemServerLabel) != 0) {
741 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
742 }
743 }
744
David Sehrde8d0bd2018-06-22 10:45:36 -0700745 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
746 is_system_server, is_child_zygote, instructionSet);
747 if (env->ExceptionCheck()) {
748 fail_fn("Error calling post fork hooks.");
749 }
750}
751
Narayan Kamath973b4662014-03-31 13:41:26 +0100752// Utility routine to fork zygote and specialize the child process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700753static pid_t ForkCommon(JNIEnv* env, jstring java_se_name, bool is_system_server,
754 jintArray fdsToClose, jintArray fdsToIgnore) {
yuanhao435e84b2018-01-15 15:37:02 +0800755 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100756
David Sehrde8d0bd2018-06-22 10:45:36 -0700757 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000758 sigset_t sigchld;
759 sigemptyset(&sigchld);
760 sigaddset(&sigchld, SIGCHLD);
761
Andreas Gampe5f35c4e2018-03-12 12:17:25 -0700762 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
763 __attribute__ ((noreturn)) {
764 const char* se_name_c_str = nullptr;
765 std::unique_ptr<ScopedUtfChars> se_name;
766 if (java_se_name != nullptr) {
767 se_name.reset(new ScopedUtfChars(env, java_se_name));
768 se_name_c_str = se_name->c_str();
769 }
770 if (se_name_c_str == nullptr && is_system_server) {
771 se_name_c_str = "system_server";
772 }
773 const std::string& error_msg = (se_name_c_str == nullptr)
774 ? msg
775 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
776 env->FatalError(error_msg.c_str());
Andreas Gamped5758f62018-03-12 12:08:55 -0700777 __builtin_unreachable();
778 };
779
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000780 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
781 // log, which would result in the logging FDs we close being reopened.
782 // This would cause failures because the FDs are not whitelisted.
783 //
784 // Note that the zygote process is single threaded at this point.
785 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700786 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000787 }
788
Narayan Kamath3764a262016-08-30 15:36:19 +0100789 // Close any logging related FDs before we start evaluating the list of
790 // file descriptors.
791 __android_log_close();
Howard Ro65e48ec2018-10-02 12:08:28 -0700792 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +0100793
Andreas Gamped5758f62018-03-12 12:08:55 -0700794 std::string error_msg;
795
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100796 // If this is the first fork for this zygote, create the open FD table.
797 // If it isn't, we just need to check whether the list of open files has
798 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800799 std::vector<int> fds_to_ignore;
Andreas Gamped5758f62018-03-12 12:08:55 -0700800 if (!FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore, &error_msg)) {
801 fail_fn(error_msg);
802 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100803 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700804 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100805 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700806 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100807 }
Andreas Gampec362a442018-03-12 14:53:34 -0700808 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
809 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100810 }
811
Josh Gaod7951102018-06-26 16:05:12 -0700812 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
813
Narayan Kamath973b4662014-03-31 13:41:26 +0100814 pid_t pid = fork();
815
816 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700817 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700818 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700819
Narayan Kamath973b4662014-03-31 13:41:26 +0100820 // Clean up any descriptors which must be closed immediately
Andreas Gamped5758f62018-03-12 12:08:55 -0700821 if (!DetachDescriptors(env, fdsToClose, &error_msg)) {
822 fail_fn(error_msg);
823 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100824
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100825 // Re-open all remaining open file descriptors so that they aren't shared
826 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700827 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
828 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100829 }
Josh Gaod7951102018-06-26 16:05:12 -0700830
831 // Turn fdsan back on.
832 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -0700833 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100834
David Sehrde8d0bd2018-06-22 10:45:36 -0700835 // We blocked SIGCHLD prior to a fork, we unblock it here.
836 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
837 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100838 }
839 return pid;
840}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700841
842static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
843 __user_cap_header_struct capheader;
844 memset(&capheader, 0, sizeof(capheader));
845 capheader.version = _LINUX_CAPABILITY_VERSION_3;
846 capheader.pid = 0;
847
848 __user_cap_data_struct capdata[2];
849 if (capget(&capheader, &capdata[0]) == -1) {
850 ALOGE("capget failed: %s", strerror(errno));
851 RuntimeAbort(env, __LINE__, "capget failed");
852 }
853
854 return capdata[0].effective |
855 (static_cast<uint64_t>(capdata[1].effective) << 32);
856}
Narayan Kamath973b4662014-03-31 13:41:26 +0100857} // anonymous namespace
858
859namespace android {
860
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800861static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
862 // security_getenforce is not allowed on app process. Initialize and cache the value before
863 // zygote forks.
864 g_is_security_enforced = security_getenforce();
865}
866
Christopher Ferris76de39e2017-06-20 16:13:40 -0700867static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
868 PreApplicationInit();
869}
870
Narayan Kamath973b4662014-03-31 13:41:26 +0100871static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
872 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100873 jint runtime_flags, jobjectArray rlimits,
Narayan Kamath973b4662014-03-31 13:41:26 +0100874 jint mount_external, jstring se_info, jstring se_name,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500875 jintArray fdsToClose, jintArray fdsToIgnore, jboolean is_child_zygote,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800876 jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700877 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800878
879 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900880 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
Philip Cuadra0fabba32017-04-26 13:49:37 -0700881 // Grant CAP_SYS_NICE to allow Bluetooth to set RT priority for
882 // audio-related threads.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900883 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800884 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800885 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900886 capabilities |= (1LL << CAP_NET_RAW);
887 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Philip Cuadra0fabba32017-04-26 13:49:37 -0700888 capabilities |= (1LL << CAP_SYS_NICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800889 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700890
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800891 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
892 bool gid_wakelock_found = false;
893 if (gid == AID_WAKELOCK) {
894 gid_wakelock_found = true;
895 } else if (gids != NULL) {
896 jsize gids_num = env->GetArrayLength(gids);
897 ScopedIntArrayRO ar(env, gids);
898 if (ar.get() == NULL) {
899 RuntimeAbort(env, __LINE__, "Bad gids array");
900 }
901 for (int i = 0; i < gids_num; i++) {
902 if (ar[i] == AID_WAKELOCK) {
903 gid_wakelock_found = true;
904 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700905 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800906 }
907 }
908 if (gid_wakelock_found) {
909 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700910 }
911
Robert Sesekd0a190df2018-02-12 18:46:01 -0500912 // If forking a child zygote process, that zygote will need to be able to change
913 // the UID and GID of processes it forks, as well as drop those capabilities.
914 if (is_child_zygote) {
915 capabilities |= (1LL << CAP_SETUID);
916 capabilities |= (1LL << CAP_SETGID);
917 capabilities |= (1LL << CAP_SETPCAP);
918 }
919
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700920 // Containers run without some capabilities, so drop any caps that are not
921 // available.
922 capabilities &= GetEffectiveCapabilityMask(env);
923
David Sehrde8d0bd2018-06-22 10:45:36 -0700924 pid_t pid = ForkCommon(env, se_name, false, fdsToClose, fdsToIgnore);
925 if (pid == 0) {
926 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
927 capabilities, capabilities,
928 mount_external, se_info, se_name, false,
929 is_child_zygote == JNI_TRUE, instructionSet, appDataDir);
930 }
931 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100932}
933
934static jint com_android_internal_os_Zygote_nativeForkSystemServer(
935 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100936 jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities,
Narayan Kamath973b4662014-03-31 13:41:26 +0100937 jlong effectiveCapabilities) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700938 pid_t pid = ForkCommon(env, NULL, true, NULL, NULL);
939 if (pid == 0) {
940 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
941 permittedCapabilities, effectiveCapabilities,
942 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true,
943 false, NULL, NULL);
944 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100945 // The zygote process checks whether the child process has died or not.
946 ALOGI("System server process %d has been created", pid);
947 gSystemServerPid = pid;
948 // There is a slight window that the system server process has crashed
949 // but it went unnoticed because we haven't published its pid yet. So
950 // we recheck here just to make sure that all is well.
951 int status;
952 if (waitpid(pid, &status, WNOHANG) == pid) {
953 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800954 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100955 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800956
Minchan Kim696873e2018-06-27 11:32:40 +0900957 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
958 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
959 if (per_app_memcg) {
960 // Assign system_server to the correct memory cgroup.
961 // Not all devices mount /dev/memcg so check for the file first
962 // to avoid unnecessarily printing errors and denials in the logs.
963 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -0800964 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim696873e2018-06-27 11:32:40 +0900965 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
966 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800967 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100968 }
969 return pid;
970}
971
Robert Sesek54e387d2016-12-02 17:27:50 -0500972static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
973 JNIEnv* env, jclass, jstring path) {
974 ScopedUtfChars path_native(env, path);
975 const char* path_cstr = path_native.c_str();
976 if (!path_cstr) {
977 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
978 }
979 FileDescriptorWhitelist::Get()->Allow(path_cstr);
980}
981
doheon1.lee885b7422016-01-20 13:07:27 +0900982static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
983 // Zygote process unmount root storage space initially before every child processes are forked.
984 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400985 // and no need unmount storage operation in MountEmulatedStorage method.
986 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
987
988 // See storage config details at http://source.android.com/tech/storage/
989 // Create private mount namespace shared by all children
990 if (unshare(CLONE_NEWNS) == -1) {
991 RuntimeAbort(env, __LINE__, "Failed to unshare()");
992 return;
993 }
994
995 // Mark rootfs as being a slave so that changes from default
996 // namespace only flow into our children.
997 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
998 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
999 return;
1000 }
1001
1002 // Create a staging tmpfs that is shared by our children; they will
1003 // bind mount storage into their respective private namespaces, which
1004 // are isolated from each other.
1005 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1006 if (target_base != nullptr) {
1007#define STRINGIFY_UID(x) __STRING(x)
1008 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1009 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1010 ALOGE("Failed to mount tmpfs to %s", target_base);
1011 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1012 return;
1013 }
1014#undef STRINGIFY_UID
1015 }
doheon1.lee885b7422016-01-20 13:07:27 +09001016
1017 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001018}
1019
Daniel Micay76f6a862015-09-19 17:31:01 -04001020static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001021 { "nativeSecurityInit", "()V",
1022 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001023 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001024 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001025 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1026 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001027 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001028 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1029 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001030 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001031 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1032 { "nativePreApplicationInit", "()V",
1033 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001034};
1035
1036int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001037 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001038 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1039 "callPostForkSystemServerHooks",
1040 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001041 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001042 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001043
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001044 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001045}
1046} // namespace android