blob: a32dbad7838ffd456c7d11a7d9d8ecfa2b849fb7 [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
Vitalii Tomkiv1e52ce42016-05-18 17:43:02 -0700158// Resets nice priority for zygote process. Zygote priority can be set
159// to high value during boot phase to speed it up. We want to ensure
160// zygote is running at normal priority before childs are forked from it.
161//
162// This ends up being called repeatedly before each fork(), but there's
163// no real harm in that.
164static void ResetNicePriority(JNIEnv* env) {
165 errno = 0;
166 int prio = getpriority(PRIO_PROCESS, 0);
167 if (prio == -1 && errno != 0) {
168 ALOGW("getpriority failed: %s\n", strerror(errno));
169 }
170 if (prio != 0 && setpriority(PRIO_PROCESS, 0, 0) != 0) {
171 ALOGE("setpriority(%d, 0, 0) failed: %s", PRIO_PROCESS, strerror(errno));
172 RuntimeAbort(env, __LINE__, "setpriority failed");
173 }
174}
175
Narayan Kamath973b4662014-03-31 13:41:26 +0100176// Sets the SIGCHLD handler back to default behavior in zygote children.
177static void UnsetSigChldHandler() {
178 struct sigaction sa;
179 memset(&sa, 0, sizeof(sa));
180 sa.sa_handler = SIG_DFL;
181
182 int err = sigaction(SIGCHLD, &sa, NULL);
183 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700184 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100185 }
186}
187
188// Calls POSIX setgroups() using the int[] object as an argument.
189// A NULL argument is tolerated.
190static void SetGids(JNIEnv* env, jintArray javaGids) {
191 if (javaGids == NULL) {
192 return;
193 }
194
195 ScopedIntArrayRO gids(env, javaGids);
196 if (gids.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800197 RuntimeAbort(env, __LINE__, "Getting gids int array failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100198 }
199 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
200 if (rc == -1) {
Narayan Kamath593aab72016-08-09 17:23:31 +0100201 std::ostringstream oss;
202 oss << "setgroups failed: " << strerror(errno) << ", gids.size=" << gids.size();
203 RuntimeAbort(env, __LINE__, oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100204 }
205}
206
207// Sets the resource limits via setrlimit(2) for the values in the
208// two-dimensional array of integers that's passed in. The second dimension
209// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
210// treated as an empty array.
211static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
212 if (javaRlimits == NULL) {
213 return;
214 }
215
216 rlimit rlim;
217 memset(&rlim, 0, sizeof(rlim));
218
219 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
220 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
221 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
222 if (javaRlimit.size() != 3) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800223 RuntimeAbort(env, __LINE__, "rlimits array must have a second dimension of size 3");
Narayan Kamath973b4662014-03-31 13:41:26 +0100224 }
225
226 rlim.rlim_cur = javaRlimit[1];
227 rlim.rlim_max = javaRlimit[2];
228
229 int rc = setrlimit(javaRlimit[0], &rlim);
230 if (rc == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800231 ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
232 rlim.rlim_max);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800233 RuntimeAbort(env, __LINE__, "setrlimit failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100234 }
235 }
236}
237
Narayan Kamath973b4662014-03-31 13:41:26 +0100238// The debug malloc library needs to know whether it's the zygote or a child.
239extern "C" int gMallocLeakZygoteChild;
240
241static void EnableKeepCapabilities(JNIEnv* env) {
242 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
243 if (rc == -1) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800244 RuntimeAbort(env, __LINE__, "prctl(PR_SET_KEEPCAPS) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100245 }
246}
247
248static void DropCapabilitiesBoundingSet(JNIEnv* env) {
249 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
250 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
251 if (rc == -1) {
252 if (errno == EINVAL) {
253 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
254 "your kernel is compiled with file capabilities support");
255 } else {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800256 RuntimeAbort(env, __LINE__, "prctl(PR_CAPBSET_DROP) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100257 }
258 }
259 }
260}
261
262static void SetCapabilities(JNIEnv* env, int64_t permitted, int64_t effective) {
263 __user_cap_header_struct capheader;
264 memset(&capheader, 0, sizeof(capheader));
265 capheader.version = _LINUX_CAPABILITY_VERSION_3;
266 capheader.pid = 0;
267
268 __user_cap_data_struct capdata[2];
269 memset(&capdata, 0, sizeof(capdata));
270 capdata[0].effective = effective;
271 capdata[1].effective = effective >> 32;
272 capdata[0].permitted = permitted;
273 capdata[1].permitted = permitted >> 32;
274
275 if (capset(&capheader, &capdata[0]) == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800276 ALOGE("capset(%" PRId64 ", %" PRId64 ") failed", permitted, effective);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800277 RuntimeAbort(env, __LINE__, "capset failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100278 }
279}
280
281static void SetSchedulerPolicy(JNIEnv* env) {
282 errno = -set_sched_policy(0, SP_DEFAULT);
283 if (errno != 0) {
284 ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
Andreas Gampeb053cce2015-11-17 16:38:59 -0800285 RuntimeAbort(env, __LINE__, "set_sched_policy(0, SP_DEFAULT) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100286 }
287}
288
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700289static int UnmountTree(const char* path) {
290 size_t path_len = strlen(path);
291
292 FILE* fp = setmntent("/proc/mounts", "r");
293 if (fp == NULL) {
294 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
295 return -errno;
296 }
297
298 // Some volumes can be stacked on each other, so force unmount in
299 // reverse order to give us the best chance of success.
300 std::list<std::string> toUnmount;
301 mntent* mentry;
302 while ((mentry = getmntent(fp)) != NULL) {
303 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
304 toUnmount.push_front(std::string(mentry->mnt_dir));
305 }
306 }
307 endmntent(fp);
308
309 for (auto path : toUnmount) {
310 if (umount2(path.c_str(), MNT_DETACH)) {
311 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
312 }
313 }
314 return 0;
315}
316
Narayan Kamath973b4662014-03-31 13:41:26 +0100317// Create a private mount namespace and bind mount appropriate emulated
318// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700319static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
320 bool force_mount_namespace) {
321 // See storage config details at http://source.android.com/tech/storage/
322
Jeff Sharkey9527b222015-06-24 15:24:48 -0700323 String8 storageSource;
324 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700325 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700326 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700327 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700328 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700329 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500330 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700331 // Sane default of no storage visible
332 return true;
333 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400334
335 // Create a second private mount namespace for our process
336 if (unshare(CLONE_NEWNS) == -1) {
337 ALOGW("Failed to unshare(): %s", strerror(errno));
338 return false;
339 }
340
Jeff Sharkey9527b222015-06-24 15:24:48 -0700341 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
342 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
343 ALOGW("Failed to mount %s to /storage: %s", storageSource.string(), strerror(errno));
344 return false;
345 }
346
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700347 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700348 userid_t user_id = multiuser_get_user_id(uid);
349 const String8 userSource(String8::format("/mnt/user/%d", user_id));
350 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
351 return false;
352 }
353 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
354 NULL, MS_BIND, NULL)) == -1) {
355 ALOGW("Failed to mount %s to /storage/self: %s", userSource.string(), strerror(errno));
356 return false;
357 }
358
Narayan Kamath973b4662014-03-31 13:41:26 +0100359 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100360}
361
Narayan Kamath973b4662014-03-31 13:41:26 +0100362static bool NeedsNoRandomizeWorkaround() {
363#if !defined(__arm__)
364 return false;
365#else
366 int major;
367 int minor;
368 struct utsname uts;
369 if (uname(&uts) == -1) {
370 return false;
371 }
372
373 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
374 return false;
375 }
376
377 // Kernels before 3.4.* need the workaround.
378 return (major < 3) || ((major == 3) && (minor < 4));
379#endif
380}
Narayan Kamath973b4662014-03-31 13:41:26 +0100381
382// Utility to close down the Zygote socket file descriptors while
383// the child is still running as root with Zygote's privileges. Each
384// descriptor (if any) is closed via dup2(), replacing it with a valid
385// (open) descriptor to /dev/null.
386
387static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
388 if (!fdsToClose) {
389 return;
390 }
391 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200392 ScopedIntArrayRO ar(env, fdsToClose);
393 if (ar.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800394 RuntimeAbort(env, __LINE__, "Bad fd array");
Narayan Kamath973b4662014-03-31 13:41:26 +0100395 }
396 jsize i;
397 int devnull;
398 for (i = 0; i < count; i++) {
399 devnull = open("/dev/null", O_RDWR);
400 if (devnull < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700401 ALOGE("Failed to open /dev/null: %s", strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800402 RuntimeAbort(env, __LINE__, "Failed to open /dev/null");
Narayan Kamath973b4662014-03-31 13:41:26 +0100403 continue;
404 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700405 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100406 if (dup2(devnull, ar[i]) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700407 ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800408 RuntimeAbort(env, __LINE__, "Failed dup2()");
Narayan Kamath973b4662014-03-31 13:41:26 +0100409 }
410 close(devnull);
411 }
412}
413
414void SetThreadName(const char* thread_name) {
415 bool hasAt = false;
416 bool hasDot = false;
417 const char* s = thread_name;
418 while (*s) {
419 if (*s == '.') {
420 hasDot = true;
421 } else if (*s == '@') {
422 hasAt = true;
423 }
424 s++;
425 }
426 const int len = s - thread_name;
427 if (len < 15 || hasAt || !hasDot) {
428 s = thread_name;
429 } else {
430 s = thread_name + len - 15;
431 }
432 // pthread_setname_np fails rather than truncating long strings.
433 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
434 strlcpy(buf, s, sizeof(buf)-1);
435 errno = pthread_setname_np(pthread_self(), buf);
436 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700437 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100438 }
439}
440
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100441// The list of open zygote file descriptors.
442static FileDescriptorTable* gOpenFdTable = NULL;
443
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800444static void FillFileDescriptorVector(JNIEnv* env,
445 jintArray java_fds,
446 std::vector<int>* fds) {
447 CHECK(fds != nullptr);
448 if (java_fds != nullptr) {
449 ScopedIntArrayRO ar(env, java_fds);
450 if (ar.get() == nullptr) {
451 RuntimeAbort(env, __LINE__, "Bad fd array");
452 }
453 fds->reserve(ar.size());
454 for (size_t i = 0; i < ar.size(); ++i) {
455 fds->push_back(ar[i]);
456 }
457 }
458}
459
Narayan Kamath973b4662014-03-31 13:41:26 +0100460// Utility routine to fork zygote and specialize the child process.
461static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
462 jint debug_flags, jobjectArray javaRlimits,
463 jlong permittedCapabilities, jlong effectiveCapabilities,
464 jint mount_external,
465 jstring java_se_info, jstring java_se_name,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700466 bool is_system_server, jintArray fdsToClose,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800467 jintArray fdsToIgnore,
jgu212eacd062014-09-10 06:55:07 -0400468 jstring instructionSet, jstring dataDir) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100469 SetSigChldHandler();
470
Narayan Kamath3764a262016-08-30 15:36:19 +0100471 // Close any logging related FDs before we start evaluating the list of
472 // file descriptors.
473 __android_log_close();
474
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100475 // If this is the first fork for this zygote, create the open FD table.
476 // If it isn't, we just need to check whether the list of open files has
477 // changed (and it shouldn't in the normal case).
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800478 std::vector<int> fds_to_ignore;
479 FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100480 if (gOpenFdTable == NULL) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800481 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100482 if (gOpenFdTable == NULL) {
483 RuntimeAbort(env, __LINE__, "Unable to construct file descriptor table.");
484 }
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800485 } else if (!gOpenFdTable->Restat(fds_to_ignore)) {
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100486 RuntimeAbort(env, __LINE__, "Unable to restat file descriptor table.");
487 }
488
Vitalii Tomkiv1e52ce42016-05-18 17:43:02 -0700489 ResetNicePriority(env);
490
Narayan Kamath973b4662014-03-31 13:41:26 +0100491 pid_t pid = fork();
492
493 if (pid == 0) {
494 // The child process.
495 gMallocLeakZygoteChild = 1;
496
497 // Clean up any descriptors which must be closed immediately
498 DetachDescriptors(env, fdsToClose);
499
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100500 // Re-open all remaining open file descriptors so that they aren't shared
501 // with the zygote across a fork.
Narayan Kamath3764a262016-08-30 15:36:19 +0100502 if (!gOpenFdTable->ReopenOrDetach()) {
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100503 RuntimeAbort(env, __LINE__, "Unable to reopen whitelisted descriptors.");
504 }
505
Narayan Kamath973b4662014-03-31 13:41:26 +0100506 // Keep capabilities across UID change, unless we're staying root.
507 if (uid != 0) {
508 EnableKeepCapabilities(env);
509 }
510
511 DropCapabilitiesBoundingSet(env);
512
Calin Juravle79ec4c12014-10-24 16:16:49 +0100513 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
514 && android::NativeBridgeAvailable();
515 if (use_native_bridge) {
jgu212eacd062014-09-10 06:55:07 -0400516 ScopedUtfChars isa_string(env, instructionSet);
Calin Juravle79ec4c12014-10-24 16:16:49 +0100517 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400518 }
Calin Juravle6a4d2362014-10-28 12:16:21 +0000519 if (use_native_bridge && dataDir == NULL) {
520 // dataDir should never be null if we need to use a native bridge.
521 // In general, dataDir will never be null for normal applications. It can only happen in
522 // special cases (for isolated processes which are not associated with any app). These are
523 // launched by the framework and should not be emulated anyway.
524 use_native_bridge = false;
525 ALOGW("Native bridge will not be used because dataDir == NULL.");
526 }
jgu212eacd062014-09-10 06:55:07 -0400527
Calin Juravle79ec4c12014-10-24 16:16:49 +0100528 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700529 ALOGW("Failed to mount emulated storage: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100530 if (errno == ENOTCONN || errno == EROFS) {
531 // When device is actively encrypting, we get ENOTCONN here
532 // since FUSE was mounted before the framework restarted.
533 // When encrypted device is booting, we get EROFS since
534 // FUSE hasn't been created yet by init.
535 // In either case, continue without external storage.
536 } else {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800537 RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage");
Narayan Kamath973b4662014-03-31 13:41:26 +0100538 }
539 }
540
Colin Cross0161bbc2014-06-03 13:26:58 -0700541 if (!is_system_server) {
542 int rc = createProcessGroup(uid, getpid());
543 if (rc != 0) {
Colin Cross3089bed2014-07-14 15:07:04 -0700544 if (rc == -EROFS) {
545 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
546 } else {
547 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
548 }
Colin Cross0161bbc2014-06-03 13:26:58 -0700549 }
550 }
551
Narayan Kamath973b4662014-03-31 13:41:26 +0100552 SetGids(env, javaGids);
553
554 SetRLimits(env, javaRlimits);
555
Calin Juravle79ec4c12014-10-24 16:16:49 +0100556 if (use_native_bridge) {
557 ScopedUtfChars isa_string(env, instructionSet);
558 ScopedUtfChars data_dir(env, dataDir);
559 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400560 }
561
Narayan Kamath973b4662014-03-31 13:41:26 +0100562 int rc = setresgid(gid, gid, gid);
563 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700564 ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800565 RuntimeAbort(env, __LINE__, "setresgid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100566 }
567
568 rc = setresuid(uid, uid, uid);
569 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700570 ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800571 RuntimeAbort(env, __LINE__, "setresuid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100572 }
573
Narayan Kamath973b4662014-03-31 13:41:26 +0100574 if (NeedsNoRandomizeWorkaround()) {
575 // Work around ARM kernel ASLR lossage (http://b/5817320).
576 int old_personality = personality(0xffffffff);
577 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
578 if (new_personality == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700579 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100580 }
581 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100582
583 SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
584
585 SetSchedulerPolicy(env);
586
Colin Cross18cd9f52014-06-13 12:58:55 -0700587 const char* se_info_c_str = NULL;
588 ScopedUtfChars* se_info = NULL;
589 if (java_se_info != NULL) {
590 se_info = new ScopedUtfChars(env, java_se_info);
591 se_info_c_str = se_info->c_str();
592 if (se_info_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800593 RuntimeAbort(env, __LINE__, "se_info_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700594 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100595 }
Colin Cross18cd9f52014-06-13 12:58:55 -0700596 const char* se_name_c_str = NULL;
597 ScopedUtfChars* se_name = NULL;
598 if (java_se_name != NULL) {
599 se_name = new ScopedUtfChars(env, java_se_name);
600 se_name_c_str = se_name->c_str();
601 if (se_name_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800602 RuntimeAbort(env, __LINE__, "se_name_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700603 }
604 }
605 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
606 if (rc == -1) {
607 ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
608 is_system_server, se_info_c_str, se_name_c_str);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800609 RuntimeAbort(env, __LINE__, "selinux_android_setcontext failed");
Colin Cross18cd9f52014-06-13 12:58:55 -0700610 }
611
612 // Make it easier to debug audit logs by setting the main thread's name to the
613 // nice name rather than "app_process".
614 if (se_info_c_str == NULL && is_system_server) {
615 se_name_c_str = "system_server";
616 }
617 if (se_info_c_str != NULL) {
618 SetThreadName(se_name_c_str);
619 }
620
621 delete se_info;
622 delete se_name;
Narayan Kamath973b4662014-03-31 13:41:26 +0100623
624 UnsetSigChldHandler();
625
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700626 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000627 is_system_server, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100628 if (env->ExceptionCheck()) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800629 RuntimeAbort(env, __LINE__, "Error calling post fork hooks.");
Narayan Kamath973b4662014-03-31 13:41:26 +0100630 }
631 } else if (pid > 0) {
632 // the parent process
633 }
634 return pid;
635}
636} // anonymous namespace
637
638namespace android {
639
640static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
641 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
642 jint debug_flags, jobjectArray rlimits,
643 jint mount_external, jstring se_info, jstring se_name,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800644 jintArray fdsToClose,
645 jintArray fdsToIgnore,
646 jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700647 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800648
649 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900650 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
651 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800652 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800653 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900654 capabilities |= (1LL << CAP_NET_RAW);
655 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800656 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700657
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800658 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
659 bool gid_wakelock_found = false;
660 if (gid == AID_WAKELOCK) {
661 gid_wakelock_found = true;
662 } else if (gids != NULL) {
663 jsize gids_num = env->GetArrayLength(gids);
664 ScopedIntArrayRO ar(env, gids);
665 if (ar.get() == NULL) {
666 RuntimeAbort(env, __LINE__, "Bad gids array");
667 }
668 for (int i = 0; i < gids_num; i++) {
669 if (ar[i] == AID_WAKELOCK) {
670 gid_wakelock_found = true;
671 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700672 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800673 }
674 }
675 if (gid_wakelock_found) {
676 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700677 }
678
Narayan Kamath973b4662014-03-31 13:41:26 +0100679 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700680 rlimits, capabilities, capabilities, mount_external, se_info,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800681 se_name, false, fdsToClose, fdsToIgnore, instructionSet, appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100682}
683
684static jint com_android_internal_os_Zygote_nativeForkSystemServer(
685 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
686 jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
687 jlong effectiveCapabilities) {
688 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
689 debug_flags, rlimits,
690 permittedCapabilities, effectiveCapabilities,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700691 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800692 NULL, NULL, NULL);
Narayan Kamath973b4662014-03-31 13:41:26 +0100693 if (pid > 0) {
694 // The zygote process checks whether the child process has died or not.
695 ALOGI("System server process %d has been created", pid);
696 gSystemServerPid = pid;
697 // There is a slight window that the system server process has crashed
698 // but it went unnoticed because we haven't published its pid yet. So
699 // we recheck here just to make sure that all is well.
700 int status;
701 if (waitpid(pid, &status, WNOHANG) == pid) {
702 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800703 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100704 }
705 }
706 return pid;
707}
708
Robert Sesek54e387d2016-12-02 17:27:50 -0500709static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
710 JNIEnv* env, jclass, jstring path) {
711 ScopedUtfChars path_native(env, path);
712 const char* path_cstr = path_native.c_str();
713 if (!path_cstr) {
714 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
715 }
716 FileDescriptorWhitelist::Get()->Allow(path_cstr);
717}
718
doheon1.lee885b7422016-01-20 13:07:27 +0900719static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
720 // Zygote process unmount root storage space initially before every child processes are forked.
721 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400722 // and no need unmount storage operation in MountEmulatedStorage method.
723 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
724
725 // See storage config details at http://source.android.com/tech/storage/
726 // Create private mount namespace shared by all children
727 if (unshare(CLONE_NEWNS) == -1) {
728 RuntimeAbort(env, __LINE__, "Failed to unshare()");
729 return;
730 }
731
732 // Mark rootfs as being a slave so that changes from default
733 // namespace only flow into our children.
734 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
735 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
736 return;
737 }
738
739 // Create a staging tmpfs that is shared by our children; they will
740 // bind mount storage into their respective private namespaces, which
741 // are isolated from each other.
742 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
743 if (target_base != nullptr) {
744#define STRINGIFY_UID(x) __STRING(x)
745 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
746 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
747 ALOGE("Failed to mount tmpfs to %s", target_base);
748 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
749 return;
750 }
751#undef STRINGIFY_UID
752 }
doheon1.lee885b7422016-01-20 13:07:27 +0900753
754 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +0900755}
756
Daniel Micay76f6a862015-09-19 17:31:01 -0400757static const JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700758 { "nativeForkAndSpecialize",
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800759 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[ILjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +0100760 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
761 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +0900762 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -0500763 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
764 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +0900765 { "nativeUnmountStorageOnInit", "()V",
766 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit }
Narayan Kamath973b4662014-03-31 13:41:26 +0100767};
768
769int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800770 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
771 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000772 "(IZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +0100773
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800774 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +0100775}
776} // namespace android