blob: ac9e636adb2a025a54682fbbb53bbf68cd024dd7 [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
Colin Cross18cd9f52014-06-13 12:58:55 -070027#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080028#include <grp.h>
29#include <inttypes.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070030#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010031#include <paths.h>
32#include <signal.h>
33#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070034#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040035#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070036#include <sys/personality.h>
37#include <sys/prctl.h>
38#include <sys/resource.h>
39#include <sys/stat.h>
Vitalii Tomkiv1e52ce42016-05-18 17:43:02 -070040#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070041#include <sys/types.h>
42#include <sys/utsname.h>
43#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080044#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070045
Andreas Gampe8dfa1782017-01-05 12:45:58 -080046#include "android-base/logging.h"
Colin Cross18cd9f52014-06-13 12:58:55 -070047#include <cutils/fs.h>
48#include <cutils/multiuser.h>
49#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070050#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070051#include <utils/String8.h>
52#include <selinux/android.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070053#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070054
Andreas Gampeed6b9df2014-11-20 22:02:20 -080055#include "core_jni_helpers.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010056#include "JNIHelp.h"
57#include "ScopedLocalRef.h"
58#include "ScopedPrimitiveArray.h"
59#include "ScopedUtfChars.h"
Robert Sesek8225b7c2016-12-16 14:02:31 -050060#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010061
jgu212eacd062014-09-10 06:55:07 -040062#include "nativebridge/native_bridge.h"
63
Narayan Kamath973b4662014-03-31 13:41:26 +010064namespace {
65
66using android::String8;
67
68static pid_t gSystemServerPid = 0;
69
70static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
71static jclass gZygoteClass;
72static jmethodID gCallPostForkChildHooks;
73
74// Must match values in com.android.internal.os.Zygote.
75enum MountExternalKind {
76 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070077 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070078 MOUNT_EXTERNAL_READ = 2,
79 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010080};
81
Andreas Gampeb053cce2015-11-17 16:38:59 -080082static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
83 std::ostringstream oss;
84 oss << __FILE__ << ":" << line << ": " << msg;
85 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +010086}
87
88// This signal handler is for zygote mode, since the zygote must reap its children
89static void SigChldHandler(int /*signal_number*/) {
90 pid_t pid;
91 int status;
92
Christopher Ferrisa8a79542015-08-31 15:40:01 -070093 // It's necessary to save and restore the errno during this function.
94 // Since errno is stored per thread, changing it here modifies the errno
95 // on the thread on which this signal handler executes. If a signal occurs
96 // between a call and an errno check, it's possible to get the errno set
97 // here.
98 // See b/23572286 for extra information.
99 int saved_errno = errno;
100
Narayan Kamath973b4662014-03-31 13:41:26 +0100101 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
102 // Log process-death status that we care about. In general it is
103 // not safe to call LOG(...) from a signal handler because of
104 // possible reentrancy. However, we know a priori that the
105 // current implementation of LOG() is safe to call from a SIGCHLD
106 // handler in the zygote process. If the LOG() implementation
107 // changes its locking strategy or its use of syscalls within the
108 // lazy-init critical section, its use here may become unsafe.
109 if (WIFEXITED(status)) {
110 if (WEXITSTATUS(status)) {
111 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100112 }
113 } else if (WIFSIGNALED(status)) {
114 if (WTERMSIG(status) != SIGKILL) {
Narayan Kamath160992d2014-04-14 14:46:07 +0100115 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100116 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100117 if (WCOREDUMP(status)) {
118 ALOGI("Process %d dumped core.", pid);
119 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100120 }
121
122 // If the just-crashed process is the system_server, bring down zygote
123 // so that it is restarted by init and system server will be restarted
124 // from there.
125 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800126 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100127 kill(getpid(), SIGKILL);
128 }
129 }
130
Narayan Kamath160992d2014-04-14 14:46:07 +0100131 // Note that we shouldn't consider ECHILD an error because
132 // the secondary zygote might have no children left to wait for.
133 if (pid < 0 && errno != ECHILD) {
134 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100135 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700136
137 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100138}
139
140// Configures the SIGCHLD handler for the zygote process. This is configured
141// very late, because earlier in the runtime we may fork() and exec()
142// other processes, and we want to waitpid() for those rather than
143// have them be harvested immediately.
144//
145// This ends up being called repeatedly before each fork(), but there's
146// no real harm in that.
147static void SetSigChldHandler() {
148 struct sigaction sa;
149 memset(&sa, 0, sizeof(sa));
150 sa.sa_handler = SigChldHandler;
151
152 int err = sigaction(SIGCHLD, &sa, NULL);
153 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700154 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100155 }
156}
157
158// Sets the SIGCHLD handler back to default behavior in zygote children.
159static void UnsetSigChldHandler() {
160 struct sigaction sa;
161 memset(&sa, 0, sizeof(sa));
162 sa.sa_handler = SIG_DFL;
163
164 int err = sigaction(SIGCHLD, &sa, NULL);
165 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700166 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100167 }
168}
169
170// Calls POSIX setgroups() using the int[] object as an argument.
171// A NULL argument is tolerated.
172static void SetGids(JNIEnv* env, jintArray javaGids) {
173 if (javaGids == NULL) {
174 return;
175 }
176
177 ScopedIntArrayRO gids(env, javaGids);
178 if (gids.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800179 RuntimeAbort(env, __LINE__, "Getting gids int array failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100180 }
181 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
182 if (rc == -1) {
Narayan Kamath593aab72016-08-09 17:23:31 +0100183 std::ostringstream oss;
184 oss << "setgroups failed: " << strerror(errno) << ", gids.size=" << gids.size();
185 RuntimeAbort(env, __LINE__, oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100186 }
187}
188
189// Sets the resource limits via setrlimit(2) for the values in the
190// two-dimensional array of integers that's passed in. The second dimension
191// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
192// treated as an empty array.
193static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
194 if (javaRlimits == NULL) {
195 return;
196 }
197
198 rlimit rlim;
199 memset(&rlim, 0, sizeof(rlim));
200
201 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
202 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
203 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
204 if (javaRlimit.size() != 3) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800205 RuntimeAbort(env, __LINE__, "rlimits array must have a second dimension of size 3");
Narayan Kamath973b4662014-03-31 13:41:26 +0100206 }
207
208 rlim.rlim_cur = javaRlimit[1];
209 rlim.rlim_max = javaRlimit[2];
210
211 int rc = setrlimit(javaRlimit[0], &rlim);
212 if (rc == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800213 ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
214 rlim.rlim_max);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800215 RuntimeAbort(env, __LINE__, "setrlimit failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100216 }
217 }
218}
219
Narayan Kamath973b4662014-03-31 13:41:26 +0100220// The debug malloc library needs to know whether it's the zygote or a child.
221extern "C" int gMallocLeakZygoteChild;
222
223static void EnableKeepCapabilities(JNIEnv* env) {
224 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
225 if (rc == -1) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800226 RuntimeAbort(env, __LINE__, "prctl(PR_SET_KEEPCAPS) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100227 }
228}
229
230static void DropCapabilitiesBoundingSet(JNIEnv* env) {
231 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
232 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
233 if (rc == -1) {
234 if (errno == EINVAL) {
235 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
236 "your kernel is compiled with file capabilities support");
237 } else {
Josh Gao45dab782017-02-01 14:56:09 -0800238 ALOGE("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800239 RuntimeAbort(env, __LINE__, "prctl(PR_CAPBSET_DROP) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100240 }
241 }
242 }
243}
244
Josh Gao45dab782017-02-01 14:56:09 -0800245static void SetInheritable(JNIEnv* env, uint64_t inheritable) {
246 __user_cap_header_struct capheader;
247 memset(&capheader, 0, sizeof(capheader));
248 capheader.version = _LINUX_CAPABILITY_VERSION_3;
249 capheader.pid = 0;
250
251 __user_cap_data_struct capdata[2];
252 if (capget(&capheader, &capdata[0]) == -1) {
253 ALOGE("capget failed: %s", strerror(errno));
254 RuntimeAbort(env, __LINE__, "capget failed");
255 }
256
257 capdata[0].inheritable = inheritable;
258 capdata[1].inheritable = inheritable >> 32;
259
260 if (capset(&capheader, &capdata[0]) == -1) {
261 ALOGE("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
262 RuntimeAbort(env, __LINE__, "capset failed");
263 }
264}
265
266static void SetCapabilities(JNIEnv* env, uint64_t permitted, uint64_t effective,
267 uint64_t inheritable) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100268 __user_cap_header_struct capheader;
269 memset(&capheader, 0, sizeof(capheader));
270 capheader.version = _LINUX_CAPABILITY_VERSION_3;
271 capheader.pid = 0;
272
273 __user_cap_data_struct capdata[2];
274 memset(&capdata, 0, sizeof(capdata));
275 capdata[0].effective = effective;
276 capdata[1].effective = effective >> 32;
277 capdata[0].permitted = permitted;
278 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800279 capdata[0].inheritable = inheritable;
280 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100281
282 if (capset(&capheader, &capdata[0]) == -1) {
Josh Gao45dab782017-02-01 14:56:09 -0800283 ALOGE("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") failed: %s", permitted,
284 effective, inheritable, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800285 RuntimeAbort(env, __LINE__, "capset failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100286 }
287}
288
289static void SetSchedulerPolicy(JNIEnv* env) {
290 errno = -set_sched_policy(0, SP_DEFAULT);
291 if (errno != 0) {
292 ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
Andreas Gampeb053cce2015-11-17 16:38:59 -0800293 RuntimeAbort(env, __LINE__, "set_sched_policy(0, SP_DEFAULT) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100294 }
295}
296
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700297static int UnmountTree(const char* path) {
298 size_t path_len = strlen(path);
299
300 FILE* fp = setmntent("/proc/mounts", "r");
301 if (fp == NULL) {
302 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
303 return -errno;
304 }
305
306 // Some volumes can be stacked on each other, so force unmount in
307 // reverse order to give us the best chance of success.
308 std::list<std::string> toUnmount;
309 mntent* mentry;
310 while ((mentry = getmntent(fp)) != NULL) {
311 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
312 toUnmount.push_front(std::string(mentry->mnt_dir));
313 }
314 }
315 endmntent(fp);
316
317 for (auto path : toUnmount) {
318 if (umount2(path.c_str(), MNT_DETACH)) {
319 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
320 }
321 }
322 return 0;
323}
324
Narayan Kamath973b4662014-03-31 13:41:26 +0100325// Create a private mount namespace and bind mount appropriate emulated
326// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700327static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
328 bool force_mount_namespace) {
329 // See storage config details at http://source.android.com/tech/storage/
330
Jeff Sharkey9527b222015-06-24 15:24:48 -0700331 String8 storageSource;
332 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700333 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700334 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700335 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700336 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700337 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500338 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700339 // Sane default of no storage visible
340 return true;
341 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400342
343 // Create a second private mount namespace for our process
344 if (unshare(CLONE_NEWNS) == -1) {
345 ALOGW("Failed to unshare(): %s", strerror(errno));
346 return false;
347 }
348
Robert Sesek06f39302017-03-20 17:30:05 -0400349 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
350 if (mount_mode == MOUNT_EXTERNAL_NONE) {
351 return true;
352 }
353
Jeff Sharkey9527b222015-06-24 15:24:48 -0700354 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
355 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
356 ALOGW("Failed to mount %s to /storage: %s", storageSource.string(), strerror(errno));
357 return false;
358 }
359
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700360 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700361 userid_t user_id = multiuser_get_user_id(uid);
362 const String8 userSource(String8::format("/mnt/user/%d", user_id));
363 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
364 return false;
365 }
366 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
367 NULL, MS_BIND, NULL)) == -1) {
368 ALOGW("Failed to mount %s to /storage/self: %s", userSource.string(), strerror(errno));
369 return false;
370 }
371
Narayan Kamath973b4662014-03-31 13:41:26 +0100372 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100373}
374
Narayan Kamath973b4662014-03-31 13:41:26 +0100375static bool NeedsNoRandomizeWorkaround() {
376#if !defined(__arm__)
377 return false;
378#else
379 int major;
380 int minor;
381 struct utsname uts;
382 if (uname(&uts) == -1) {
383 return false;
384 }
385
386 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
387 return false;
388 }
389
390 // Kernels before 3.4.* need the workaround.
391 return (major < 3) || ((major == 3) && (minor < 4));
392#endif
393}
Narayan Kamath973b4662014-03-31 13:41:26 +0100394
395// Utility to close down the Zygote socket file descriptors while
396// the child is still running as root with Zygote's privileges. Each
397// descriptor (if any) is closed via dup2(), replacing it with a valid
398// (open) descriptor to /dev/null.
399
400static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
401 if (!fdsToClose) {
402 return;
403 }
404 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200405 ScopedIntArrayRO ar(env, fdsToClose);
406 if (ar.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800407 RuntimeAbort(env, __LINE__, "Bad fd array");
Narayan Kamath973b4662014-03-31 13:41:26 +0100408 }
409 jsize i;
410 int devnull;
411 for (i = 0; i < count; i++) {
412 devnull = open("/dev/null", O_RDWR);
413 if (devnull < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700414 ALOGE("Failed to open /dev/null: %s", strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800415 RuntimeAbort(env, __LINE__, "Failed to open /dev/null");
Narayan Kamath973b4662014-03-31 13:41:26 +0100416 continue;
417 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700418 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100419 if (dup2(devnull, ar[i]) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700420 ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800421 RuntimeAbort(env, __LINE__, "Failed dup2()");
Narayan Kamath973b4662014-03-31 13:41:26 +0100422 }
423 close(devnull);
424 }
425}
426
427void SetThreadName(const char* thread_name) {
428 bool hasAt = false;
429 bool hasDot = false;
430 const char* s = thread_name;
431 while (*s) {
432 if (*s == '.') {
433 hasDot = true;
434 } else if (*s == '@') {
435 hasAt = true;
436 }
437 s++;
438 }
439 const int len = s - thread_name;
440 if (len < 15 || hasAt || !hasDot) {
441 s = thread_name;
442 } else {
443 s = thread_name + len - 15;
444 }
445 // pthread_setname_np fails rather than truncating long strings.
446 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
447 strlcpy(buf, s, sizeof(buf)-1);
448 errno = pthread_setname_np(pthread_self(), buf);
449 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700450 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100451 }
452}
453
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100454// The list of open zygote file descriptors.
455static FileDescriptorTable* gOpenFdTable = NULL;
456
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800457static void FillFileDescriptorVector(JNIEnv* env,
458 jintArray java_fds,
459 std::vector<int>* fds) {
460 CHECK(fds != nullptr);
461 if (java_fds != nullptr) {
462 ScopedIntArrayRO ar(env, java_fds);
463 if (ar.get() == nullptr) {
464 RuntimeAbort(env, __LINE__, "Bad fd array");
465 }
466 fds->reserve(ar.size());
467 for (size_t i = 0; i < ar.size(); ++i) {
468 fds->push_back(ar[i]);
469 }
470 }
471}
472
Narayan Kamath973b4662014-03-31 13:41:26 +0100473// Utility routine to fork zygote and specialize the child process.
474static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
475 jint debug_flags, jobjectArray javaRlimits,
476 jlong permittedCapabilities, jlong effectiveCapabilities,
477 jint mount_external,
478 jstring java_se_info, jstring java_se_name,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700479 bool is_system_server, jintArray fdsToClose,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800480 jintArray fdsToIgnore,
jgu212eacd062014-09-10 06:55:07 -0400481 jstring instructionSet, jstring dataDir) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100482 SetSigChldHandler();
483
Narayan Kamath3764a262016-08-30 15:36:19 +0100484 // Close any logging related FDs before we start evaluating the list of
485 // file descriptors.
486 __android_log_close();
487
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100488 // If this is the first fork for this zygote, create the open FD table.
489 // If it isn't, we just need to check whether the list of open files has
490 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800491 std::vector<int> fds_to_ignore;
492 FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100493 if (gOpenFdTable == NULL) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800494 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100495 if (gOpenFdTable == NULL) {
496 RuntimeAbort(env, __LINE__, "Unable to construct file descriptor table.");
497 }
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800498 } else if (!gOpenFdTable->Restat(fds_to_ignore)) {
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100499 RuntimeAbort(env, __LINE__, "Unable to restat file descriptor table.");
500 }
501
Narayan Kamath973b4662014-03-31 13:41:26 +0100502 pid_t pid = fork();
503
504 if (pid == 0) {
505 // The child process.
506 gMallocLeakZygoteChild = 1;
507
508 // Clean up any descriptors which must be closed immediately
509 DetachDescriptors(env, fdsToClose);
510
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100511 // Re-open all remaining open file descriptors so that they aren't shared
512 // with the zygote across a fork.
Narayan Kamath3764a262016-08-30 15:36:19 +0100513 if (!gOpenFdTable->ReopenOrDetach()) {
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100514 RuntimeAbort(env, __LINE__, "Unable to reopen whitelisted descriptors.");
515 }
516
Narayan Kamath973b4662014-03-31 13:41:26 +0100517 // Keep capabilities across UID change, unless we're staying root.
518 if (uid != 0) {
519 EnableKeepCapabilities(env);
520 }
521
Josh Gao45dab782017-02-01 14:56:09 -0800522 SetInheritable(env, permittedCapabilities);
Narayan Kamath973b4662014-03-31 13:41:26 +0100523 DropCapabilitiesBoundingSet(env);
524
Calin Juravle79ec4c12014-10-24 16:16:49 +0100525 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
526 && android::NativeBridgeAvailable();
527 if (use_native_bridge) {
jgu212eacd062014-09-10 06:55:07 -0400528 ScopedUtfChars isa_string(env, instructionSet);
Calin Juravle79ec4c12014-10-24 16:16:49 +0100529 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400530 }
Calin Juravle6a4d2362014-10-28 12:16:21 +0000531 if (use_native_bridge && dataDir == NULL) {
532 // dataDir should never be null if we need to use a native bridge.
533 // In general, dataDir will never be null for normal applications. It can only happen in
534 // special cases (for isolated processes which are not associated with any app). These are
535 // launched by the framework and should not be emulated anyway.
536 use_native_bridge = false;
537 ALOGW("Native bridge will not be used because dataDir == NULL.");
538 }
jgu212eacd062014-09-10 06:55:07 -0400539
Calin Juravle79ec4c12014-10-24 16:16:49 +0100540 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700541 ALOGW("Failed to mount emulated storage: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100542 if (errno == ENOTCONN || errno == EROFS) {
543 // When device is actively encrypting, we get ENOTCONN here
544 // since FUSE was mounted before the framework restarted.
545 // When encrypted device is booting, we get EROFS since
546 // FUSE hasn't been created yet by init.
547 // In either case, continue without external storage.
548 } else {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800549 RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage");
Narayan Kamath973b4662014-03-31 13:41:26 +0100550 }
551 }
552
Colin Cross0161bbc2014-06-03 13:26:58 -0700553 if (!is_system_server) {
554 int rc = createProcessGroup(uid, getpid());
555 if (rc != 0) {
Colin Cross3089bed2014-07-14 15:07:04 -0700556 if (rc == -EROFS) {
557 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
558 } else {
559 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
560 }
Colin Cross0161bbc2014-06-03 13:26:58 -0700561 }
562 }
563
Narayan Kamath973b4662014-03-31 13:41:26 +0100564 SetGids(env, javaGids);
565
566 SetRLimits(env, javaRlimits);
567
Calin Juravle79ec4c12014-10-24 16:16:49 +0100568 if (use_native_bridge) {
569 ScopedUtfChars isa_string(env, instructionSet);
570 ScopedUtfChars data_dir(env, dataDir);
571 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400572 }
573
Narayan Kamath973b4662014-03-31 13:41:26 +0100574 int rc = setresgid(gid, gid, gid);
575 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700576 ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800577 RuntimeAbort(env, __LINE__, "setresgid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100578 }
579
580 rc = setresuid(uid, uid, uid);
581 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700582 ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800583 RuntimeAbort(env, __LINE__, "setresuid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100584 }
585
Narayan Kamath973b4662014-03-31 13:41:26 +0100586 if (NeedsNoRandomizeWorkaround()) {
587 // Work around ARM kernel ASLR lossage (http://b/5817320).
588 int old_personality = personality(0xffffffff);
589 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
590 if (new_personality == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700591 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100592 }
593 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100594
Josh Gao45dab782017-02-01 14:56:09 -0800595 SetCapabilities(env, permittedCapabilities, effectiveCapabilities, permittedCapabilities);
Narayan Kamath973b4662014-03-31 13:41:26 +0100596
597 SetSchedulerPolicy(env);
598
Colin Cross18cd9f52014-06-13 12:58:55 -0700599 const char* se_info_c_str = NULL;
600 ScopedUtfChars* se_info = NULL;
601 if (java_se_info != NULL) {
602 se_info = new ScopedUtfChars(env, java_se_info);
603 se_info_c_str = se_info->c_str();
604 if (se_info_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800605 RuntimeAbort(env, __LINE__, "se_info_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700606 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100607 }
Colin Cross18cd9f52014-06-13 12:58:55 -0700608 const char* se_name_c_str = NULL;
609 ScopedUtfChars* se_name = NULL;
610 if (java_se_name != NULL) {
611 se_name = new ScopedUtfChars(env, java_se_name);
612 se_name_c_str = se_name->c_str();
613 if (se_name_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800614 RuntimeAbort(env, __LINE__, "se_name_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700615 }
616 }
617 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
618 if (rc == -1) {
619 ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
620 is_system_server, se_info_c_str, se_name_c_str);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800621 RuntimeAbort(env, __LINE__, "selinux_android_setcontext failed");
Colin Cross18cd9f52014-06-13 12:58:55 -0700622 }
623
624 // Make it easier to debug audit logs by setting the main thread's name to the
625 // nice name rather than "app_process".
626 if (se_info_c_str == NULL && is_system_server) {
627 se_name_c_str = "system_server";
628 }
629 if (se_info_c_str != NULL) {
630 SetThreadName(se_name_c_str);
631 }
632
633 delete se_info;
634 delete se_name;
Narayan Kamath973b4662014-03-31 13:41:26 +0100635
636 UnsetSigChldHandler();
637
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700638 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000639 is_system_server, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100640 if (env->ExceptionCheck()) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800641 RuntimeAbort(env, __LINE__, "Error calling post fork hooks.");
Narayan Kamath973b4662014-03-31 13:41:26 +0100642 }
643 } else if (pid > 0) {
644 // the parent process
645 }
646 return pid;
647}
648} // anonymous namespace
649
650namespace android {
651
652static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
653 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
654 jint debug_flags, jobjectArray rlimits,
655 jint mount_external, jstring se_info, jstring se_name,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800656 jintArray fdsToClose,
657 jintArray fdsToIgnore,
658 jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700659 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800660
661 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900662 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
663 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800664 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800665 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900666 capabilities |= (1LL << CAP_NET_RAW);
667 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800668 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700669
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800670 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
671 bool gid_wakelock_found = false;
672 if (gid == AID_WAKELOCK) {
673 gid_wakelock_found = true;
674 } else if (gids != NULL) {
675 jsize gids_num = env->GetArrayLength(gids);
676 ScopedIntArrayRO ar(env, gids);
677 if (ar.get() == NULL) {
678 RuntimeAbort(env, __LINE__, "Bad gids array");
679 }
680 for (int i = 0; i < gids_num; i++) {
681 if (ar[i] == AID_WAKELOCK) {
682 gid_wakelock_found = true;
683 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700684 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800685 }
686 }
687 if (gid_wakelock_found) {
688 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700689 }
690
Narayan Kamath973b4662014-03-31 13:41:26 +0100691 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700692 rlimits, capabilities, capabilities, mount_external, se_info,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800693 se_name, false, fdsToClose, fdsToIgnore, instructionSet, appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100694}
695
696static jint com_android_internal_os_Zygote_nativeForkSystemServer(
697 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
698 jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
699 jlong effectiveCapabilities) {
700 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
701 debug_flags, rlimits,
702 permittedCapabilities, effectiveCapabilities,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700703 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800704 NULL, NULL, NULL);
Narayan Kamath973b4662014-03-31 13:41:26 +0100705 if (pid > 0) {
706 // The zygote process checks whether the child process has died or not.
707 ALOGI("System server process %d has been created", pid);
708 gSystemServerPid = pid;
709 // There is a slight window that the system server process has crashed
710 // but it went unnoticed because we haven't published its pid yet. So
711 // we recheck here just to make sure that all is well.
712 int status;
713 if (waitpid(pid, &status, WNOHANG) == pid) {
714 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800715 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100716 }
717 }
718 return pid;
719}
720
Robert Sesek54e387d2016-12-02 17:27:50 -0500721static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
722 JNIEnv* env, jclass, jstring path) {
723 ScopedUtfChars path_native(env, path);
724 const char* path_cstr = path_native.c_str();
725 if (!path_cstr) {
726 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
727 }
728 FileDescriptorWhitelist::Get()->Allow(path_cstr);
729}
730
doheon1.lee885b7422016-01-20 13:07:27 +0900731static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
732 // Zygote process unmount root storage space initially before every child processes are forked.
733 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400734 // and no need unmount storage operation in MountEmulatedStorage method.
735 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
736
737 // See storage config details at http://source.android.com/tech/storage/
738 // Create private mount namespace shared by all children
739 if (unshare(CLONE_NEWNS) == -1) {
740 RuntimeAbort(env, __LINE__, "Failed to unshare()");
741 return;
742 }
743
744 // Mark rootfs as being a slave so that changes from default
745 // namespace only flow into our children.
746 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
747 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
748 return;
749 }
750
751 // Create a staging tmpfs that is shared by our children; they will
752 // bind mount storage into their respective private namespaces, which
753 // are isolated from each other.
754 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
755 if (target_base != nullptr) {
756#define STRINGIFY_UID(x) __STRING(x)
757 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
758 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
759 ALOGE("Failed to mount tmpfs to %s", target_base);
760 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
761 return;
762 }
763#undef STRINGIFY_UID
764 }
doheon1.lee885b7422016-01-20 13:07:27 +0900765
766 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +0900767}
768
Daniel Micay76f6a862015-09-19 17:31:01 -0400769static const JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700770 { "nativeForkAndSpecialize",
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800771 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[ILjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +0100772 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
773 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +0900774 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -0500775 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
776 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +0900777 { "nativeUnmountStorageOnInit", "()V",
778 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit }
Narayan Kamath973b4662014-03-31 13:41:26 +0100779};
780
781int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800782 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
783 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000784 "(IZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +0100785
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800786 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +0100787}
788} // namespace android