blob: 738069216b2c1345e7e3a1f616a834a034fcf1b2 [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>
Colin Cross0161bbc2014-06-03 13:26:58 -070059#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070060
Andreas Gampeed6b9df2014-11-20 22:02:20 -080061#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070062#include <nativehelper/JNIHelp.h>
63#include <nativehelper/ScopedLocalRef.h>
64#include <nativehelper/ScopedPrimitiveArray.h>
65#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050066#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010067
jgu212eacd062014-09-10 06:55:07 -040068#include "nativebridge/native_bridge.h"
69
Narayan Kamath973b4662014-03-31 13:41:26 +010070namespace {
71
72using android::String8;
Sudheer Shanka663b1042018-07-30 17:34:21 -070073using android::base::StringAppendF;
Carmen Jacksondd401252017-02-23 15:21:10 -080074using android::base::StringPrintf;
75using android::base::WriteStringToFile;
Minchan Kim5fa8af22018-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
Sudheer Shanka663b1042018-07-30 17:34:21 -070083static const char kIsolatedStorage[] = "persist.sys.isolated_storage";
Narayan Kamath973b4662014-03-31 13:41:26 +010084static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
85static jclass gZygoteClass;
86static 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
Sudheer Shanka663b1042018-07-30 17:34:21 -0700384static bool createPkgSandbox(uid_t uid, const char* package_name, std::string& pkg_sandbox_dir,
385 std::string* error_msg) {
386 // Create /mnt/user/0/package/<package-name>
387 userid_t user_id = multiuser_get_user_id(uid);
388 StringAppendF(&pkg_sandbox_dir, "/%d", user_id);
389 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
390 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
391 return false;
392 }
393 StringAppendF(&pkg_sandbox_dir, "/package");
394 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
395 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
396 return false;
397 }
398 StringAppendF(&pkg_sandbox_dir, "/%s", package_name);
399 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0755, uid, uid) != 0) {
400 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
401 return false;
402 }
403 return true;
404}
405
Narayan Kamath973b4662014-03-31 13:41:26 +0100406// Create a private mount namespace and bind mount appropriate emulated
407// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700408static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700409 bool force_mount_namespace, std::string* error_msg, const char* package_name) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700410 // See storage config details at http://source.android.com/tech/storage/
411
Jeff Sharkey9527b222015-06-24 15:24:48 -0700412 String8 storageSource;
413 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700414 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700415 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700416 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700417 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700418 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500419 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700420 // Sane default of no storage visible
421 return true;
422 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400423
424 // Create a second private mount namespace for our process
425 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700426 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400427 return false;
428 }
429
Robert Sesek06f39302017-03-20 17:30:05 -0400430 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
431 if (mount_mode == MOUNT_EXTERNAL_NONE) {
432 return true;
433 }
434
Sudheer Shanka663b1042018-07-30 17:34:21 -0700435 if (GetBoolProperty(kIsolatedStorage, false)) {
436 if (package_name == nullptr) {
437 return true;
438 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700439
Sudheer Shanka663b1042018-07-30 17:34:21 -0700440 std::string pkgSandboxDir("/mnt/user");
441 if (!createPkgSandbox(uid, package_name, pkgSandboxDir, error_msg)) {
442 return false;
443 }
444 if (TEMP_FAILURE_RETRY(mount(pkgSandboxDir.c_str(), "/storage",
445 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
446 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
447 pkgSandboxDir.c_str(), strerror(errno));
448 return false;
449 }
450 } else {
451 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
452 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
453 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
454 storageSource.string(),
455 strerror(errno));
456 return false;
457 }
458
459 // Mount user-specific symlink helper into place
460 userid_t user_id = multiuser_get_user_id(uid);
461 const String8 userSource(String8::format("/mnt/user/%d", user_id));
462 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
463 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
464 return false;
465 }
466 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
467 NULL, MS_BIND, NULL)) == -1) {
468 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
469 userSource.string(),
470 strerror(errno));
471 return false;
472 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700473 }
474
Narayan Kamath973b4662014-03-31 13:41:26 +0100475 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100476}
477
Narayan Kamath973b4662014-03-31 13:41:26 +0100478static bool NeedsNoRandomizeWorkaround() {
479#if !defined(__arm__)
480 return false;
481#else
482 int major;
483 int minor;
484 struct utsname uts;
485 if (uname(&uts) == -1) {
486 return false;
487 }
488
489 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
490 return false;
491 }
492
493 // Kernels before 3.4.* need the workaround.
494 return (major < 3) || ((major == 3) && (minor < 4));
495#endif
496}
Narayan Kamath973b4662014-03-31 13:41:26 +0100497
498// Utility to close down the Zygote socket file descriptors while
499// the child is still running as root with Zygote's privileges. Each
500// descriptor (if any) is closed via dup2(), replacing it with a valid
501// (open) descriptor to /dev/null.
502
Andreas Gamped5758f62018-03-12 12:08:55 -0700503static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100504 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700505 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100506 }
507 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200508 ScopedIntArrayRO ar(env, fdsToClose);
509 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700510 *error_msg = "Bad fd array";
511 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100512 }
513 jsize i;
514 int devnull;
515 for (i = 0; i < count; i++) {
516 devnull = open("/dev/null", O_RDWR);
517 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700518 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
519 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100520 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700521 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100522 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700523 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
524 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100525 }
526 close(devnull);
527 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700528 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100529}
530
531void SetThreadName(const char* thread_name) {
532 bool hasAt = false;
533 bool hasDot = false;
534 const char* s = thread_name;
535 while (*s) {
536 if (*s == '.') {
537 hasDot = true;
538 } else if (*s == '@') {
539 hasAt = true;
540 }
541 s++;
542 }
543 const int len = s - thread_name;
544 if (len < 15 || hasAt || !hasDot) {
545 s = thread_name;
546 } else {
547 s = thread_name + len - 15;
548 }
549 // pthread_setname_np fails rather than truncating long strings.
550 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
551 strlcpy(buf, s, sizeof(buf)-1);
552 errno = pthread_setname_np(pthread_self(), buf);
553 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700554 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100555 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800556 // Update base::logging default tag.
557 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100558}
559
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100560// The list of open zygote file descriptors.
561static FileDescriptorTable* gOpenFdTable = NULL;
562
Andreas Gamped5758f62018-03-12 12:08:55 -0700563static bool FillFileDescriptorVector(JNIEnv* env,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800564 jintArray java_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700565 std::vector<int>* fds,
566 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800567 CHECK(fds != nullptr);
568 if (java_fds != nullptr) {
569 ScopedIntArrayRO ar(env, java_fds);
570 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700571 *error_msg = "Bad fd array";
572 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800573 }
574 fds->reserve(ar.size());
575 for (size_t i = 0; i < ar.size(); ++i) {
576 fds->push_back(ar[i]);
577 }
578 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700579 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800580}
581
David Sehrde8d0bd2018-06-22 10:45:36 -0700582// Utility routine to specialize a zygote child process.
583static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
584 jint runtime_flags, jobjectArray javaRlimits,
585 jlong permittedCapabilities, jlong effectiveCapabilities,
586 jint mount_external, jstring java_se_info, jstring java_se_name,
587 bool is_system_server, bool is_child_zygote, jstring instructionSet,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700588 jstring dataDir, jstring packageName) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700589 std::string error_msg;
590
591 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
592 __attribute__ ((noreturn)) {
593 const char* se_name_c_str = nullptr;
594 std::unique_ptr<ScopedUtfChars> se_name;
595 if (java_se_name != nullptr) {
596 se_name.reset(new ScopedUtfChars(env, java_se_name));
597 se_name_c_str = se_name->c_str();
598 }
599 if (se_name_c_str == nullptr && is_system_server) {
600 se_name_c_str = "system_server";
601 }
602 const std::string& error_msg = (se_name_c_str == nullptr)
603 ? msg
604 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
605 env->FatalError(error_msg.c_str());
606 __builtin_unreachable();
607 };
608
609 // Keep capabilities across UID change, unless we're staying root.
610 if (uid != 0) {
611 if (!EnableKeepCapabilities(&error_msg)) {
612 fail_fn(error_msg);
613 }
614 }
615
616 if (!SetInheritable(permittedCapabilities, &error_msg)) {
617 fail_fn(error_msg);
618 }
619 if (!DropCapabilitiesBoundingSet(&error_msg)) {
620 fail_fn(error_msg);
621 }
622
623 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
624 && android::NativeBridgeAvailable();
625 if (use_native_bridge) {
626 ScopedUtfChars isa_string(env, instructionSet);
627 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
628 }
629 if (use_native_bridge && dataDir == NULL) {
630 // dataDir should never be null if we need to use a native bridge.
631 // In general, dataDir will never be null for normal applications. It can only happen in
632 // special cases (for isolated processes which are not associated with any app). These are
633 // launched by the framework and should not be emulated anyway.
634 use_native_bridge = false;
635 ALOGW("Native bridge will not be used because dataDir == NULL.");
636 }
637
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700638 ScopedUtfChars* package_name = nullptr;
639 const char* package_name_c_str = nullptr;
640 if (packageName != nullptr) {
641 package_name = new ScopedUtfChars(env, packageName);
642 package_name_c_str = package_name->c_str();
643 } else if (is_system_server) {
644 package_name_c_str = "android";
645 }
646 bool success = MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg,
647 package_name_c_str);
648 delete package_name;
649 if (!success) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700650 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
651 if (errno == ENOTCONN || errno == EROFS) {
652 // When device is actively encrypting, we get ENOTCONN here
653 // since FUSE was mounted before the framework restarted.
654 // When encrypted device is booting, we get EROFS since
655 // FUSE hasn't been created yet by init.
656 // In either case, continue without external storage.
657 } else {
658 fail_fn(error_msg);
659 }
660 }
661
662 // If this zygote isn't root, it won't be able to create a process group,
663 // since the directory is owned by root.
664 if (!is_system_server && getuid() == 0) {
665 int rc = createProcessGroup(uid, getpid());
666 if (rc != 0) {
667 if (rc == -EROFS) {
668 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
669 } else {
670 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
671 }
672 }
673 }
674
675 if (!SetGids(env, javaGids, &error_msg)) {
676 fail_fn(error_msg);
677 }
678
679 if (!SetRLimits(env, javaRlimits, &error_msg)) {
680 fail_fn(error_msg);
681 }
682
683 if (use_native_bridge) {
684 ScopedUtfChars isa_string(env, instructionSet);
685 ScopedUtfChars data_dir(env, dataDir);
686 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
687 }
688
689 int rc = setresgid(gid, gid, gid);
690 if (rc == -1) {
691 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
692 }
693
694 // Must be called when the new process still has CAP_SYS_ADMIN, in this case, before changing
695 // uid from 0, which clears capabilities. The other alternative is to call
696 // prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that breaks SELinux domain transition (see
697 // b/71859146). As the result, privileged syscalls used below still need to be accessible in
698 // app process.
699 SetUpSeccompFilter(uid);
700
701 rc = setresuid(uid, uid, uid);
702 if (rc == -1) {
703 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
704 }
705
706 // The "dumpable" flag of a process, which controls core dump generation, is
707 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
708 // user or group ID changes. See proc(5) for possible values. In most cases,
709 // the value is 0, so core dumps are disabled for zygote children. However,
710 // when running in a Chrome OS container, the value is already set to 2,
711 // which allows the external crash reporter to collect all core dumps. Since
712 // only system crashes are interested, core dump is disabled for app
713 // processes. This also ensures compliance with CTS.
714 int dumpable = prctl(PR_GET_DUMPABLE);
715 if (dumpable == -1) {
716 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
717 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
718 }
719 if (dumpable == 2 && uid >= AID_APP) {
720 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
721 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
722 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
723 }
724 }
725
726 if (NeedsNoRandomizeWorkaround()) {
727 // Work around ARM kernel ASLR lossage (http://b/5817320).
728 int old_personality = personality(0xffffffff);
729 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
730 if (new_personality == -1) {
731 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
732 }
733 }
734
735 if (!SetCapabilities(permittedCapabilities, effectiveCapabilities, permittedCapabilities,
736 &error_msg)) {
737 fail_fn(error_msg);
738 }
739
740 if (!SetSchedulerPolicy(&error_msg)) {
741 fail_fn(error_msg);
742 }
743
744 const char* se_info_c_str = NULL;
745 ScopedUtfChars* se_info = NULL;
746 if (java_se_info != NULL) {
747 se_info = new ScopedUtfChars(env, java_se_info);
748 se_info_c_str = se_info->c_str();
749 if (se_info_c_str == NULL) {
750 fail_fn("se_info_c_str == NULL");
751 }
752 }
753 const char* se_name_c_str = NULL;
754 ScopedUtfChars* se_name = NULL;
755 if (java_se_name != NULL) {
756 se_name = new ScopedUtfChars(env, java_se_name);
757 se_name_c_str = se_name->c_str();
758 if (se_name_c_str == NULL) {
759 fail_fn("se_name_c_str == NULL");
760 }
761 }
762 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
763 if (rc == -1) {
764 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
765 is_system_server, se_info_c_str, se_name_c_str));
766 }
767
768 // Make it easier to debug audit logs by setting the main thread's name to the
769 // nice name rather than "app_process".
770 if (se_name_c_str == NULL && is_system_server) {
771 se_name_c_str = "system_server";
772 }
773 if (se_name_c_str != NULL) {
774 SetThreadName(se_name_c_str);
775 }
776
777 delete se_info;
778 delete se_name;
779
780 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
781 UnsetChldSignalHandler();
782
783 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
784 is_system_server, is_child_zygote, instructionSet);
785 if (env->ExceptionCheck()) {
786 fail_fn("Error calling post fork hooks.");
787 }
788}
789
Narayan Kamath973b4662014-03-31 13:41:26 +0100790// Utility routine to fork zygote and specialize the child process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700791static pid_t ForkCommon(JNIEnv* env, jstring java_se_name, bool is_system_server,
792 jintArray fdsToClose, jintArray fdsToIgnore) {
yuanhao435e84b2018-01-15 15:37:02 +0800793 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100794
David Sehrde8d0bd2018-06-22 10:45:36 -0700795 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000796 sigset_t sigchld;
797 sigemptyset(&sigchld);
798 sigaddset(&sigchld, SIGCHLD);
799
Andreas Gampe5f35c4e2018-03-12 12:17:25 -0700800 auto fail_fn = [env, java_se_name, is_system_server](const std::string& msg)
801 __attribute__ ((noreturn)) {
802 const char* se_name_c_str = nullptr;
803 std::unique_ptr<ScopedUtfChars> se_name;
804 if (java_se_name != nullptr) {
805 se_name.reset(new ScopedUtfChars(env, java_se_name));
806 se_name_c_str = se_name->c_str();
807 }
808 if (se_name_c_str == nullptr && is_system_server) {
809 se_name_c_str = "system_server";
810 }
811 const std::string& error_msg = (se_name_c_str == nullptr)
812 ? msg
813 : StringPrintf("(%s) %s", se_name_c_str, msg.c_str());
814 env->FatalError(error_msg.c_str());
Andreas Gamped5758f62018-03-12 12:08:55 -0700815 __builtin_unreachable();
816 };
817
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000818 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
819 // log, which would result in the logging FDs we close being reopened.
820 // This would cause failures because the FDs are not whitelisted.
821 //
822 // Note that the zygote process is single threaded at this point.
823 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700824 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000825 }
826
Narayan Kamath3764a262016-08-30 15:36:19 +0100827 // Close any logging related FDs before we start evaluating the list of
828 // file descriptors.
829 __android_log_close();
830
Andreas Gamped5758f62018-03-12 12:08:55 -0700831 std::string error_msg;
832
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100833 // If this is the first fork for this zygote, create the open FD table.
834 // If it isn't, we just need to check whether the list of open files has
835 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800836 std::vector<int> fds_to_ignore;
Andreas Gamped5758f62018-03-12 12:08:55 -0700837 if (!FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore, &error_msg)) {
838 fail_fn(error_msg);
839 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100840 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700841 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100842 if (gOpenFdTable == NULL) {
Andreas Gampec362a442018-03-12 14:53:34 -0700843 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100844 }
Andreas Gampec362a442018-03-12 14:53:34 -0700845 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
846 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100847 }
848
Josh Gaod7951102018-06-26 16:05:12 -0700849 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
850
Narayan Kamath973b4662014-03-31 13:41:26 +0100851 pid_t pid = fork();
852
853 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700854 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700855 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700856
Narayan Kamath973b4662014-03-31 13:41:26 +0100857 // Clean up any descriptors which must be closed immediately
Andreas Gamped5758f62018-03-12 12:08:55 -0700858 if (!DetachDescriptors(env, fdsToClose, &error_msg)) {
859 fail_fn(error_msg);
860 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100861
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100862 // Re-open all remaining open file descriptors so that they aren't shared
863 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700864 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
865 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100866 }
Josh Gaod7951102018-06-26 16:05:12 -0700867
868 // Turn fdsan back on.
869 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -0700870 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100871
David Sehrde8d0bd2018-06-22 10:45:36 -0700872 // We blocked SIGCHLD prior to a fork, we unblock it here.
873 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
874 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100875 }
876 return pid;
877}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700878
879static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
880 __user_cap_header_struct capheader;
881 memset(&capheader, 0, sizeof(capheader));
882 capheader.version = _LINUX_CAPABILITY_VERSION_3;
883 capheader.pid = 0;
884
885 __user_cap_data_struct capdata[2];
886 if (capget(&capheader, &capdata[0]) == -1) {
887 ALOGE("capget failed: %s", strerror(errno));
888 RuntimeAbort(env, __LINE__, "capget failed");
889 }
890
891 return capdata[0].effective |
892 (static_cast<uint64_t>(capdata[1].effective) << 32);
893}
Narayan Kamath973b4662014-03-31 13:41:26 +0100894} // anonymous namespace
895
896namespace android {
897
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800898static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
899 // security_getenforce is not allowed on app process. Initialize and cache the value before
900 // zygote forks.
901 g_is_security_enforced = security_getenforce();
902}
903
Christopher Ferris76de39e2017-06-20 16:13:40 -0700904static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
905 PreApplicationInit();
906}
907
Narayan Kamath973b4662014-03-31 13:41:26 +0100908static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
909 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100910 jint runtime_flags, jobjectArray rlimits,
Narayan Kamath973b4662014-03-31 13:41:26 +0100911 jint mount_external, jstring se_info, jstring se_name,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500912 jintArray fdsToClose, jintArray fdsToIgnore, jboolean is_child_zygote,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700913 jstring instructionSet, jstring appDataDir, jstring packageName) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700914 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800915
916 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900917 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
Philip Cuadra0fabba32017-04-26 13:49:37 -0700918 // Grant CAP_SYS_NICE to allow Bluetooth to set RT priority for
919 // audio-related threads.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900920 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800921 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800922 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900923 capabilities |= (1LL << CAP_NET_RAW);
924 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Philip Cuadra0fabba32017-04-26 13:49:37 -0700925 capabilities |= (1LL << CAP_SYS_NICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800926 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700927
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800928 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
929 bool gid_wakelock_found = false;
930 if (gid == AID_WAKELOCK) {
931 gid_wakelock_found = true;
932 } else if (gids != NULL) {
933 jsize gids_num = env->GetArrayLength(gids);
934 ScopedIntArrayRO ar(env, gids);
935 if (ar.get() == NULL) {
936 RuntimeAbort(env, __LINE__, "Bad gids array");
937 }
938 for (int i = 0; i < gids_num; i++) {
939 if (ar[i] == AID_WAKELOCK) {
940 gid_wakelock_found = true;
941 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700942 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800943 }
944 }
945 if (gid_wakelock_found) {
946 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700947 }
948
Robert Sesekd0a190df2018-02-12 18:46:01 -0500949 // If forking a child zygote process, that zygote will need to be able to change
950 // the UID and GID of processes it forks, as well as drop those capabilities.
951 if (is_child_zygote) {
952 capabilities |= (1LL << CAP_SETUID);
953 capabilities |= (1LL << CAP_SETGID);
954 capabilities |= (1LL << CAP_SETPCAP);
955 }
956
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700957 // Containers run without some capabilities, so drop any caps that are not
958 // available.
959 capabilities &= GetEffectiveCapabilityMask(env);
960
David Sehrde8d0bd2018-06-22 10:45:36 -0700961 pid_t pid = ForkCommon(env, se_name, false, fdsToClose, fdsToIgnore);
962 if (pid == 0) {
963 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
964 capabilities, capabilities,
965 mount_external, se_info, se_name, false,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700966 is_child_zygote == JNI_TRUE, instructionSet, appDataDir, packageName);
David Sehrde8d0bd2018-06-22 10:45:36 -0700967 }
968 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +0100969}
970
971static jint com_android_internal_os_Zygote_nativeForkSystemServer(
972 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100973 jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities,
Narayan Kamath973b4662014-03-31 13:41:26 +0100974 jlong effectiveCapabilities) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700975 pid_t pid = ForkCommon(env, NULL, true, NULL, NULL);
976 if (pid == 0) {
977 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
978 permittedCapabilities, effectiveCapabilities,
979 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true,
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700980 false, NULL, NULL, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -0700981 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100982 // The zygote process checks whether the child process has died or not.
983 ALOGI("System server process %d has been created", pid);
984 gSystemServerPid = pid;
985 // There is a slight window that the system server process has crashed
986 // but it went unnoticed because we haven't published its pid yet. So
987 // we recheck here just to make sure that all is well.
988 int status;
989 if (waitpid(pid, &status, WNOHANG) == pid) {
990 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800991 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100992 }
Carmen Jacksondd401252017-02-23 15:21:10 -0800993
Minchan Kim5fa8af22018-06-27 11:32:40 +0900994 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
995 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
996 if (per_app_memcg) {
997 // Assign system_server to the correct memory cgroup.
998 // Not all devices mount /dev/memcg so check for the file first
999 // to avoid unnecessarily printing errors and denials in the logs.
1000 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -08001001 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001002 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
1003 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001004 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001005 }
1006 return pid;
1007}
1008
Robert Sesek54e387d2016-12-02 17:27:50 -05001009static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1010 JNIEnv* env, jclass, jstring path) {
1011 ScopedUtfChars path_native(env, path);
1012 const char* path_cstr = path_native.c_str();
1013 if (!path_cstr) {
1014 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
1015 }
1016 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1017}
1018
doheon1.lee885b7422016-01-20 13:07:27 +09001019static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1020 // Zygote process unmount root storage space initially before every child processes are forked.
1021 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001022 // and no need unmount storage operation in MountEmulatedStorage method.
1023 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1024
1025 // See storage config details at http://source.android.com/tech/storage/
1026 // Create private mount namespace shared by all children
1027 if (unshare(CLONE_NEWNS) == -1) {
1028 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1029 return;
1030 }
1031
1032 // Mark rootfs as being a slave so that changes from default
1033 // namespace only flow into our children.
1034 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1035 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1036 return;
1037 }
1038
1039 // Create a staging tmpfs that is shared by our children; they will
1040 // bind mount storage into their respective private namespaces, which
1041 // are isolated from each other.
1042 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1043 if (target_base != nullptr) {
1044#define STRINGIFY_UID(x) __STRING(x)
1045 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1046 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1047 ALOGE("Failed to mount tmpfs to %s", target_base);
1048 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1049 return;
1050 }
1051#undef STRINGIFY_UID
1052 }
doheon1.lee885b7422016-01-20 13:07:27 +09001053
1054 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001055}
1056
Daniel Micay76f6a862015-09-19 17:31:01 -04001057static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001058 { "nativeSecurityInit", "()V",
1059 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001060 { "nativeForkAndSpecialize",
Sudheer Shanka154fe3f2018-07-30 14:44:26 -07001061 "(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 +01001062 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1063 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001064 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001065 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1066 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001067 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001068 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1069 { "nativePreApplicationInit", "()V",
1070 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001071};
1072
1073int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001074 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
1075 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001076 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001077
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001078 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001079}
1080} // namespace android