blob: 8e9a0bf61517dbb1a808b5e23c895ca8b7f648f3 [file] [log] [blame]
Narayan Kamath973b4662014-03-31 13:41:26 +01001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Colin Cross18cd9f52014-06-13 12:58:55 -070017#define LOG_TAG "Zygote"
Narayan Kamath973b4662014-03-31 13:41:26 +010018
19// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
20#include <sys/mount.h>
21#include <linux/fs.h>
22
Chris Wailesaf594fc2018-11-02 11:00:07 -070023#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070024#include <list>
Chris Wailesaf594fc2018-11-02 11:00:07 -070025#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080026#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070027#include <string>
28
Josh Gaod7951102018-06-26 16:05:12 -070029#include <android/fdsan.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070030#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080031#include <grp.h>
32#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070033#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070034#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010035#include <paths.h>
36#include <signal.h>
37#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070038#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040039#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070040#include <sys/personality.h>
41#include <sys/prctl.h>
42#include <sys/resource.h>
43#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070044#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070045#include <sys/types.h>
46#include <sys/utsname.h>
47#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080048#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070049
Andreas Gampe8dfa1782017-01-05 12:45:58 -080050#include "android-base/logging.h"
Minchan Kim5fa8af22018-06-27 11:32:40 +090051#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080052#include <android-base/file.h>
53#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070054#include <cutils/fs.h>
55#include <cutils/multiuser.h>
56#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070057#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070058#include <utils/String8.h>
59#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080060#include <seccomp_policy.h>
Howard Ro27330412018-10-02 12:08:28 -070061#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070062#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070063
Andreas Gampeed6b9df2014-11-20 22:02:20 -080064#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070065#include <nativehelper/JNIHelp.h>
66#include <nativehelper/ScopedLocalRef.h>
67#include <nativehelper/ScopedPrimitiveArray.h>
68#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050069#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010070
jgu212eacd062014-09-10 06:55:07 -040071#include "nativebridge/native_bridge.h"
72
Narayan Kamath973b4662014-03-31 13:41:26 +010073namespace {
74
Chris Wailesaf594fc2018-11-02 11:00:07 -070075using namespace std::placeholders;
76
Narayan Kamath973b4662014-03-31 13:41:26 +010077using android::String8;
Sudheer Shanka663b1042018-07-30 17:34:21 -070078using android::base::StringAppendF;
Carmen Jacksondd401252017-02-23 15:21:10 -080079using android::base::StringPrintf;
80using android::base::WriteStringToFile;
Minchan Kim5fa8af22018-06-27 11:32:40 +090081using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010082
Andreas Gamped5758f62018-03-12 12:08:55 -070083#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
84 append(StringPrintf(__VA_ARGS__))
85
Narayan Kamath973b4662014-03-31 13:41:26 +010086static pid_t gSystemServerPid = 0;
87
Sudheer Shanka663b1042018-07-30 17:34:21 -070088static const char kIsolatedStorage[] = "persist.sys.isolated_storage";
Narayan Kamath973b4662014-03-31 13:41:26 +010089static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
90static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +010091static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +010092static jmethodID gCallPostForkChildHooks;
93
Victor Hsiehc8176ef2018-01-08 12:43:00 -080094static bool g_is_security_enforced = true;
95
Narayan Kamath973b4662014-03-31 13:41:26 +010096// Must match values in com.android.internal.os.Zygote.
97enum MountExternalKind {
98 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070099 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700100 MOUNT_EXTERNAL_READ = 2,
101 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700102 MOUNT_EXTERNAL_FULL = 4,
Narayan Kamath973b4662014-03-31 13:41:26 +0100103};
104
Andreas Gampeb053cce2015-11-17 16:38:59 -0800105static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
106 std::ostringstream oss;
107 oss << __FILE__ << ":" << line << ": " << msg;
108 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100109}
110
111// This signal handler is for zygote mode, since the zygote must reap its children
112static void SigChldHandler(int /*signal_number*/) {
113 pid_t pid;
114 int status;
115
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700116 // It's necessary to save and restore the errno during this function.
117 // Since errno is stored per thread, changing it here modifies the errno
118 // on the thread on which this signal handler executes. If a signal occurs
119 // between a call and an errno check, it's possible to get the errno set
120 // here.
121 // See b/23572286 for extra information.
122 int saved_errno = errno;
123
Narayan Kamath973b4662014-03-31 13:41:26 +0100124 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
125 // Log process-death status that we care about. In general it is
126 // not safe to call LOG(...) from a signal handler because of
127 // possible reentrancy. However, we know a priori that the
128 // current implementation of LOG() is safe to call from a SIGCHLD
129 // handler in the zygote process. If the LOG() implementation
130 // changes its locking strategy or its use of syscalls within the
131 // lazy-init critical section, its use here may become unsafe.
132 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700133 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100134 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700135 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100136 if (WCOREDUMP(status)) {
137 ALOGI("Process %d dumped core.", pid);
138 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100139 }
140
141 // If the just-crashed process is the system_server, bring down zygote
142 // so that it is restarted by init and system server will be restarted
143 // from there.
144 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800145 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100146 kill(getpid(), SIGKILL);
147 }
148 }
149
Narayan Kamath160992d2014-04-14 14:46:07 +0100150 // Note that we shouldn't consider ECHILD an error because
151 // the secondary zygote might have no children left to wait for.
152 if (pid < 0 && errno != ECHILD) {
153 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100154 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700155
156 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100157}
158
yuanhao435e84b2018-01-15 15:37:02 +0800159// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
160// configured very late, because earlier in the runtime we may fork() and
161// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100162// have them be harvested immediately.
163//
yuanhao435e84b2018-01-15 15:37:02 +0800164// Ignore SIGHUP because all processes forked by the zygote are in the same
165// process group as the zygote and we don't want to be notified if we become
166// an orphaned group and have one or more stopped processes. This is not a
167// theoretical concern :
168// - we can become an orphaned group if one of our direct descendants forks
169// and is subsequently killed before its children.
170// - crash_dump routinely STOPs the process it's tracing.
171//
172// See issues b/71965619 and b/25567761 for further details.
173//
Narayan Kamath973b4662014-03-31 13:41:26 +0100174// This ends up being called repeatedly before each fork(), but there's
175// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800176static void SetSignalHandlers() {
177 struct sigaction sig_chld = {};
178 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100179
yuanhao435e84b2018-01-15 15:37:02 +0800180 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700181 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100182 }
yuanhao435e84b2018-01-15 15:37:02 +0800183
184 struct sigaction sig_hup = {};
185 sig_hup.sa_handler = SIG_IGN;
186 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
187 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
188 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100189}
190
191// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800192static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100193 struct sigaction sa;
194 memset(&sa, 0, sizeof(sa));
195 sa.sa_handler = SIG_DFL;
196
yuanhao435e84b2018-01-15 15:37:02 +0800197 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700198 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100199 }
200}
201
202// Calls POSIX setgroups() using the int[] object as an argument.
203// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700204static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100205 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700206 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100207 }
208
209 ScopedIntArrayRO gids(env, javaGids);
210 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700211 *error_msg = CREATE_ERROR("Getting gids int array failed");
212 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100213 }
214 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
215 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700216 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
217 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100218 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700219
220 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100221}
222
223// Sets the resource limits via setrlimit(2) for the values in the
224// two-dimensional array of integers that's passed in. The second dimension
225// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
226// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700227static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100228 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700229 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100230 }
231
232 rlimit rlim;
233 memset(&rlim, 0, sizeof(rlim));
234
235 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
236 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
237 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
238 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700239 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
240 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100241 }
242
243 rlim.rlim_cur = javaRlimit[1];
244 rlim.rlim_max = javaRlimit[2];
245
246 int rc = setrlimit(javaRlimit[0], &rlim);
247 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700248 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800249 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700250 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100251 }
252 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700253
254 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100255}
256
Narayan Kamath973b4662014-03-31 13:41:26 +0100257// The debug malloc library needs to know whether it's the zygote or a child.
258extern "C" int gMallocLeakZygoteChild;
259
Christopher Ferris76de39e2017-06-20 16:13:40 -0700260static void PreApplicationInit() {
261 // The child process sets this to indicate it's not the zygote.
262 gMallocLeakZygoteChild = 1;
263
264 // Set the jemalloc decay time to 1.
265 mallopt(M_DECAY_TIME, 1);
266}
267
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800268static void SetUpSeccompFilter(uid_t uid) {
269 if (!g_is_security_enforced) {
270 ALOGI("seccomp disabled by setenforce 0");
271 return;
272 }
273
274 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700275 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800276 set_app_seccomp_filter();
277 } else {
278 set_system_seccomp_filter();
279 }
280}
281
Andreas Gamped5758f62018-03-12 12:08:55 -0700282static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100283 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
284 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700285 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
286 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100287 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700288 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100289}
290
Andreas Gamped5758f62018-03-12 12:08:55 -0700291static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100292 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
293 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
294 if (rc == -1) {
295 if (errno == EINVAL) {
296 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
297 "your kernel is compiled with file capabilities support");
298 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700299 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
300 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100301 }
302 }
303 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700304 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100305}
306
Andreas Gamped5758f62018-03-12 12:08:55 -0700307static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800308 __user_cap_header_struct capheader;
309 memset(&capheader, 0, sizeof(capheader));
310 capheader.version = _LINUX_CAPABILITY_VERSION_3;
311 capheader.pid = 0;
312
313 __user_cap_data_struct capdata[2];
314 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700315 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
316 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800317 }
318
319 capdata[0].inheritable = inheritable;
320 capdata[1].inheritable = inheritable >> 32;
321
322 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700323 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
324 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800325 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700326
327 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800328}
329
Andreas Gamped5758f62018-03-12 12:08:55 -0700330static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
331 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100332 __user_cap_header_struct capheader;
333 memset(&capheader, 0, sizeof(capheader));
334 capheader.version = _LINUX_CAPABILITY_VERSION_3;
335 capheader.pid = 0;
336
337 __user_cap_data_struct capdata[2];
338 memset(&capdata, 0, sizeof(capdata));
339 capdata[0].effective = effective;
340 capdata[1].effective = effective >> 32;
341 capdata[0].permitted = permitted;
342 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800343 capdata[0].inheritable = inheritable;
344 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100345
346 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700347 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
348 "failed: %s", permitted, effective, inheritable, strerror(errno));
349 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100350 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700351 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100352}
353
Andreas Gamped5758f62018-03-12 12:08:55 -0700354static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100355 errno = -set_sched_policy(0, SP_DEFAULT);
356 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700357 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
358 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100359 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700360 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100361}
362
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700363static int UnmountTree(const char* path) {
364 size_t path_len = strlen(path);
365
366 FILE* fp = setmntent("/proc/mounts", "r");
367 if (fp == NULL) {
368 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
369 return -errno;
370 }
371
372 // Some volumes can be stacked on each other, so force unmount in
373 // reverse order to give us the best chance of success.
374 std::list<std::string> toUnmount;
375 mntent* mentry;
376 while ((mentry = getmntent(fp)) != NULL) {
377 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
378 toUnmount.push_front(std::string(mentry->mnt_dir));
379 }
380 }
381 endmntent(fp);
382
383 for (auto path : toUnmount) {
384 if (umount2(path.c_str(), MNT_DETACH)) {
385 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
386 }
387 }
388 return 0;
389}
390
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700391static bool createPkgSandbox(uid_t uid, const std::string& package_name, std::string* error_msg) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700392 // Create /mnt/user/0/package/<package-name>
393 userid_t user_id = multiuser_get_user_id(uid);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700394 std::string pkg_sandbox_dir = StringPrintf("/mnt/user/%d", user_id);
Sudheer Shanka8d8223e2018-08-03 18:18:21 -0700395 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700396 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
397 return false;
398 }
399 StringAppendF(&pkg_sandbox_dir, "/package");
400 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
401 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
402 return false;
403 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700404 StringAppendF(&pkg_sandbox_dir, "/%s", package_name.c_str());
Sudheer Shanka663b1042018-07-30 17:34:21 -0700405 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0755, uid, uid) != 0) {
406 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
407 return false;
408 }
409 return true;
410}
411
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700412static bool mountPkgSpecificDir(const std::string& mntSourceRoot,
413 const std::string& mntTargetRoot, const std::string& packageName,
414 const char* dirName, std::string* error_msg) {
415 std::string mntSourceDir = StringPrintf("%s/Android/%s/%s",
416 mntSourceRoot.c_str(), dirName, packageName.c_str());
417 std::string mntTargetDir = StringPrintf("%s/Android/%s/%s",
418 mntTargetRoot.c_str(), dirName, packageName.c_str());
419 if (TEMP_FAILURE_RETRY(mount(mntSourceDir.c_str(), mntTargetDir.c_str(),
420 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
421 *error_msg = CREATE_ERROR("Failed to mount %s to %s: %s",
422 mntSourceDir.c_str(), mntTargetDir.c_str(), strerror(errno));
423 return false;
424 }
425 if (TEMP_FAILURE_RETRY(mount(nullptr, mntTargetDir.c_str(),
426 nullptr, MS_SLAVE | MS_REC, nullptr)) == -1) {
427 *error_msg = CREATE_ERROR("Failed to set MS_SLAVE for %s", mntTargetDir.c_str());
428 return false;
429 }
430 return true;
431}
432
433static bool preparePkgSpecificDirs(const std::vector<std::string>& packageNames,
434 const std::vector<std::string>& volumeLabels, userid_t userId, std::string* error_msg) {
435 for (auto& label : volumeLabels) {
436 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", label.c_str());
437 std::string mntTarget = StringPrintf("/storage/%s", label.c_str());
438 if (label == "emulated") {
439 StringAppendF(&mntSource, "/%d", userId);
440 StringAppendF(&mntTarget, "/%d", userId);
441 }
442 for (auto& package : packageNames) {
443 mountPkgSpecificDir(mntSource, mntTarget, package, "data", error_msg);
444 mountPkgSpecificDir(mntSource, mntTarget, package, "media", error_msg);
445 mountPkgSpecificDir(mntSource, mntTarget, package, "obb", error_msg);
446 }
447 }
448 return true;
449}
450
Narayan Kamath973b4662014-03-31 13:41:26 +0100451// Create a private mount namespace and bind mount appropriate emulated
452// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700453static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700454 bool force_mount_namespace, std::string* error_msg, const std::string& package_name,
455 const std::vector<std::string>& packages_for_uid,
456 const std::vector<std::string>& visible_vol_ids) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700457 // See storage config details at http://source.android.com/tech/storage/
458
Jeff Sharkey9527b222015-06-24 15:24:48 -0700459 String8 storageSource;
460 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700461 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700462 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700463 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700464 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700465 storageSource = "/mnt/runtime/write";
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700466 } else if (mount_mode != MOUNT_EXTERNAL_FULL && !force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700467 // Sane default of no storage visible
468 return true;
469 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400470
471 // Create a second private mount namespace for our process
472 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700473 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400474 return false;
475 }
476
Robert Sesek06f39302017-03-20 17:30:05 -0400477 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
478 if (mount_mode == MOUNT_EXTERNAL_NONE) {
479 return true;
480 }
481
Sudheer Shanka663b1042018-07-30 17:34:21 -0700482 if (GetBoolProperty(kIsolatedStorage, false)) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700483 if (mount_mode == MOUNT_EXTERNAL_FULL) {
484 storageSource = "/mnt/runtime/write";
485 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
486 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
487 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
488 storageSource.string(),
489 strerror(errno));
490 return false;
491 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700492
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700493 // Mount user-specific symlink helper into place
494 userid_t user_id = multiuser_get_user_id(uid);
495 const String8 userSource(String8::format("/mnt/user/%d", user_id));
496 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
497 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
498 return false;
499 }
500 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
501 NULL, MS_BIND, NULL)) == -1) {
502 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
503 userSource.string(),
504 strerror(errno));
505 return false;
506 }
507 } else {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700508 if (package_name.empty()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700509 return true;
510 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700511 userid_t user_id = multiuser_get_user_id(uid);
512 std::string pkgSandboxDir = StringPrintf("/mnt/user/%d/package/%s",
513 user_id, package_name.c_str());
514 struct stat sb;
515 bool sandboxAlreadyCreated = true;
516 if (TEMP_FAILURE_RETRY(lstat(pkgSandboxDir.c_str(), &sb)) == -1) {
517 if (errno == ENOENT) {
518 ALOGD("Sandbox not yet created for %s", pkgSandboxDir.c_str());
519 sandboxAlreadyCreated = false;
520 if (!createPkgSandbox(uid, package_name, error_msg)) {
521 return false;
522 }
523 } else {
524 ALOGE("Failed to lstat %s", pkgSandboxDir.c_str());
525 return false;
526 }
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700527 }
528 if (TEMP_FAILURE_RETRY(mount(pkgSandboxDir.c_str(), "/storage",
529 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
530 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
531 pkgSandboxDir.c_str(), strerror(errno));
532 return false;
533 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700534 // If the sandbox was already created by vold, only then set up the bind mounts for
535 // pkg specific directories. Otherwise, leave as is and bind mounts will be taken
536 // care of by vold later.
537 if (sandboxAlreadyCreated) {
538 if (!preparePkgSpecificDirs(packages_for_uid, visible_vol_ids,
539 user_id, error_msg)) {
540 return false;
541 }
542 }
Sudheer Shanka663b1042018-07-30 17:34:21 -0700543 }
544 } else {
545 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
546 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
547 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
548 storageSource.string(),
549 strerror(errno));
550 return false;
551 }
552
553 // Mount user-specific symlink helper into place
554 userid_t user_id = multiuser_get_user_id(uid);
555 const String8 userSource(String8::format("/mnt/user/%d", user_id));
556 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
557 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
558 return false;
559 }
560 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
561 NULL, MS_BIND, NULL)) == -1) {
562 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
563 userSource.string(),
564 strerror(errno));
565 return false;
566 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700567 }
568
Narayan Kamath973b4662014-03-31 13:41:26 +0100569 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100570}
571
Narayan Kamath973b4662014-03-31 13:41:26 +0100572static bool NeedsNoRandomizeWorkaround() {
573#if !defined(__arm__)
574 return false;
575#else
576 int major;
577 int minor;
578 struct utsname uts;
579 if (uname(&uts) == -1) {
580 return false;
581 }
582
583 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
584 return false;
585 }
586
587 // Kernels before 3.4.* need the workaround.
588 return (major < 3) || ((major == 3) && (minor < 4));
589#endif
590}
Narayan Kamath973b4662014-03-31 13:41:26 +0100591
592// Utility to close down the Zygote socket file descriptors while
593// the child is still running as root with Zygote's privileges. Each
594// descriptor (if any) is closed via dup2(), replacing it with a valid
595// (open) descriptor to /dev/null.
596
Andreas Gamped5758f62018-03-12 12:08:55 -0700597static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100598 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700599 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100600 }
601 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200602 ScopedIntArrayRO ar(env, fdsToClose);
603 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700604 *error_msg = "Bad fd array";
605 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100606 }
607 jsize i;
608 int devnull;
609 for (i = 0; i < count; i++) {
610 devnull = open("/dev/null", O_RDWR);
611 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700612 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
613 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100614 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700615 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100616 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700617 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
618 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100619 }
620 close(devnull);
621 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700622 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100623}
624
625void SetThreadName(const char* thread_name) {
626 bool hasAt = false;
627 bool hasDot = false;
628 const char* s = thread_name;
629 while (*s) {
630 if (*s == '.') {
631 hasDot = true;
632 } else if (*s == '@') {
633 hasAt = true;
634 }
635 s++;
636 }
637 const int len = s - thread_name;
638 if (len < 15 || hasAt || !hasDot) {
639 s = thread_name;
640 } else {
641 s = thread_name + len - 15;
642 }
643 // pthread_setname_np fails rather than truncating long strings.
644 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
645 strlcpy(buf, s, sizeof(buf)-1);
646 errno = pthread_setname_np(pthread_self(), buf);
647 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700648 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100649 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800650 // Update base::logging default tag.
651 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100652}
653
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100654// The list of open zygote file descriptors.
655static FileDescriptorTable* gOpenFdTable = NULL;
656
Andreas Gamped5758f62018-03-12 12:08:55 -0700657static bool FillFileDescriptorVector(JNIEnv* env,
Chris Wailesaf594fc2018-11-02 11:00:07 -0700658 jintArray managed_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700659 std::vector<int>* fds,
660 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800661 CHECK(fds != nullptr);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700662 if (managed_fds != nullptr) {
663 ScopedIntArrayRO ar(env, managed_fds);
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800664 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700665 *error_msg = "Bad fd array";
666 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800667 }
668 fds->reserve(ar.size());
669 for (size_t i = 0; i < ar.size(); ++i) {
670 fds->push_back(ar[i]);
671 }
672 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700673 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800674}
675
Chris Wailesaf594fc2018-11-02 11:00:07 -0700676[[noreturn]]
677static void ZygoteFailure(JNIEnv* env,
678 const char* process_name,
679 jstring managed_process_name,
680 const std::string& msg) {
681 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
682 if (managed_process_name != nullptr) {
683 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
684 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
685 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -0700686 }
687 }
688
Chris Wailesaf594fc2018-11-02 11:00:07 -0700689 const std::string& error_msg =
690 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700691
Chris Wailesaf594fc2018-11-02 11:00:07 -0700692 env->FatalError(error_msg.c_str());
693 __builtin_unreachable();
694}
David Sehrde8d0bd2018-06-22 10:45:36 -0700695
Chris Wailesaf594fc2018-11-02 11:00:07 -0700696static std::optional<std::string> ExtractJString(JNIEnv* env,
697 const char* process_name,
698 jstring managed_process_name,
699 jstring managed_string) {
700 if (managed_string == nullptr) {
701 return std::optional<std::string>();
702 } else {
703 ScopedUtfChars scoped_string_chars(env, managed_string);
704
705 if (scoped_string_chars.c_str() != nullptr) {
706 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700707 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -0700708 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700709 }
710 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700711}
712
Chris Wailesaf594fc2018-11-02 11:00:07 -0700713// Utility routine to fork a zygote.
714static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
715 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore) {
yuanhao435e84b2018-01-15 15:37:02 +0800716 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100717
David Sehrde8d0bd2018-06-22 10:45:36 -0700718 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000719 sigset_t sigchld;
720 sigemptyset(&sigchld);
721 sigaddset(&sigchld, SIGCHLD);
722
Chris Wailesaf594fc2018-11-02 11:00:07 -0700723 // Curry a failure function.
724 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
725 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -0700726
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000727 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
728 // log, which would result in the logging FDs we close being reopened.
729 // This would cause failures because the FDs are not whitelisted.
730 //
731 // Note that the zygote process is single threaded at this point.
732 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700733 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000734 }
735
Narayan Kamath3764a262016-08-30 15:36:19 +0100736 // Close any logging related FDs before we start evaluating the list of
737 // file descriptors.
738 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -0700739 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +0100740
Chris Wailesaf594fc2018-11-02 11:00:07 -0700741 // If this is the first fork for this zygote, create the open FD table. If
742 // it isn't, we just need to check whether the list of open files has changed
743 // (and it shouldn't in the normal case).
Andreas Gamped5758f62018-03-12 12:08:55 -0700744 std::string error_msg;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800745 std::vector<int> fds_to_ignore;
Chris Wailesaf594fc2018-11-02 11:00:07 -0700746 if (!FillFileDescriptorVector(env, managed_fds_to_ignore, &fds_to_ignore, &error_msg)) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700747 fail_fn(error_msg);
748 }
Chris Wailesaf594fc2018-11-02 11:00:07 -0700749
750 if (gOpenFdTable == nullptr) {
Andreas Gampec362a442018-03-12 14:53:34 -0700751 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700752 if (gOpenFdTable == nullptr) {
Andreas Gampec362a442018-03-12 14:53:34 -0700753 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100754 }
Andreas Gampec362a442018-03-12 14:53:34 -0700755 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
756 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100757 }
758
Josh Gaod7951102018-06-26 16:05:12 -0700759 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
760
Narayan Kamath973b4662014-03-31 13:41:26 +0100761 pid_t pid = fork();
762
763 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700764 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700765 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700766
Narayan Kamath973b4662014-03-31 13:41:26 +0100767 // Clean up any descriptors which must be closed immediately
Chris Wailesaf594fc2018-11-02 11:00:07 -0700768 if (!DetachDescriptors(env, managed_fds_to_close, &error_msg)) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700769 fail_fn(error_msg);
770 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100771
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100772 // Re-open all remaining open file descriptors so that they aren't shared
773 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700774 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
775 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100776 }
Josh Gaod7951102018-06-26 16:05:12 -0700777
778 // Turn fdsan back on.
779 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -0700780 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100781
David Sehrde8d0bd2018-06-22 10:45:36 -0700782 // We blocked SIGCHLD prior to a fork, we unblock it here.
783 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
784 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100785 }
Chris Wailesaf594fc2018-11-02 11:00:07 -0700786
Narayan Kamath973b4662014-03-31 13:41:26 +0100787 return pid;
788}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700789
Chris Wailesaf594fc2018-11-02 11:00:07 -0700790// Utility routine to specialize a zygote child process.
791static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
792 jint runtime_flags, jobjectArray rlimits,
793 jlong permitted_capabilities, jlong effective_capabilities,
794 jint mount_external, jstring managed_se_info,
795 jstring managed_nice_name, bool is_system_server,
796 bool is_child_zygote, jstring managed_instruction_set,
797 jstring managed_app_data_dir, jstring managed_package_name,
798 jobjectArray managed_pacakges_for_uid,
799 jobjectArray managed_visible_vol_ids) {
800 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
801 managed_nice_name, _1);
802 auto extract_fn = std::bind(ExtractJString, env, is_system_server ? "system_server" : "zygote",
803 managed_nice_name, _1);
804
805 auto se_info = extract_fn(managed_se_info);
806 auto nice_name = extract_fn(managed_nice_name);
807 auto instruction_set = extract_fn(managed_instruction_set);
808 auto app_data_dir = extract_fn(managed_app_data_dir);
809 auto package_name = extract_fn(managed_package_name);
810
811 std::string error_msg;
812
813 // Keep capabilities across UID change, unless we're staying root.
814 if (uid != 0) {
815 if (!EnableKeepCapabilities(&error_msg)) {
816 fail_fn(error_msg);
817 }
818 }
819
820 if (!SetInheritable(permitted_capabilities, &error_msg)) {
821 fail_fn(error_msg);
822 }
823
824 if (!DropCapabilitiesBoundingSet(&error_msg)) {
825 fail_fn(error_msg);
826 }
827
828 bool use_native_bridge = !is_system_server &&
829 instruction_set.has_value() &&
830 android::NativeBridgeAvailable() &&
831 android::NeedsNativeBridge(instruction_set.value().c_str());
832
833 if (use_native_bridge && !app_data_dir.has_value()) {
834 // The app_data_dir variable should never be empty if we need to use a
835 // native bridge. In general, app_data_dir will never be empty for normal
836 // applications. It can only happen in special cases (for isolated
837 // processes which are not associated with any app). These are launched by
838 // the framework and should not be emulated anyway.
839 use_native_bridge = false;
840 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
841 }
842
843 if (!package_name.has_value()) {
844 if (is_system_server) {
845 package_name.emplace("android");
846 } else {
847 package_name.emplace("");
848 }
849 }
850
851 std::vector<std::string> packages_for_uid;
852 if (managed_pacakges_for_uid != nullptr) {
853 jsize count = env->GetArrayLength(managed_pacakges_for_uid);
854 for (jsize package_index = 0; package_index < count; ++package_index) {
855 jstring managed_package_for_uid =
856 (jstring) env->GetObjectArrayElement(managed_pacakges_for_uid, package_index);
857
858 auto package_for_uid = extract_fn(managed_package_for_uid);
859 if (LIKELY(package_for_uid.has_value())) {
860 packages_for_uid.emplace_back(std::move(package_for_uid.value()));
861 } else {
862 fail_fn("Null string found in managed packages_for_uid.");
863 }
864 }
865 }
866
867 std::vector<std::string> visible_vol_ids;
868 if (managed_visible_vol_ids != nullptr) {
869 jsize count = env->GetArrayLength(managed_visible_vol_ids);
870 for (jsize vol_id_index = 0; vol_id_index < count; ++vol_id_index) {
871 jstring managed_visible_vol_id =
872 (jstring) env->GetObjectArrayElement(managed_visible_vol_ids, vol_id_index);
873
874 auto visible_vol_id = extract_fn(managed_visible_vol_id);
875 if (LIKELY(visible_vol_id.has_value())) {
876 visible_vol_ids.emplace_back(std::move(visible_vol_id.value()));
877 } else {
878 fail_fn("Null string found in managed visible_vol_ids.");
879 }
880 }
881 }
882
883 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg,
884 package_name.value(), packages_for_uid, visible_vol_ids)) {
885 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
886 if (errno == ENOTCONN || errno == EROFS) {
887 // When device is actively encrypting, we get ENOTCONN here
888 // since FUSE was mounted before the framework restarted.
889 // When encrypted device is booting, we get EROFS since
890 // FUSE hasn't been created yet by init.
891 // In either case, continue without external storage.
892 } else {
893 fail_fn(error_msg);
894 }
895 }
896
897 // If this zygote isn't root, it won't be able to create a process group,
898 // since the directory is owned by root.
899 if (!is_system_server && getuid() == 0) {
900 int rc = createProcessGroup(uid, getpid());
901 if (rc == -EROFS) {
902 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
903 } else if (rc != 0) {
904 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
905 }
906 }
907
908 if (!SetGids(env, gids, &error_msg)) {
909 fail_fn(error_msg);
910 }
911
912 if (!SetRLimits(env, rlimits, &error_msg)) {
913 fail_fn(error_msg);
914 }
915
916 if (use_native_bridge) {
917 // Due to the logic behind use_native_bridge we know that both app_data_dir
918 // and instruction_set contain values.
919 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
920 instruction_set.value().c_str());
921 }
922
923 if (setresgid(gid, gid, gid) == -1) {
924 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
925 }
926
927 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
928 // before changing uid from 0, which clears capabilities. The other
929 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
930 // breaks SELinux domain transition (see b/71859146). As the result,
931 // privileged syscalls used below still need to be accessible in app process.
932 SetUpSeccompFilter(uid);
933
934 if (setresuid(uid, uid, uid) == -1) {
935 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
936 }
937
938 // The "dumpable" flag of a process, which controls core dump generation, is
939 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
940 // user or group ID changes. See proc(5) for possible values. In most cases,
941 // the value is 0, so core dumps are disabled for zygote children. However,
942 // when running in a Chrome OS container, the value is already set to 2,
943 // which allows the external crash reporter to collect all core dumps. Since
944 // only system crashes are interested, core dump is disabled for app
945 // processes. This also ensures compliance with CTS.
946 int dumpable = prctl(PR_GET_DUMPABLE);
947 if (dumpable == -1) {
948 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
949 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
950 }
951
952 if (dumpable == 2 && uid >= AID_APP) {
953 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
954 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
955 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
956 }
957 }
958
959 if (NeedsNoRandomizeWorkaround()) {
960 // Work around ARM kernel ASLR lossage (http://b/5817320).
961 int old_personality = personality(0xffffffff);
962 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
963 if (new_personality == -1) {
964 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
965 }
966 }
967
968 if (!SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities,
969 &error_msg)) {
970 fail_fn(error_msg);
971 }
972
973 if (!SetSchedulerPolicy(&error_msg)) {
974 fail_fn(error_msg);
975 }
976
977 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
978 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
979
980 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
981 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
982 uid, is_system_server, se_info_ptr, nice_name_ptr));
983 }
984
985 // Make it easier to debug audit logs by setting the main thread's name to the
986 // nice name rather than "app_process".
987 if (nice_name.has_value()) {
988 SetThreadName(nice_name.value().c_str());
989 } else if (is_system_server) {
990 SetThreadName("system_server");
991 }
992
993 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
994 UnsetChldSignalHandler();
995
996 if (is_system_server) {
997 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
998 if (env->ExceptionCheck()) {
999 fail_fn("Error calling post fork system server hooks.");
1000 }
1001 // TODO(oth): Remove hardcoded label here (b/117874058).
1002 static const char* kSystemServerLabel = "u:r:system_server:s0";
1003 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1004 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1005 }
1006 }
1007
1008 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1009 is_system_server, is_child_zygote, managed_instruction_set);
1010
1011 if (env->ExceptionCheck()) {
1012 fail_fn("Error calling post fork hooks.");
1013 }
1014}
1015
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001016static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1017 __user_cap_header_struct capheader;
1018 memset(&capheader, 0, sizeof(capheader));
1019 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1020 capheader.pid = 0;
1021
1022 __user_cap_data_struct capdata[2];
1023 if (capget(&capheader, &capdata[0]) == -1) {
1024 ALOGE("capget failed: %s", strerror(errno));
1025 RuntimeAbort(env, __LINE__, "capget failed");
1026 }
1027
Chris Wailesaf594fc2018-11-02 11:00:07 -07001028 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1029}
1030
1031static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1032 bool is_child_zygote) {
1033 jlong capabilities = 0;
1034
1035 /*
1036 * Grant the following capabilities to the Bluetooth user:
1037 * - CAP_WAKE_ALARM
1038 * - CAP_NET_RAW
1039 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1040 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1041 */
1042
1043 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1044 capabilities |= (1LL << CAP_WAKE_ALARM);
1045 capabilities |= (1LL << CAP_NET_RAW);
1046 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1047 capabilities |= (1LL << CAP_SYS_NICE);
1048 }
1049
1050 /*
1051 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1052 */
1053
1054 bool gid_wakelock_found = false;
1055 if (gid == AID_WAKELOCK) {
1056 gid_wakelock_found = true;
1057 } else if (gids != nullptr) {
1058 jsize gids_num = env->GetArrayLength(gids);
1059 ScopedIntArrayRO native_gid_proxy(env, gids);
1060
1061 if (native_gid_proxy.get() == nullptr) {
1062 RuntimeAbort(env, __LINE__, "Bad gids array");
1063 }
1064
1065 for (int gid_index = gids_num; --gids_num >= 0;) {
1066 if (native_gid_proxy[gid_index] == AID_WAKELOCK) {
1067 gid_wakelock_found = true;
1068 break;
1069 }
1070 }
1071 }
1072
1073 if (gid_wakelock_found) {
1074 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1075 }
1076
1077 /*
1078 * Grant child Zygote processes the following capabilities:
1079 * - CAP_SETUID (change UID of child processes)
1080 * - CAP_SETGID (change GID of child processes)
1081 * - CAP_SETPCAP (change capabilities of child processes)
1082 */
1083
1084 if (is_child_zygote) {
1085 capabilities |= (1LL << CAP_SETUID);
1086 capabilities |= (1LL << CAP_SETGID);
1087 capabilities |= (1LL << CAP_SETPCAP);
1088 }
1089
1090 /*
1091 * Containers run without some capabilities, so drop any caps that are not
1092 * available.
1093 */
1094
1095 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001096}
Narayan Kamath973b4662014-03-31 13:41:26 +01001097} // anonymous namespace
1098
1099namespace android {
1100
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001101static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001102 // security_getenforce is not allowed on app process. Initialize and cache
1103 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001104 g_is_security_enforced = security_getenforce();
1105}
1106
Christopher Ferris76de39e2017-06-20 16:13:40 -07001107static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1108 PreApplicationInit();
1109}
1110
Narayan Kamath973b4662014-03-31 13:41:26 +01001111static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1112 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001113 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001114 jint mount_external, jstring se_info, jstring nice_name,
1115 jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote,
1116 jstring instruction_set, jstring app_data_dir, jstring package_name,
1117 jobjectArray packages_for_uid, jobjectArray visible_vol_ids) {
1118 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001119
Chris Wailesaf594fc2018-11-02 11:00:07 -07001120 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001121 if (pid == 0) {
1122 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1123 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001124 mount_external, se_info, nice_name, false,
1125 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
1126 package_name, packages_for_uid, visible_vol_ids);
David Sehrde8d0bd2018-06-22 10:45:36 -07001127 }
1128 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001129}
1130
1131static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1132 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001133 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1134 jlong effective_capabilities) {
1135 pid_t pid = ForkCommon(env, true,
1136 /* managed_fds_to_close= */ nullptr,
1137 /* managed_fds_to_ignore= */ nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001138 if (pid == 0) {
1139 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001140 permitted_capabilities, effective_capabilities,
1141 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1142 false, nullptr, nullptr, nullptr, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001143 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001144 // The zygote process checks whether the child process has died or not.
1145 ALOGI("System server process %d has been created", pid);
1146 gSystemServerPid = pid;
1147 // There is a slight window that the system server process has crashed
1148 // but it went unnoticed because we haven't published its pid yet. So
1149 // we recheck here just to make sure that all is well.
1150 int status;
1151 if (waitpid(pid, &status, WNOHANG) == pid) {
1152 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001153 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001154 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001155
Minchan Kim5fa8af22018-06-27 11:32:40 +09001156 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
1157 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
1158 if (per_app_memcg) {
1159 // Assign system_server to the correct memory cgroup.
1160 // Not all devices mount /dev/memcg so check for the file first
1161 // to avoid unnecessarily printing errors and denials in the logs.
1162 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -08001163 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001164 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
1165 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001166 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001167 }
1168 return pid;
1169}
1170
Robert Sesek54e387d2016-12-02 17:27:50 -05001171static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1172 JNIEnv* env, jclass, jstring path) {
1173 ScopedUtfChars path_native(env, path);
1174 const char* path_cstr = path_native.c_str();
1175 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001176 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001177 }
1178 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1179}
1180
doheon1.lee885b7422016-01-20 13:07:27 +09001181static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1182 // Zygote process unmount root storage space initially before every child processes are forked.
1183 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001184 // and no need unmount storage operation in MountEmulatedStorage method.
1185 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1186
1187 // See storage config details at http://source.android.com/tech/storage/
1188 // Create private mount namespace shared by all children
1189 if (unshare(CLONE_NEWNS) == -1) {
1190 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1191 return;
1192 }
1193
1194 // Mark rootfs as being a slave so that changes from default
1195 // namespace only flow into our children.
1196 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1197 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1198 return;
1199 }
1200
1201 // Create a staging tmpfs that is shared by our children; they will
1202 // bind mount storage into their respective private namespaces, which
1203 // are isolated from each other.
1204 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1205 if (target_base != nullptr) {
1206#define STRINGIFY_UID(x) __STRING(x)
1207 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1208 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1209 ALOGE("Failed to mount tmpfs to %s", target_base);
1210 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1211 return;
1212 }
1213#undef STRINGIFY_UID
1214 }
doheon1.lee885b7422016-01-20 13:07:27 +09001215
1216 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001217}
1218
Daniel Micay76f6a862015-09-19 17:31:01 -04001219static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001220 { "nativeSecurityInit", "()V",
1221 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001222 { "nativeForkAndSpecialize",
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001223 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001224 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1225 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001226 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001227 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1228 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001229 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001230 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1231 { "nativePreApplicationInit", "()V",
1232 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001233};
1234
1235int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001236 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001237 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1238 "callPostForkSystemServerHooks",
1239 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001240 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001241 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001242
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001243 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001244}
1245} // namespace android