blob: e2533ae6efd6ae22f252903392bc55c24eb1f2b3 [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 Kim5fa8af22018-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 Ro27330412018-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;
Sudheer Shanka663b1042018-07-30 17:34:21 -070074using android::base::StringAppendF;
Carmen Jacksondd401252017-02-23 15:21:10 -080075using android::base::StringPrintf;
76using android::base::WriteStringToFile;
Minchan Kim5fa8af22018-06-27 11:32:40 +090077using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010078
Andreas Gamped5758f62018-03-12 12:08:55 -070079#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
80 append(StringPrintf(__VA_ARGS__))
81
Narayan Kamath973b4662014-03-31 13:41:26 +010082static pid_t gSystemServerPid = 0;
83
Sudheer Shanka663b1042018-07-30 17:34:21 -070084static const char kIsolatedStorage[] = "persist.sys.isolated_storage";
Narayan Kamath973b4662014-03-31 13:41:26 +010085static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
86static jclass gZygoteClass;
87static jmethodID gCallPostForkChildHooks;
88
Victor Hsiehc8176ef2018-01-08 12:43:00 -080089static bool g_is_security_enforced = true;
90
Narayan Kamath973b4662014-03-31 13:41:26 +010091// Must match values in com.android.internal.os.Zygote.
92enum MountExternalKind {
93 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070094 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070095 MOUNT_EXTERNAL_READ = 2,
96 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka98cb3f02018-08-17 16:10:29 -070097 MOUNT_EXTERNAL_FULL = 4,
Narayan Kamath973b4662014-03-31 13:41:26 +010098};
99
Andreas Gampeb053cce2015-11-17 16:38:59 -0800100static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
101 std::ostringstream oss;
102 oss << __FILE__ << ":" << line << ": " << msg;
103 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100104}
105
106// This signal handler is for zygote mode, since the zygote must reap its children
107static void SigChldHandler(int /*signal_number*/) {
108 pid_t pid;
109 int status;
110
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700111 // It's necessary to save and restore the errno during this function.
112 // Since errno is stored per thread, changing it here modifies the errno
113 // on the thread on which this signal handler executes. If a signal occurs
114 // between a call and an errno check, it's possible to get the errno set
115 // here.
116 // See b/23572286 for extra information.
117 int saved_errno = errno;
118
Narayan Kamath973b4662014-03-31 13:41:26 +0100119 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
120 // Log process-death status that we care about. In general it is
121 // not safe to call LOG(...) from a signal handler because of
122 // possible reentrancy. However, we know a priori that the
123 // current implementation of LOG() is safe to call from a SIGCHLD
124 // handler in the zygote process. If the LOG() implementation
125 // changes its locking strategy or its use of syscalls within the
126 // lazy-init critical section, its use here may become unsafe.
127 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700128 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100129 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700130 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100131 if (WCOREDUMP(status)) {
132 ALOGI("Process %d dumped core.", pid);
133 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100134 }
135
136 // If the just-crashed process is the system_server, bring down zygote
137 // so that it is restarted by init and system server will be restarted
138 // from there.
139 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800140 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100141 kill(getpid(), SIGKILL);
142 }
143 }
144
Narayan Kamath160992d2014-04-14 14:46:07 +0100145 // Note that we shouldn't consider ECHILD an error because
146 // the secondary zygote might have no children left to wait for.
147 if (pid < 0 && errno != ECHILD) {
148 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100149 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700150
151 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100152}
153
yuanhao435e84b2018-01-15 15:37:02 +0800154// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
155// configured very late, because earlier in the runtime we may fork() and
156// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100157// have them be harvested immediately.
158//
yuanhao435e84b2018-01-15 15:37:02 +0800159// Ignore SIGHUP because all processes forked by the zygote are in the same
160// process group as the zygote and we don't want to be notified if we become
161// an orphaned group and have one or more stopped processes. This is not a
162// theoretical concern :
163// - we can become an orphaned group if one of our direct descendants forks
164// and is subsequently killed before its children.
165// - crash_dump routinely STOPs the process it's tracing.
166//
167// See issues b/71965619 and b/25567761 for further details.
168//
Narayan Kamath973b4662014-03-31 13:41:26 +0100169// This ends up being called repeatedly before each fork(), but there's
170// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800171static void SetSignalHandlers() {
172 struct sigaction sig_chld = {};
173 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100174
yuanhao435e84b2018-01-15 15:37:02 +0800175 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700176 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100177 }
yuanhao435e84b2018-01-15 15:37:02 +0800178
179 struct sigaction sig_hup = {};
180 sig_hup.sa_handler = SIG_IGN;
181 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
182 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
183 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100184}
185
186// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800187static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100188 struct sigaction sa;
189 memset(&sa, 0, sizeof(sa));
190 sa.sa_handler = SIG_DFL;
191
yuanhao435e84b2018-01-15 15:37:02 +0800192 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700193 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100194 }
195}
196
197// Calls POSIX setgroups() using the int[] object as an argument.
198// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700199static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100200 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700201 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100202 }
203
204 ScopedIntArrayRO gids(env, javaGids);
205 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700206 *error_msg = CREATE_ERROR("Getting gids int array failed");
207 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100208 }
209 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
210 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700211 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
212 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100213 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700214
215 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100216}
217
218// Sets the resource limits via setrlimit(2) for the values in the
219// two-dimensional array of integers that's passed in. The second dimension
220// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
221// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700222static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100223 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700224 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100225 }
226
227 rlimit rlim;
228 memset(&rlim, 0, sizeof(rlim));
229
230 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
231 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
232 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
233 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700234 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
235 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100236 }
237
238 rlim.rlim_cur = javaRlimit[1];
239 rlim.rlim_max = javaRlimit[2];
240
241 int rc = setrlimit(javaRlimit[0], &rlim);
242 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700243 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800244 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700245 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100246 }
247 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700248
249 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100250}
251
Narayan Kamath973b4662014-03-31 13:41:26 +0100252// The debug malloc library needs to know whether it's the zygote or a child.
253extern "C" int gMallocLeakZygoteChild;
254
Christopher Ferris76de39e2017-06-20 16:13:40 -0700255static void PreApplicationInit() {
256 // The child process sets this to indicate it's not the zygote.
257 gMallocLeakZygoteChild = 1;
258
259 // Set the jemalloc decay time to 1.
260 mallopt(M_DECAY_TIME, 1);
261}
262
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800263static void SetUpSeccompFilter(uid_t uid) {
264 if (!g_is_security_enforced) {
265 ALOGI("seccomp disabled by setenforce 0");
266 return;
267 }
268
269 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700270 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800271 set_app_seccomp_filter();
272 } else {
273 set_system_seccomp_filter();
274 }
275}
276
Andreas Gamped5758f62018-03-12 12:08:55 -0700277static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100278 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
279 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700280 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
281 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100282 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700283 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100284}
285
Andreas Gamped5758f62018-03-12 12:08:55 -0700286static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100287 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
288 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
289 if (rc == -1) {
290 if (errno == EINVAL) {
291 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
292 "your kernel is compiled with file capabilities support");
293 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700294 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
295 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100296 }
297 }
298 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700299 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100300}
301
Andreas Gamped5758f62018-03-12 12:08:55 -0700302static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800303 __user_cap_header_struct capheader;
304 memset(&capheader, 0, sizeof(capheader));
305 capheader.version = _LINUX_CAPABILITY_VERSION_3;
306 capheader.pid = 0;
307
308 __user_cap_data_struct capdata[2];
309 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700310 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
311 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800312 }
313
314 capdata[0].inheritable = inheritable;
315 capdata[1].inheritable = inheritable >> 32;
316
317 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700318 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
319 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800320 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700321
322 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800323}
324
Andreas Gamped5758f62018-03-12 12:08:55 -0700325static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
326 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100327 __user_cap_header_struct capheader;
328 memset(&capheader, 0, sizeof(capheader));
329 capheader.version = _LINUX_CAPABILITY_VERSION_3;
330 capheader.pid = 0;
331
332 __user_cap_data_struct capdata[2];
333 memset(&capdata, 0, sizeof(capdata));
334 capdata[0].effective = effective;
335 capdata[1].effective = effective >> 32;
336 capdata[0].permitted = permitted;
337 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800338 capdata[0].inheritable = inheritable;
339 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100340
341 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700342 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
343 "failed: %s", permitted, effective, inheritable, strerror(errno));
344 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100345 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700346 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100347}
348
Andreas Gamped5758f62018-03-12 12:08:55 -0700349static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100350 errno = -set_sched_policy(0, SP_DEFAULT);
351 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700352 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
353 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100354 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700355 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100356}
357
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700358static int UnmountTree(const char* path) {
359 size_t path_len = strlen(path);
360
361 FILE* fp = setmntent("/proc/mounts", "r");
362 if (fp == NULL) {
363 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
364 return -errno;
365 }
366
367 // Some volumes can be stacked on each other, so force unmount in
368 // reverse order to give us the best chance of success.
369 std::list<std::string> toUnmount;
370 mntent* mentry;
371 while ((mentry = getmntent(fp)) != NULL) {
372 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
373 toUnmount.push_front(std::string(mentry->mnt_dir));
374 }
375 }
376 endmntent(fp);
377
378 for (auto path : toUnmount) {
379 if (umount2(path.c_str(), MNT_DETACH)) {
380 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
381 }
382 }
383 return 0;
384}
385
Sudheer Shanka663b1042018-07-30 17:34:21 -0700386static bool createPkgSandbox(uid_t uid, const char* package_name, std::string& pkg_sandbox_dir,
387 std::string* error_msg) {
388 // Create /mnt/user/0/package/<package-name>
389 userid_t user_id = multiuser_get_user_id(uid);
390 StringAppendF(&pkg_sandbox_dir, "/%d", user_id);
Sudheer Shanka8d8223e2018-08-03 18:18:21 -0700391 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700392 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
393 return false;
394 }
395 StringAppendF(&pkg_sandbox_dir, "/package");
396 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
397 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
398 return false;
399 }
400 StringAppendF(&pkg_sandbox_dir, "/%s", package_name);
401 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0755, uid, uid) != 0) {
402 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
403 return false;
404 }
405 return true;
406}
407
Narayan Kamath973b4662014-03-31 13:41:26 +0100408// Create a private mount namespace and bind mount appropriate emulated
409// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700410static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700411 bool force_mount_namespace, std::string* error_msg, const char* package_name) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700412 // See storage config details at http://source.android.com/tech/storage/
413
Jeff Sharkey9527b222015-06-24 15:24:48 -0700414 String8 storageSource;
415 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700416 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700417 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700418 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700419 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700420 storageSource = "/mnt/runtime/write";
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700421 } else if (mount_mode != MOUNT_EXTERNAL_FULL && !force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700422 // Sane default of no storage visible
423 return true;
424 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400425
426 // Create a second private mount namespace for our process
427 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700428 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400429 return false;
430 }
431
Robert Sesek06f39302017-03-20 17:30:05 -0400432 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
433 if (mount_mode == MOUNT_EXTERNAL_NONE) {
434 return true;
435 }
436
Sudheer Shanka663b1042018-07-30 17:34:21 -0700437 if (GetBoolProperty(kIsolatedStorage, false)) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700438 if (mount_mode == MOUNT_EXTERNAL_FULL) {
439 storageSource = "/mnt/runtime/write";
440 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
441 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
442 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
443 storageSource.string(),
444 strerror(errno));
445 return false;
446 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700447
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700448 // Mount user-specific symlink helper into place
449 userid_t user_id = multiuser_get_user_id(uid);
450 const String8 userSource(String8::format("/mnt/user/%d", user_id));
451 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
452 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
453 return false;
454 }
455 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
456 NULL, MS_BIND, NULL)) == -1) {
457 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
458 userSource.string(),
459 strerror(errno));
460 return false;
461 }
462 } else {
463 if (package_name == nullptr) {
464 return true;
465 }
466 std::string pkgSandboxDir("/mnt/user");
467 if (!createPkgSandbox(uid, package_name, pkgSandboxDir, error_msg)) {
468 return false;
469 }
470 if (TEMP_FAILURE_RETRY(mount(pkgSandboxDir.c_str(), "/storage",
471 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
472 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
473 pkgSandboxDir.c_str(), strerror(errno));
474 return false;
475 }
Sudheer Shanka663b1042018-07-30 17:34:21 -0700476 }
477 } else {
478 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
479 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
480 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
481 storageSource.string(),
482 strerror(errno));
483 return false;
484 }
485
486 // Mount user-specific symlink helper into place
487 userid_t user_id = multiuser_get_user_id(uid);
488 const String8 userSource(String8::format("/mnt/user/%d", user_id));
489 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
490 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
491 return false;
492 }
493 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
494 NULL, MS_BIND, NULL)) == -1) {
495 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
496 userSource.string(),
497 strerror(errno));
498 return false;
499 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700500 }
501
Narayan Kamath973b4662014-03-31 13:41:26 +0100502 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100503}
504
Narayan Kamath973b4662014-03-31 13:41:26 +0100505static bool NeedsNoRandomizeWorkaround() {
506#if !defined(__arm__)
507 return false;
508#else
509 int major;
510 int minor;
511 struct utsname uts;
512 if (uname(&uts) == -1) {
513 return false;
514 }
515
516 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
517 return false;
518 }
519
520 // Kernels before 3.4.* need the workaround.
521 return (major < 3) || ((major == 3) && (minor < 4));
522#endif
523}
Narayan Kamath973b4662014-03-31 13:41:26 +0100524
525// Utility to close down the Zygote socket file descriptors while
526// the child is still running as root with Zygote's privileges. Each
527// descriptor (if any) is closed via dup2(), replacing it with a valid
528// (open) descriptor to /dev/null.
529
Andreas Gamped5758f62018-03-12 12:08:55 -0700530static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100531 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700532 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100533 }
534 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200535 ScopedIntArrayRO ar(env, fdsToClose);
536 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700537 *error_msg = "Bad fd array";
538 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100539 }
540 jsize i;
541 int devnull;
542 for (i = 0; i < count; i++) {
543 devnull = open("/dev/null", O_RDWR);
544 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700545 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
546 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100547 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700548 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100549 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700550 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
551 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100552 }
553 close(devnull);
554 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700555 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100556}
557
558void SetThreadName(const char* thread_name) {
559 bool hasAt = false;
560 bool hasDot = false;
561 const char* s = thread_name;
562 while (*s) {
563 if (*s == '.') {
564 hasDot = true;
565 } else if (*s == '@') {
566 hasAt = true;
567 }
568 s++;
569 }
570 const int len = s - thread_name;
571 if (len < 15 || hasAt || !hasDot) {
572 s = thread_name;
573 } else {
574 s = thread_name + len - 15;
575 }
576 // pthread_setname_np fails rather than truncating long strings.
577 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
578 strlcpy(buf, s, sizeof(buf)-1);
579 errno = pthread_setname_np(pthread_self(), buf);
580 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700581 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100582 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800583 // Update base::logging default tag.
584 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100585}
586
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100587// The list of open zygote file descriptors.
588static FileDescriptorTable* gOpenFdTable = NULL;
589
Andreas Gamped5758f62018-03-12 12:08:55 -0700590static bool FillFileDescriptorVector(JNIEnv* env,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800591 jintArray java_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700592 std::vector<int>* fds,
593 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800594 CHECK(fds != nullptr);
595 if (java_fds != nullptr) {
596 ScopedIntArrayRO ar(env, java_fds);
597 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700598 *error_msg = "Bad fd array";
599 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800600 }
601 fds->reserve(ar.size());
602 for (size_t i = 0; i < ar.size(); ++i) {
603 fds->push_back(ar[i]);
604 }
605 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700606 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800607}
608
David Sehrde8d0bd2018-06-22 10:45:36 -0700609// Utility routine to specialize a zygote child process.
610static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
611 jint runtime_flags, jobjectArray javaRlimits,
612 jlong permittedCapabilities, jlong effectiveCapabilities,
613 jint mount_external, jstring java_se_info, jstring java_se_name,
614 bool is_system_server, bool is_child_zygote, jstring instructionSet,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700615 jstring dataDir, jstring packageName) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700616 std::string error_msg;
617
618 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
619 __attribute__ ((noreturn)) {
620 const char* se_name_c_str = nullptr;
621 std::unique_ptr<ScopedUtfChars> se_name;
622 if (java_se_name != nullptr) {
623 se_name.reset(new ScopedUtfChars(env, java_se_name));
624 se_name_c_str = se_name->c_str();
625 }
626 if (se_name_c_str == nullptr && is_system_server) {
627 se_name_c_str = "system_server";
628 }
629 const std::string& error_msg = (se_name_c_str == nullptr)
630 ? msg
631 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
632 env->FatalError(error_msg.c_str());
633 __builtin_unreachable();
634 };
635
636 // Keep capabilities across UID change, unless we're staying root.
637 if (uid != 0) {
638 if (!EnableKeepCapabilities(&error_msg)) {
639 fail_fn(error_msg);
640 }
641 }
642
643 if (!SetInheritable(permittedCapabilities, &error_msg)) {
644 fail_fn(error_msg);
645 }
646 if (!DropCapabilitiesBoundingSet(&error_msg)) {
647 fail_fn(error_msg);
648 }
649
650 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
651 && android::NativeBridgeAvailable();
652 if (use_native_bridge) {
653 ScopedUtfChars isa_string(env, instructionSet);
654 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
655 }
656 if (use_native_bridge && dataDir == NULL) {
657 // dataDir should never be null if we need to use a native bridge.
658 // In general, dataDir will never be null for normal applications. It can only happen in
659 // special cases (for isolated processes which are not associated with any app). These are
660 // launched by the framework and should not be emulated anyway.
661 use_native_bridge = false;
662 ALOGW("Native bridge will not be used because dataDir == NULL.");
663 }
664
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700665 ScopedUtfChars* package_name = nullptr;
666 const char* package_name_c_str = nullptr;
667 if (packageName != nullptr) {
668 package_name = new ScopedUtfChars(env, packageName);
669 package_name_c_str = package_name->c_str();
670 } else if (is_system_server) {
671 package_name_c_str = "android";
672 }
673 bool success = MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg,
674 package_name_c_str);
675 delete package_name;
676 if (!success) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700677 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
678 if (errno == ENOTCONN || errno == EROFS) {
679 // When device is actively encrypting, we get ENOTCONN here
680 // since FUSE was mounted before the framework restarted.
681 // When encrypted device is booting, we get EROFS since
682 // FUSE hasn't been created yet by init.
683 // In either case, continue without external storage.
684 } else {
685 fail_fn(error_msg);
686 }
687 }
688
689 // If this zygote isn't root, it won't be able to create a process group,
690 // since the directory is owned by root.
691 if (!is_system_server && getuid() == 0) {
692 int rc = createProcessGroup(uid, getpid());
693 if (rc != 0) {
694 if (rc == -EROFS) {
695 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
696 } else {
697 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
698 }
699 }
700 }
701
702 if (!SetGids(env, javaGids, &error_msg)) {
703 fail_fn(error_msg);
704 }
705
706 if (!SetRLimits(env, javaRlimits, &error_msg)) {
707 fail_fn(error_msg);
708 }
709
710 if (use_native_bridge) {
711 ScopedUtfChars isa_string(env, instructionSet);
712 ScopedUtfChars data_dir(env, dataDir);
713 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
714 }
715
716 int rc = setresgid(gid, gid, gid);
717 if (rc == -1) {
718 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
719 }
720
721 // Must be called when the new process still has CAP_SYS_ADMIN, in this case, before changing
722 // uid from 0, which clears capabilities. The other alternative is to call
723 // prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that breaks SELinux domain transition (see
724 // b/71859146). As the result, privileged syscalls used below still need to be accessible in
725 // app process.
726 SetUpSeccompFilter(uid);
727
728 rc = setresuid(uid, uid, uid);
729 if (rc == -1) {
730 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
731 }
732
733 // The "dumpable" flag of a process, which controls core dump generation, is
734 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
735 // user or group ID changes. See proc(5) for possible values. In most cases,
736 // the value is 0, so core dumps are disabled for zygote children. However,
737 // when running in a Chrome OS container, the value is already set to 2,
738 // which allows the external crash reporter to collect all core dumps. Since
739 // only system crashes are interested, core dump is disabled for app
740 // processes. This also ensures compliance with CTS.
741 int dumpable = prctl(PR_GET_DUMPABLE);
742 if (dumpable == -1) {
743 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
744 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
745 }
746 if (dumpable == 2 && uid >= AID_APP) {
747 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
748 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
749 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
750 }
751 }
752
753 if (NeedsNoRandomizeWorkaround()) {
754 // Work around ARM kernel ASLR lossage (http://b/5817320).
755 int old_personality = personality(0xffffffff);
756 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
757 if (new_personality == -1) {
758 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
759 }
760 }
761
762 if (!SetCapabilities(permittedCapabilities, effectiveCapabilities, permittedCapabilities,
763 &error_msg)) {
764 fail_fn(error_msg);
765 }
766
767 if (!SetSchedulerPolicy(&error_msg)) {
768 fail_fn(error_msg);
769 }
770
771 const char* se_info_c_str = NULL;
772 ScopedUtfChars* se_info = NULL;
773 if (java_se_info != NULL) {
774 se_info = new ScopedUtfChars(env, java_se_info);
775 se_info_c_str = se_info->c_str();
776 if (se_info_c_str == NULL) {
777 fail_fn("se_info_c_str == NULL");
778 }
779 }
780 const char* se_name_c_str = NULL;
781 ScopedUtfChars* se_name = NULL;
782 if (java_se_name != NULL) {
783 se_name = new ScopedUtfChars(env, java_se_name);
784 se_name_c_str = se_name->c_str();
785 if (se_name_c_str == NULL) {
786 fail_fn("se_name_c_str == NULL");
787 }
788 }
789 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
790 if (rc == -1) {
791 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
792 is_system_server, se_info_c_str, se_name_c_str));
793 }
794
795 // Make it easier to debug audit logs by setting the main thread's name to the
796 // nice name rather than "app_process".
797 if (se_name_c_str == NULL && is_system_server) {
798 se_name_c_str = "system_server";
799 }
800 if (se_name_c_str != NULL) {
801 SetThreadName(se_name_c_str);
802 }
803
804 delete se_info;
805 delete se_name;
806
807 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
808 UnsetChldSignalHandler();
809
810 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
811 is_system_server, is_child_zygote, instructionSet);
812 if (env->ExceptionCheck()) {
813 fail_fn("Error calling post fork hooks.");
814 }
815}
816
Narayan Kamath973b4662014-03-31 13:41:26 +0100817// Utility routine to fork zygote and specialize the child process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700818static pid_t ForkCommon(JNIEnv* env, jstring java_se_name, bool is_system_server,
819 jintArray fdsToClose, jintArray fdsToIgnore) {
yuanhao435e84b2018-01-15 15:37:02 +0800820 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100821
David Sehrde8d0bd2018-06-22 10:45:36 -0700822 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000823 sigset_t sigchld;
824 sigemptyset(&sigchld);
825 sigaddset(&sigchld, SIGCHLD);
826
Andreas Gampe5f35c4e2018-03-12 12:17:25 -0700827 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
828 __attribute__ ((noreturn)) {
829 const char* se_name_c_str = nullptr;
830 std::unique_ptr<ScopedUtfChars> se_name;
831 if (java_se_name != nullptr) {
832 se_name.reset(new ScopedUtfChars(env, java_se_name));
833 se_name_c_str = se_name->c_str();
834 }
835 if (se_name_c_str == nullptr && is_system_server) {
836 se_name_c_str = "system_server";
837 }
838 const std::string& error_msg = (se_name_c_str == nullptr)
839 ? msg
840 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
841 env->FatalError(error_msg.c_str());
Andreas Gamped5758f62018-03-12 12:08:55 -0700842 __builtin_unreachable();
843 };
844
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000845 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
846 // log, which would result in the logging FDs we close being reopened.
847 // This would cause failures because the FDs are not whitelisted.
848 //
849 // Note that the zygote process is single threaded at this point.
850 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700851 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000852 }
853
Narayan Kamath3764a262016-08-30 15:36:19 +0100854 // Close any logging related FDs before we start evaluating the list of
855 // file descriptors.
856 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -0700857 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +0100858
Andreas Gamped5758f62018-03-12 12:08:55 -0700859 std::string error_msg;
860
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100861 // If this is the first fork for this zygote, create the open FD table.
862 // If it isn't, we just need to check whether the list of open files has
863 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800864 std::vector<int> fds_to_ignore;
Andreas Gamped5758f62018-03-12 12:08:55 -0700865 if (!FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore, &error_msg)) {
866 fail_fn(error_msg);
867 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100868 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700869 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100870 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700871 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100872 }
Andreas Gampec362a442018-03-12 14:53:34 -0700873 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
874 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100875 }
876
Josh Gaod7951102018-06-26 16:05:12 -0700877 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
878
Narayan Kamath973b4662014-03-31 13:41:26 +0100879 pid_t pid = fork();
880
881 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700882 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700883 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700884
Narayan Kamath973b4662014-03-31 13:41:26 +0100885 // Clean up any descriptors which must be closed immediately
Andreas Gamped5758f62018-03-12 12:08:55 -0700886 if (!DetachDescriptors(env, fdsToClose, &error_msg)) {
887 fail_fn(error_msg);
888 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100889
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100890 // Re-open all remaining open file descriptors so that they aren't shared
891 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700892 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
893 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100894 }
Josh Gaod7951102018-06-26 16:05:12 -0700895
896 // Turn fdsan back on.
897 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -0700898 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100899
David Sehrde8d0bd2018-06-22 10:45:36 -0700900 // We blocked SIGCHLD prior to a fork, we unblock it here.
901 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
902 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100903 }
904 return pid;
905}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700906
907static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
908 __user_cap_header_struct capheader;
909 memset(&capheader, 0, sizeof(capheader));
910 capheader.version = _LINUX_CAPABILITY_VERSION_3;
911 capheader.pid = 0;
912
913 __user_cap_data_struct capdata[2];
914 if (capget(&capheader, &capdata[0]) == -1) {
915 ALOGE("capget failed: %s", strerror(errno));
916 RuntimeAbort(env, __LINE__, "capget failed");
917 }
918
919 return capdata[0].effective |
920 (static_cast<uint64_t>(capdata[1].effective) << 32);
921}
Narayan Kamath973b4662014-03-31 13:41:26 +0100922} // anonymous namespace
923
924namespace android {
925
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800926static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
927 // security_getenforce is not allowed on app process. Initialize and cache the value before
928 // zygote forks.
929 g_is_security_enforced = security_getenforce();
930}
931
Christopher Ferris76de39e2017-06-20 16:13:40 -0700932static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
933 PreApplicationInit();
934}
935
Narayan Kamath973b4662014-03-31 13:41:26 +0100936static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
937 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100938 jint runtime_flags, jobjectArray rlimits,
Narayan Kamath973b4662014-03-31 13:41:26 +0100939 jint mount_external, jstring se_info, jstring se_name,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500940 jintArray fdsToClose, jintArray fdsToIgnore, jboolean is_child_zygote,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700941 jstring instructionSet, jstring appDataDir, jstring packageName) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700942 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800943
944 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900945 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
Philip Cuadra0fabba32017-04-26 13:49:37 -0700946 // Grant CAP_SYS_NICE to allow Bluetooth to set RT priority for
947 // audio-related threads.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900948 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800949 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800950 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900951 capabilities |= (1LL << CAP_NET_RAW);
952 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Philip Cuadra0fabba32017-04-26 13:49:37 -0700953 capabilities |= (1LL << CAP_SYS_NICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800954 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700955
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800956 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
957 bool gid_wakelock_found = false;
958 if (gid == AID_WAKELOCK) {
959 gid_wakelock_found = true;
960 } else if (gids != NULL) {
961 jsize gids_num = env->GetArrayLength(gids);
962 ScopedIntArrayRO ar(env, gids);
963 if (ar.get() == NULL) {
964 RuntimeAbort(env, __LINE__, "Bad gids array");
965 }
966 for (int i = 0; i < gids_num; i++) {
967 if (ar[i] == AID_WAKELOCK) {
968 gid_wakelock_found = true;
969 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700970 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800971 }
972 }
973 if (gid_wakelock_found) {
974 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700975 }
976
Robert Sesekd0a190df2018-02-12 18:46:01 -0500977 // If forking a child zygote process, that zygote will need to be able to change
978 // the UID and GID of processes it forks, as well as drop those capabilities.
979 if (is_child_zygote) {
980 capabilities |= (1LL << CAP_SETUID);
981 capabilities |= (1LL << CAP_SETGID);
982 capabilities |= (1LL << CAP_SETPCAP);
983 }
984
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700985 // Containers run without some capabilities, so drop any caps that are not
986 // available.
987 capabilities &= GetEffectiveCapabilityMask(env);
988
David Sehrde8d0bd2018-06-22 10:45:36 -0700989 pid_t pid = ForkCommon(env, se_name, false, fdsToClose, fdsToIgnore);
990 if (pid == 0) {
991 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
992 capabilities, capabilities,
993 mount_external, se_info, se_name, false,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700994 is_child_zygote == JNI_TRUE, instructionSet, appDataDir, packageName);
David Sehrde8d0bd2018-06-22 10:45:36 -0700995 }
996 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100997}
998
999static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1000 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001001 jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities,
Narayan Kamath973b4662014-03-31 13:41:26 +01001002 jlong effectiveCapabilities) {
David Sehrde8d0bd2018-06-22 10:45:36 -07001003 pid_t pid = ForkCommon(env, NULL, true, NULL, NULL);
1004 if (pid == 0) {
1005 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1006 permittedCapabilities, effectiveCapabilities,
1007 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -07001008 false, NULL, NULL, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001009 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001010 // The zygote process checks whether the child process has died or not.
1011 ALOGI("System server process %d has been created", pid);
1012 gSystemServerPid = pid;
1013 // There is a slight window that the system server process has crashed
1014 // but it went unnoticed because we haven't published its pid yet. So
1015 // we recheck here just to make sure that all is well.
1016 int status;
1017 if (waitpid(pid, &status, WNOHANG) == pid) {
1018 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001019 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001020 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001021
Minchan Kim5fa8af22018-06-27 11:32:40 +09001022 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
1023 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
1024 if (per_app_memcg) {
1025 // Assign system_server to the correct memory cgroup.
1026 // Not all devices mount /dev/memcg so check for the file first
1027 // to avoid unnecessarily printing errors and denials in the logs.
1028 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -08001029 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001030 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
1031 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001032 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001033 }
1034 return pid;
1035}
1036
Robert Sesek54e387d2016-12-02 17:27:50 -05001037static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1038 JNIEnv* env, jclass, jstring path) {
1039 ScopedUtfChars path_native(env, path);
1040 const char* path_cstr = path_native.c_str();
1041 if (!path_cstr) {
1042 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
1043 }
1044 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1045}
1046
doheon1.lee885b7422016-01-20 13:07:27 +09001047static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1048 // Zygote process unmount root storage space initially before every child processes are forked.
1049 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001050 // and no need unmount storage operation in MountEmulatedStorage method.
1051 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1052
1053 // See storage config details at http://source.android.com/tech/storage/
1054 // Create private mount namespace shared by all children
1055 if (unshare(CLONE_NEWNS) == -1) {
1056 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1057 return;
1058 }
1059
1060 // Mark rootfs as being a slave so that changes from default
1061 // namespace only flow into our children.
1062 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1063 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1064 return;
1065 }
1066
1067 // Create a staging tmpfs that is shared by our children; they will
1068 // bind mount storage into their respective private namespaces, which
1069 // are isolated from each other.
1070 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1071 if (target_base != nullptr) {
1072#define STRINGIFY_UID(x) __STRING(x)
1073 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1074 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1075 ALOGE("Failed to mount tmpfs to %s", target_base);
1076 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1077 return;
1078 }
1079#undef STRINGIFY_UID
1080 }
doheon1.lee885b7422016-01-20 13:07:27 +09001081
1082 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001083}
1084
Daniel Micay76f6a862015-09-19 17:31:01 -04001085static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001086 { "nativeSecurityInit", "()V",
1087 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001088 { "nativeForkAndSpecialize",
Sudheer Shanka154fe3f2018-07-30 14:44:26 -07001089 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001090 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1091 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001092 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001093 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1094 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001095 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001096 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1097 { "nativePreApplicationInit", "()V",
1098 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001099};
1100
1101int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001102 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
1103 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001104 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001105
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001106 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001107}
1108} // namespace android