blob: d73e7dd50140852fda00c7a70b80aca6816aee2f [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>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070030#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070031#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010032#include <paths.h>
33#include <signal.h>
34#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070035#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040036#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070037#include <sys/personality.h>
38#include <sys/prctl.h>
39#include <sys/resource.h>
40#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070041#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070042#include <sys/types.h>
43#include <sys/utsname.h>
44#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080045#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070046
Andreas Gampe8dfa1782017-01-05 12:45:58 -080047#include "android-base/logging.h"
Colin Cross18cd9f52014-06-13 12:58:55 -070048#include <cutils/fs.h>
49#include <cutils/multiuser.h>
50#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070051#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070052#include <utils/String8.h>
53#include <selinux/android.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070054#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070055
Andreas Gampeed6b9df2014-11-20 22:02:20 -080056#include "core_jni_helpers.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010057#include "JNIHelp.h"
58#include "ScopedLocalRef.h"
59#include "ScopedPrimitiveArray.h"
60#include "ScopedUtfChars.h"
Robert Sesek8225b7c2016-12-16 14:02:31 -050061#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010062
jgu212eacd062014-09-10 06:55:07 -040063#include "nativebridge/native_bridge.h"
64
Narayan Kamath973b4662014-03-31 13:41:26 +010065namespace {
66
67using android::String8;
68
69static pid_t gSystemServerPid = 0;
70
71static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
72static jclass gZygoteClass;
73static jmethodID gCallPostForkChildHooks;
74
75// Must match values in com.android.internal.os.Zygote.
76enum MountExternalKind {
77 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070078 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070079 MOUNT_EXTERNAL_READ = 2,
80 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010081};
82
Andreas Gampeb053cce2015-11-17 16:38:59 -080083static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
84 std::ostringstream oss;
85 oss << __FILE__ << ":" << line << ": " << msg;
86 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +010087}
88
89// This signal handler is for zygote mode, since the zygote must reap its children
90static void SigChldHandler(int /*signal_number*/) {
91 pid_t pid;
92 int status;
93
Christopher Ferrisa8a79542015-08-31 15:40:01 -070094 // It's necessary to save and restore the errno during this function.
95 // Since errno is stored per thread, changing it here modifies the errno
96 // on the thread on which this signal handler executes. If a signal occurs
97 // between a call and an errno check, it's possible to get the errno set
98 // here.
99 // See b/23572286 for extra information.
100 int saved_errno = errno;
101
Narayan Kamath973b4662014-03-31 13:41:26 +0100102 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
103 // Log process-death status that we care about. In general it is
104 // not safe to call LOG(...) from a signal handler because of
105 // possible reentrancy. However, we know a priori that the
106 // current implementation of LOG() is safe to call from a SIGCHLD
107 // handler in the zygote process. If the LOG() implementation
108 // changes its locking strategy or its use of syscalls within the
109 // lazy-init critical section, its use here may become unsafe.
110 if (WIFEXITED(status)) {
111 if (WEXITSTATUS(status)) {
112 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100113 }
114 } else if (WIFSIGNALED(status)) {
115 if (WTERMSIG(status) != SIGKILL) {
Narayan Kamath160992d2014-04-14 14:46:07 +0100116 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100117 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100118 if (WCOREDUMP(status)) {
119 ALOGI("Process %d dumped core.", pid);
120 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100121 }
122
123 // If the just-crashed process is the system_server, bring down zygote
124 // so that it is restarted by init and system server will be restarted
125 // from there.
126 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800127 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100128 kill(getpid(), SIGKILL);
129 }
130 }
131
Narayan Kamath160992d2014-04-14 14:46:07 +0100132 // Note that we shouldn't consider ECHILD an error because
133 // the secondary zygote might have no children left to wait for.
134 if (pid < 0 && errno != ECHILD) {
135 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100136 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700137
138 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100139}
140
141// Configures the SIGCHLD handler for the zygote process. This is configured
142// very late, because earlier in the runtime we may fork() and exec()
143// other processes, and we want to waitpid() for those rather than
144// have them be harvested immediately.
145//
146// This ends up being called repeatedly before each fork(), but there's
147// no real harm in that.
148static void SetSigChldHandler() {
149 struct sigaction sa;
150 memset(&sa, 0, sizeof(sa));
151 sa.sa_handler = SigChldHandler;
152
153 int err = sigaction(SIGCHLD, &sa, NULL);
154 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700155 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100156 }
157}
158
159// Sets the SIGCHLD handler back to default behavior in zygote children.
160static void UnsetSigChldHandler() {
161 struct sigaction sa;
162 memset(&sa, 0, sizeof(sa));
163 sa.sa_handler = SIG_DFL;
164
165 int err = sigaction(SIGCHLD, &sa, NULL);
166 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700167 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100168 }
169}
170
171// Calls POSIX setgroups() using the int[] object as an argument.
172// A NULL argument is tolerated.
173static void SetGids(JNIEnv* env, jintArray javaGids) {
174 if (javaGids == NULL) {
175 return;
176 }
177
178 ScopedIntArrayRO gids(env, javaGids);
179 if (gids.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800180 RuntimeAbort(env, __LINE__, "Getting gids int array failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100181 }
182 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
183 if (rc == -1) {
Narayan Kamath593aab72016-08-09 17:23:31 +0100184 std::ostringstream oss;
185 oss << "setgroups failed: " << strerror(errno) << ", gids.size=" << gids.size();
186 RuntimeAbort(env, __LINE__, oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100187 }
188}
189
190// Sets the resource limits via setrlimit(2) for the values in the
191// two-dimensional array of integers that's passed in. The second dimension
192// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
193// treated as an empty array.
194static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
195 if (javaRlimits == NULL) {
196 return;
197 }
198
199 rlimit rlim;
200 memset(&rlim, 0, sizeof(rlim));
201
202 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
203 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
204 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
205 if (javaRlimit.size() != 3) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800206 RuntimeAbort(env, __LINE__, "rlimits array must have a second dimension of size 3");
Narayan Kamath973b4662014-03-31 13:41:26 +0100207 }
208
209 rlim.rlim_cur = javaRlimit[1];
210 rlim.rlim_max = javaRlimit[2];
211
212 int rc = setrlimit(javaRlimit[0], &rlim);
213 if (rc == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800214 ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
215 rlim.rlim_max);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800216 RuntimeAbort(env, __LINE__, "setrlimit failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100217 }
218 }
219}
220
Narayan Kamath973b4662014-03-31 13:41:26 +0100221// The debug malloc library needs to know whether it's the zygote or a child.
222extern "C" int gMallocLeakZygoteChild;
223
224static void EnableKeepCapabilities(JNIEnv* env) {
225 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
226 if (rc == -1) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800227 RuntimeAbort(env, __LINE__, "prctl(PR_SET_KEEPCAPS) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100228 }
229}
230
231static void DropCapabilitiesBoundingSet(JNIEnv* env) {
232 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
233 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
234 if (rc == -1) {
235 if (errno == EINVAL) {
236 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
237 "your kernel is compiled with file capabilities support");
238 } else {
Josh Gao45dab782017-02-01 14:56:09 -0800239 ALOGE("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800240 RuntimeAbort(env, __LINE__, "prctl(PR_CAPBSET_DROP) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100241 }
242 }
243 }
244}
245
Josh Gao45dab782017-02-01 14:56:09 -0800246static void SetInheritable(JNIEnv* env, uint64_t inheritable) {
247 __user_cap_header_struct capheader;
248 memset(&capheader, 0, sizeof(capheader));
249 capheader.version = _LINUX_CAPABILITY_VERSION_3;
250 capheader.pid = 0;
251
252 __user_cap_data_struct capdata[2];
253 if (capget(&capheader, &capdata[0]) == -1) {
254 ALOGE("capget failed: %s", strerror(errno));
255 RuntimeAbort(env, __LINE__, "capget failed");
256 }
257
258 capdata[0].inheritable = inheritable;
259 capdata[1].inheritable = inheritable >> 32;
260
261 if (capset(&capheader, &capdata[0]) == -1) {
262 ALOGE("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
263 RuntimeAbort(env, __LINE__, "capset failed");
264 }
265}
266
267static void SetCapabilities(JNIEnv* env, uint64_t permitted, uint64_t effective,
268 uint64_t inheritable) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100269 __user_cap_header_struct capheader;
270 memset(&capheader, 0, sizeof(capheader));
271 capheader.version = _LINUX_CAPABILITY_VERSION_3;
272 capheader.pid = 0;
273
274 __user_cap_data_struct capdata[2];
275 memset(&capdata, 0, sizeof(capdata));
276 capdata[0].effective = effective;
277 capdata[1].effective = effective >> 32;
278 capdata[0].permitted = permitted;
279 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800280 capdata[0].inheritable = inheritable;
281 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100282
283 if (capset(&capheader, &capdata[0]) == -1) {
Josh Gao45dab782017-02-01 14:56:09 -0800284 ALOGE("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") failed: %s", permitted,
285 effective, inheritable, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800286 RuntimeAbort(env, __LINE__, "capset failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100287 }
288}
289
290static void SetSchedulerPolicy(JNIEnv* env) {
291 errno = -set_sched_policy(0, SP_DEFAULT);
292 if (errno != 0) {
293 ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
Andreas Gampeb053cce2015-11-17 16:38:59 -0800294 RuntimeAbort(env, __LINE__, "set_sched_policy(0, SP_DEFAULT) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100295 }
296}
297
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700298static int UnmountTree(const char* path) {
299 size_t path_len = strlen(path);
300
301 FILE* fp = setmntent("/proc/mounts", "r");
302 if (fp == NULL) {
303 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
304 return -errno;
305 }
306
307 // Some volumes can be stacked on each other, so force unmount in
308 // reverse order to give us the best chance of success.
309 std::list<std::string> toUnmount;
310 mntent* mentry;
311 while ((mentry = getmntent(fp)) != NULL) {
312 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
313 toUnmount.push_front(std::string(mentry->mnt_dir));
314 }
315 }
316 endmntent(fp);
317
318 for (auto path : toUnmount) {
319 if (umount2(path.c_str(), MNT_DETACH)) {
320 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
321 }
322 }
323 return 0;
324}
325
Narayan Kamath973b4662014-03-31 13:41:26 +0100326// Create a private mount namespace and bind mount appropriate emulated
327// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700328static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
329 bool force_mount_namespace) {
330 // See storage config details at http://source.android.com/tech/storage/
331
Jeff Sharkey9527b222015-06-24 15:24:48 -0700332 String8 storageSource;
333 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700334 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700335 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700336 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700337 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700338 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500339 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700340 // Sane default of no storage visible
341 return true;
342 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400343
344 // Create a second private mount namespace for our process
345 if (unshare(CLONE_NEWNS) == -1) {
346 ALOGW("Failed to unshare(): %s", strerror(errno));
347 return false;
348 }
349
Robert Sesek06f39302017-03-20 17:30:05 -0400350 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
351 if (mount_mode == MOUNT_EXTERNAL_NONE) {
352 return true;
353 }
354
Jeff Sharkey9527b222015-06-24 15:24:48 -0700355 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
356 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
357 ALOGW("Failed to mount %s to /storage: %s", storageSource.string(), strerror(errno));
358 return false;
359 }
360
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700361 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700362 userid_t user_id = multiuser_get_user_id(uid);
363 const String8 userSource(String8::format("/mnt/user/%d", user_id));
364 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
365 return false;
366 }
367 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
368 NULL, MS_BIND, NULL)) == -1) {
369 ALOGW("Failed to mount %s to /storage/self: %s", userSource.string(), strerror(errno));
370 return false;
371 }
372
Narayan Kamath973b4662014-03-31 13:41:26 +0100373 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100374}
375
Narayan Kamath973b4662014-03-31 13:41:26 +0100376static bool NeedsNoRandomizeWorkaround() {
377#if !defined(__arm__)
378 return false;
379#else
380 int major;
381 int minor;
382 struct utsname uts;
383 if (uname(&uts) == -1) {
384 return false;
385 }
386
387 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
388 return false;
389 }
390
391 // Kernels before 3.4.* need the workaround.
392 return (major < 3) || ((major == 3) && (minor < 4));
393#endif
394}
Narayan Kamath973b4662014-03-31 13:41:26 +0100395
396// Utility to close down the Zygote socket file descriptors while
397// the child is still running as root with Zygote's privileges. Each
398// descriptor (if any) is closed via dup2(), replacing it with a valid
399// (open) descriptor to /dev/null.
400
401static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
402 if (!fdsToClose) {
403 return;
404 }
405 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200406 ScopedIntArrayRO ar(env, fdsToClose);
407 if (ar.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800408 RuntimeAbort(env, __LINE__, "Bad fd array");
Narayan Kamath973b4662014-03-31 13:41:26 +0100409 }
410 jsize i;
411 int devnull;
412 for (i = 0; i < count; i++) {
413 devnull = open("/dev/null", O_RDWR);
414 if (devnull < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700415 ALOGE("Failed to open /dev/null: %s", strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800416 RuntimeAbort(env, __LINE__, "Failed to open /dev/null");
Narayan Kamath973b4662014-03-31 13:41:26 +0100417 continue;
418 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700419 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100420 if (dup2(devnull, ar[i]) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700421 ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800422 RuntimeAbort(env, __LINE__, "Failed dup2()");
Narayan Kamath973b4662014-03-31 13:41:26 +0100423 }
424 close(devnull);
425 }
426}
427
428void SetThreadName(const char* thread_name) {
429 bool hasAt = false;
430 bool hasDot = false;
431 const char* s = thread_name;
432 while (*s) {
433 if (*s == '.') {
434 hasDot = true;
435 } else if (*s == '@') {
436 hasAt = true;
437 }
438 s++;
439 }
440 const int len = s - thread_name;
441 if (len < 15 || hasAt || !hasDot) {
442 s = thread_name;
443 } else {
444 s = thread_name + len - 15;
445 }
446 // pthread_setname_np fails rather than truncating long strings.
447 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
448 strlcpy(buf, s, sizeof(buf)-1);
449 errno = pthread_setname_np(pthread_self(), buf);
450 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700451 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100452 }
453}
454
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100455// The list of open zygote file descriptors.
456static FileDescriptorTable* gOpenFdTable = NULL;
457
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800458static void FillFileDescriptorVector(JNIEnv* env,
459 jintArray java_fds,
460 std::vector<int>* fds) {
461 CHECK(fds != nullptr);
462 if (java_fds != nullptr) {
463 ScopedIntArrayRO ar(env, java_fds);
464 if (ar.get() == nullptr) {
465 RuntimeAbort(env, __LINE__, "Bad fd array");
466 }
467 fds->reserve(ar.size());
468 for (size_t i = 0; i < ar.size(); ++i) {
469 fds->push_back(ar[i]);
470 }
471 }
472}
473
Narayan Kamath973b4662014-03-31 13:41:26 +0100474// Utility routine to fork zygote and specialize the child process.
475static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
476 jint debug_flags, jobjectArray javaRlimits,
477 jlong permittedCapabilities, jlong effectiveCapabilities,
478 jint mount_external,
479 jstring java_se_info, jstring java_se_name,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700480 bool is_system_server, jintArray fdsToClose,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800481 jintArray fdsToIgnore,
jgu212eacd062014-09-10 06:55:07 -0400482 jstring instructionSet, jstring dataDir) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100483 SetSigChldHandler();
484
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000485 sigset_t sigchld;
486 sigemptyset(&sigchld);
487 sigaddset(&sigchld, SIGCHLD);
488
489 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
490 // log, which would result in the logging FDs we close being reopened.
491 // This would cause failures because the FDs are not whitelisted.
492 //
493 // Note that the zygote process is single threaded at this point.
494 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
495 ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
496 RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_BLOCK, { SIGCHLD }) failed.");
497 }
498
Narayan Kamath3764a262016-08-30 15:36:19 +0100499 // Close any logging related FDs before we start evaluating the list of
500 // file descriptors.
501 __android_log_close();
502
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100503 // If this is the first fork for this zygote, create the open FD table.
504 // If it isn't, we just need to check whether the list of open files has
505 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800506 std::vector<int> fds_to_ignore;
507 FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100508 if (gOpenFdTable == NULL) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800509 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100510 if (gOpenFdTable == NULL) {
511 RuntimeAbort(env, __LINE__, "Unable to construct file descriptor table.");
512 }
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800513 } else if (!gOpenFdTable->Restat(fds_to_ignore)) {
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100514 RuntimeAbort(env, __LINE__, "Unable to restat file descriptor table.");
515 }
516
Narayan Kamath973b4662014-03-31 13:41:26 +0100517 pid_t pid = fork();
518
519 if (pid == 0) {
520 // The child process.
521 gMallocLeakZygoteChild = 1;
522
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700523 // Set the jemalloc decay time to 1.
524 mallopt(M_DECAY_TIME, 1);
525
Narayan Kamath973b4662014-03-31 13:41:26 +0100526 // Clean up any descriptors which must be closed immediately
527 DetachDescriptors(env, fdsToClose);
528
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100529 // Re-open all remaining open file descriptors so that they aren't shared
530 // with the zygote across a fork.
Narayan Kamath3764a262016-08-30 15:36:19 +0100531 if (!gOpenFdTable->ReopenOrDetach()) {
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100532 RuntimeAbort(env, __LINE__, "Unable to reopen whitelisted descriptors.");
533 }
534
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000535 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
536 ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
537 RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed.");
538 }
539
Narayan Kamath973b4662014-03-31 13:41:26 +0100540 // Keep capabilities across UID change, unless we're staying root.
541 if (uid != 0) {
542 EnableKeepCapabilities(env);
543 }
544
Josh Gao45dab782017-02-01 14:56:09 -0800545 SetInheritable(env, permittedCapabilities);
Narayan Kamath973b4662014-03-31 13:41:26 +0100546 DropCapabilitiesBoundingSet(env);
547
Calin Juravle79ec4c12014-10-24 16:16:49 +0100548 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
549 && android::NativeBridgeAvailable();
550 if (use_native_bridge) {
jgu212eacd062014-09-10 06:55:07 -0400551 ScopedUtfChars isa_string(env, instructionSet);
Calin Juravle79ec4c12014-10-24 16:16:49 +0100552 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400553 }
Calin Juravle6a4d2362014-10-28 12:16:21 +0000554 if (use_native_bridge && dataDir == NULL) {
555 // dataDir should never be null if we need to use a native bridge.
556 // In general, dataDir will never be null for normal applications. It can only happen in
557 // special cases (for isolated processes which are not associated with any app). These are
558 // launched by the framework and should not be emulated anyway.
559 use_native_bridge = false;
560 ALOGW("Native bridge will not be used because dataDir == NULL.");
561 }
jgu212eacd062014-09-10 06:55:07 -0400562
Calin Juravle79ec4c12014-10-24 16:16:49 +0100563 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700564 ALOGW("Failed to mount emulated storage: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100565 if (errno == ENOTCONN || errno == EROFS) {
566 // When device is actively encrypting, we get ENOTCONN here
567 // since FUSE was mounted before the framework restarted.
568 // When encrypted device is booting, we get EROFS since
569 // FUSE hasn't been created yet by init.
570 // In either case, continue without external storage.
571 } else {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800572 RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage");
Narayan Kamath973b4662014-03-31 13:41:26 +0100573 }
574 }
575
Colin Cross0161bbc2014-06-03 13:26:58 -0700576 if (!is_system_server) {
577 int rc = createProcessGroup(uid, getpid());
578 if (rc != 0) {
Colin Cross3089bed2014-07-14 15:07:04 -0700579 if (rc == -EROFS) {
580 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
581 } else {
582 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
583 }
Colin Cross0161bbc2014-06-03 13:26:58 -0700584 }
585 }
586
Narayan Kamath973b4662014-03-31 13:41:26 +0100587 SetGids(env, javaGids);
588
589 SetRLimits(env, javaRlimits);
590
Calin Juravle79ec4c12014-10-24 16:16:49 +0100591 if (use_native_bridge) {
592 ScopedUtfChars isa_string(env, instructionSet);
593 ScopedUtfChars data_dir(env, dataDir);
594 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400595 }
596
Narayan Kamath973b4662014-03-31 13:41:26 +0100597 int rc = setresgid(gid, gid, gid);
598 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700599 ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800600 RuntimeAbort(env, __LINE__, "setresgid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100601 }
602
603 rc = setresuid(uid, uid, uid);
604 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700605 ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800606 RuntimeAbort(env, __LINE__, "setresuid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100607 }
608
Narayan Kamath973b4662014-03-31 13:41:26 +0100609 if (NeedsNoRandomizeWorkaround()) {
610 // Work around ARM kernel ASLR lossage (http://b/5817320).
611 int old_personality = personality(0xffffffff);
612 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
613 if (new_personality == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700614 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100615 }
616 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100617
Josh Gao45dab782017-02-01 14:56:09 -0800618 SetCapabilities(env, permittedCapabilities, effectiveCapabilities, permittedCapabilities);
Narayan Kamath973b4662014-03-31 13:41:26 +0100619
620 SetSchedulerPolicy(env);
621
Colin Cross18cd9f52014-06-13 12:58:55 -0700622 const char* se_info_c_str = NULL;
623 ScopedUtfChars* se_info = NULL;
624 if (java_se_info != NULL) {
625 se_info = new ScopedUtfChars(env, java_se_info);
626 se_info_c_str = se_info->c_str();
627 if (se_info_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800628 RuntimeAbort(env, __LINE__, "se_info_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700629 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100630 }
Colin Cross18cd9f52014-06-13 12:58:55 -0700631 const char* se_name_c_str = NULL;
632 ScopedUtfChars* se_name = NULL;
633 if (java_se_name != NULL) {
634 se_name = new ScopedUtfChars(env, java_se_name);
635 se_name_c_str = se_name->c_str();
636 if (se_name_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800637 RuntimeAbort(env, __LINE__, "se_name_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700638 }
639 }
640 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
641 if (rc == -1) {
642 ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
643 is_system_server, se_info_c_str, se_name_c_str);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800644 RuntimeAbort(env, __LINE__, "selinux_android_setcontext failed");
Colin Cross18cd9f52014-06-13 12:58:55 -0700645 }
646
647 // Make it easier to debug audit logs by setting the main thread's name to the
648 // nice name rather than "app_process".
649 if (se_info_c_str == NULL && is_system_server) {
650 se_name_c_str = "system_server";
651 }
652 if (se_info_c_str != NULL) {
653 SetThreadName(se_name_c_str);
654 }
655
656 delete se_info;
657 delete se_name;
Narayan Kamath973b4662014-03-31 13:41:26 +0100658
659 UnsetSigChldHandler();
660
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700661 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000662 is_system_server, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100663 if (env->ExceptionCheck()) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800664 RuntimeAbort(env, __LINE__, "Error calling post fork hooks.");
Narayan Kamath973b4662014-03-31 13:41:26 +0100665 }
666 } else if (pid > 0) {
667 // the parent process
Tim Murray6d43a8612015-08-05 14:31:05 -0700668
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000669 // We blocked SIGCHLD prior to a fork, we unblock it here.
670 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
671 ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
672 RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed.");
673 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100674 }
675 return pid;
676}
677} // anonymous namespace
678
679namespace android {
680
681static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
682 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
683 jint debug_flags, jobjectArray rlimits,
684 jint mount_external, jstring se_info, jstring se_name,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800685 jintArray fdsToClose,
686 jintArray fdsToIgnore,
687 jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700688 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800689
690 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900691 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
Philip Cuadra0fabba32017-04-26 13:49:37 -0700692 // Grant CAP_SYS_NICE to allow Bluetooth to set RT priority for
693 // audio-related threads.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900694 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800695 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800696 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900697 capabilities |= (1LL << CAP_NET_RAW);
698 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Philip Cuadra0fabba32017-04-26 13:49:37 -0700699 capabilities |= (1LL << CAP_SYS_NICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800700 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700701
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800702 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
703 bool gid_wakelock_found = false;
704 if (gid == AID_WAKELOCK) {
705 gid_wakelock_found = true;
706 } else if (gids != NULL) {
707 jsize gids_num = env->GetArrayLength(gids);
708 ScopedIntArrayRO ar(env, gids);
709 if (ar.get() == NULL) {
710 RuntimeAbort(env, __LINE__, "Bad gids array");
711 }
712 for (int i = 0; i < gids_num; i++) {
713 if (ar[i] == AID_WAKELOCK) {
714 gid_wakelock_found = true;
715 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700716 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800717 }
718 }
719 if (gid_wakelock_found) {
720 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700721 }
722
Narayan Kamath973b4662014-03-31 13:41:26 +0100723 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700724 rlimits, capabilities, capabilities, mount_external, se_info,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800725 se_name, false, fdsToClose, fdsToIgnore, instructionSet, appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100726}
727
728static jint com_android_internal_os_Zygote_nativeForkSystemServer(
729 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
730 jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
731 jlong effectiveCapabilities) {
732 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
733 debug_flags, rlimits,
734 permittedCapabilities, effectiveCapabilities,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700735 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800736 NULL, NULL, NULL);
Narayan Kamath973b4662014-03-31 13:41:26 +0100737 if (pid > 0) {
738 // The zygote process checks whether the child process has died or not.
739 ALOGI("System server process %d has been created", pid);
740 gSystemServerPid = pid;
741 // There is a slight window that the system server process has crashed
742 // but it went unnoticed because we haven't published its pid yet. So
743 // we recheck here just to make sure that all is well.
744 int status;
745 if (waitpid(pid, &status, WNOHANG) == pid) {
746 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800747 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100748 }
749 }
750 return pid;
751}
752
Robert Sesek54e387d2016-12-02 17:27:50 -0500753static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
754 JNIEnv* env, jclass, jstring path) {
755 ScopedUtfChars path_native(env, path);
756 const char* path_cstr = path_native.c_str();
757 if (!path_cstr) {
758 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
759 }
760 FileDescriptorWhitelist::Get()->Allow(path_cstr);
761}
762
doheon1.lee885b7422016-01-20 13:07:27 +0900763static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
764 // Zygote process unmount root storage space initially before every child processes are forked.
765 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400766 // and no need unmount storage operation in MountEmulatedStorage method.
767 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
768
769 // See storage config details at http://source.android.com/tech/storage/
770 // Create private mount namespace shared by all children
771 if (unshare(CLONE_NEWNS) == -1) {
772 RuntimeAbort(env, __LINE__, "Failed to unshare()");
773 return;
774 }
775
776 // Mark rootfs as being a slave so that changes from default
777 // namespace only flow into our children.
778 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
779 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
780 return;
781 }
782
783 // Create a staging tmpfs that is shared by our children; they will
784 // bind mount storage into their respective private namespaces, which
785 // are isolated from each other.
786 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
787 if (target_base != nullptr) {
788#define STRINGIFY_UID(x) __STRING(x)
789 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
790 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
791 ALOGE("Failed to mount tmpfs to %s", target_base);
792 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
793 return;
794 }
795#undef STRINGIFY_UID
796 }
doheon1.lee885b7422016-01-20 13:07:27 +0900797
798 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +0900799}
800
Daniel Micay76f6a862015-09-19 17:31:01 -0400801static const JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700802 { "nativeForkAndSpecialize",
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800803 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[ILjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +0100804 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
805 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +0900806 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -0500807 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
808 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +0900809 { "nativeUnmountStorageOnInit", "()V",
810 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit }
Narayan Kamath973b4662014-03-31 13:41:26 +0100811};
812
813int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800814 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
815 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000816 "(IZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +0100817
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800818 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +0100819}
820} // namespace android