blob: 94935cc5c14420157f74bf454cfa86e81b40344a [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
46#include <cutils/fs.h>
47#include <cutils/multiuser.h>
48#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070049#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070050#include <utils/String8.h>
51#include <selinux/android.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070052#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070053
Andreas Gampeed6b9df2014-11-20 22:02:20 -080054#include "core_jni_helpers.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010055#include "JNIHelp.h"
56#include "ScopedLocalRef.h"
57#include "ScopedPrimitiveArray.h"
58#include "ScopedUtfChars.h"
Robert Sesek8225b7c2016-12-16 14:02:31 -050059#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010060
jgu212eacd062014-09-10 06:55:07 -040061#include "nativebridge/native_bridge.h"
62
Narayan Kamath973b4662014-03-31 13:41:26 +010063namespace {
64
65using android::String8;
66
67static pid_t gSystemServerPid = 0;
68
69static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
70static jclass gZygoteClass;
71static jmethodID gCallPostForkChildHooks;
72
73// Must match values in com.android.internal.os.Zygote.
74enum MountExternalKind {
75 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070076 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070077 MOUNT_EXTERNAL_READ = 2,
78 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010079};
80
Andreas Gampeb053cce2015-11-17 16:38:59 -080081static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
82 std::ostringstream oss;
83 oss << __FILE__ << ":" << line << ": " << msg;
84 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +010085}
86
87// This signal handler is for zygote mode, since the zygote must reap its children
88static void SigChldHandler(int /*signal_number*/) {
89 pid_t pid;
90 int status;
91
Christopher Ferrisa8a79542015-08-31 15:40:01 -070092 // It's necessary to save and restore the errno during this function.
93 // Since errno is stored per thread, changing it here modifies the errno
94 // on the thread on which this signal handler executes. If a signal occurs
95 // between a call and an errno check, it's possible to get the errno set
96 // here.
97 // See b/23572286 for extra information.
98 int saved_errno = errno;
99
Narayan Kamath973b4662014-03-31 13:41:26 +0100100 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
101 // Log process-death status that we care about. In general it is
102 // not safe to call LOG(...) from a signal handler because of
103 // possible reentrancy. However, we know a priori that the
104 // current implementation of LOG() is safe to call from a SIGCHLD
105 // handler in the zygote process. If the LOG() implementation
106 // changes its locking strategy or its use of syscalls within the
107 // lazy-init critical section, its use here may become unsafe.
108 if (WIFEXITED(status)) {
109 if (WEXITSTATUS(status)) {
110 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100111 }
112 } else if (WIFSIGNALED(status)) {
113 if (WTERMSIG(status) != SIGKILL) {
Narayan Kamath160992d2014-04-14 14:46:07 +0100114 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100115 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100116 if (WCOREDUMP(status)) {
117 ALOGI("Process %d dumped core.", pid);
118 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100119 }
120
121 // If the just-crashed process is the system_server, bring down zygote
122 // so that it is restarted by init and system server will be restarted
123 // from there.
124 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800125 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100126 kill(getpid(), SIGKILL);
127 }
128 }
129
Narayan Kamath160992d2014-04-14 14:46:07 +0100130 // Note that we shouldn't consider ECHILD an error because
131 // the secondary zygote might have no children left to wait for.
132 if (pid < 0 && errno != ECHILD) {
133 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100134 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700135
136 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100137}
138
139// Configures the SIGCHLD handler for the zygote process. This is configured
140// very late, because earlier in the runtime we may fork() and exec()
141// other processes, and we want to waitpid() for those rather than
142// have them be harvested immediately.
143//
144// This ends up being called repeatedly before each fork(), but there's
145// no real harm in that.
146static void SetSigChldHandler() {
147 struct sigaction sa;
148 memset(&sa, 0, sizeof(sa));
149 sa.sa_handler = SigChldHandler;
150
151 int err = sigaction(SIGCHLD, &sa, NULL);
152 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700153 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100154 }
155}
156
Vitalii Tomkiv1e52ce42016-05-18 17:43:02 -0700157// Resets nice priority for zygote process. Zygote priority can be set
158// to high value during boot phase to speed it up. We want to ensure
159// zygote is running at normal priority before childs are forked from it.
160//
161// This ends up being called repeatedly before each fork(), but there's
162// no real harm in that.
163static void ResetNicePriority(JNIEnv* env) {
164 errno = 0;
165 int prio = getpriority(PRIO_PROCESS, 0);
166 if (prio == -1 && errno != 0) {
167 ALOGW("getpriority failed: %s\n", strerror(errno));
168 }
169 if (prio != 0 && setpriority(PRIO_PROCESS, 0, 0) != 0) {
170 ALOGE("setpriority(%d, 0, 0) failed: %s", PRIO_PROCESS, strerror(errno));
171 RuntimeAbort(env, __LINE__, "setpriority failed");
172 }
173}
174
Narayan Kamath973b4662014-03-31 13:41:26 +0100175// Sets the SIGCHLD handler back to default behavior in zygote children.
176static void UnsetSigChldHandler() {
177 struct sigaction sa;
178 memset(&sa, 0, sizeof(sa));
179 sa.sa_handler = SIG_DFL;
180
181 int err = sigaction(SIGCHLD, &sa, NULL);
182 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700183 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100184 }
185}
186
187// Calls POSIX setgroups() using the int[] object as an argument.
188// A NULL argument is tolerated.
189static void SetGids(JNIEnv* env, jintArray javaGids) {
190 if (javaGids == NULL) {
191 return;
192 }
193
194 ScopedIntArrayRO gids(env, javaGids);
195 if (gids.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800196 RuntimeAbort(env, __LINE__, "Getting gids int array failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100197 }
198 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
199 if (rc == -1) {
Narayan Kamath593aab72016-08-09 17:23:31 +0100200 std::ostringstream oss;
201 oss << "setgroups failed: " << strerror(errno) << ", gids.size=" << gids.size();
202 RuntimeAbort(env, __LINE__, oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100203 }
204}
205
206// Sets the resource limits via setrlimit(2) for the values in the
207// two-dimensional array of integers that's passed in. The second dimension
208// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
209// treated as an empty array.
210static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
211 if (javaRlimits == NULL) {
212 return;
213 }
214
215 rlimit rlim;
216 memset(&rlim, 0, sizeof(rlim));
217
218 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
219 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
220 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
221 if (javaRlimit.size() != 3) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800222 RuntimeAbort(env, __LINE__, "rlimits array must have a second dimension of size 3");
Narayan Kamath973b4662014-03-31 13:41:26 +0100223 }
224
225 rlim.rlim_cur = javaRlimit[1];
226 rlim.rlim_max = javaRlimit[2];
227
228 int rc = setrlimit(javaRlimit[0], &rlim);
229 if (rc == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800230 ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
231 rlim.rlim_max);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800232 RuntimeAbort(env, __LINE__, "setrlimit failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100233 }
234 }
235}
236
Narayan Kamath973b4662014-03-31 13:41:26 +0100237// The debug malloc library needs to know whether it's the zygote or a child.
238extern "C" int gMallocLeakZygoteChild;
239
240static void EnableKeepCapabilities(JNIEnv* env) {
241 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
242 if (rc == -1) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800243 RuntimeAbort(env, __LINE__, "prctl(PR_SET_KEEPCAPS) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100244 }
245}
246
247static void DropCapabilitiesBoundingSet(JNIEnv* env) {
248 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
249 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
250 if (rc == -1) {
251 if (errno == EINVAL) {
252 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
253 "your kernel is compiled with file capabilities support");
254 } else {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800255 RuntimeAbort(env, __LINE__, "prctl(PR_CAPBSET_DROP) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100256 }
257 }
258 }
259}
260
261static void SetCapabilities(JNIEnv* env, int64_t permitted, int64_t effective) {
262 __user_cap_header_struct capheader;
263 memset(&capheader, 0, sizeof(capheader));
264 capheader.version = _LINUX_CAPABILITY_VERSION_3;
265 capheader.pid = 0;
266
267 __user_cap_data_struct capdata[2];
268 memset(&capdata, 0, sizeof(capdata));
269 capdata[0].effective = effective;
270 capdata[1].effective = effective >> 32;
271 capdata[0].permitted = permitted;
272 capdata[1].permitted = permitted >> 32;
273
274 if (capset(&capheader, &capdata[0]) == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800275 ALOGE("capset(%" PRId64 ", %" PRId64 ") failed", permitted, effective);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800276 RuntimeAbort(env, __LINE__, "capset failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100277 }
278}
279
280static void SetSchedulerPolicy(JNIEnv* env) {
281 errno = -set_sched_policy(0, SP_DEFAULT);
282 if (errno != 0) {
283 ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
Andreas Gampeb053cce2015-11-17 16:38:59 -0800284 RuntimeAbort(env, __LINE__, "set_sched_policy(0, SP_DEFAULT) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100285 }
286}
287
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700288static int UnmountTree(const char* path) {
289 size_t path_len = strlen(path);
290
291 FILE* fp = setmntent("/proc/mounts", "r");
292 if (fp == NULL) {
293 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
294 return -errno;
295 }
296
297 // Some volumes can be stacked on each other, so force unmount in
298 // reverse order to give us the best chance of success.
299 std::list<std::string> toUnmount;
300 mntent* mentry;
301 while ((mentry = getmntent(fp)) != NULL) {
302 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
303 toUnmount.push_front(std::string(mentry->mnt_dir));
304 }
305 }
306 endmntent(fp);
307
308 for (auto path : toUnmount) {
309 if (umount2(path.c_str(), MNT_DETACH)) {
310 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
311 }
312 }
313 return 0;
314}
315
Narayan Kamath973b4662014-03-31 13:41:26 +0100316// Create a private mount namespace and bind mount appropriate emulated
317// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700318static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
319 bool force_mount_namespace) {
320 // See storage config details at http://source.android.com/tech/storage/
321
Jeff Sharkey9527b222015-06-24 15:24:48 -0700322 String8 storageSource;
323 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700324 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700325 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700326 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700327 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700328 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500329 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700330 // Sane default of no storage visible
331 return true;
332 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400333
334 // Create a second private mount namespace for our process
335 if (unshare(CLONE_NEWNS) == -1) {
336 ALOGW("Failed to unshare(): %s", strerror(errno));
337 return false;
338 }
339
Jeff Sharkey9527b222015-06-24 15:24:48 -0700340 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
341 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
342 ALOGW("Failed to mount %s to /storage: %s", storageSource.string(), strerror(errno));
343 return false;
344 }
345
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700346 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700347 userid_t user_id = multiuser_get_user_id(uid);
348 const String8 userSource(String8::format("/mnt/user/%d", user_id));
349 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
350 return false;
351 }
352 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
353 NULL, MS_BIND, NULL)) == -1) {
354 ALOGW("Failed to mount %s to /storage/self: %s", userSource.string(), strerror(errno));
355 return false;
356 }
357
Narayan Kamath973b4662014-03-31 13:41:26 +0100358 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100359}
360
Narayan Kamath973b4662014-03-31 13:41:26 +0100361static bool NeedsNoRandomizeWorkaround() {
362#if !defined(__arm__)
363 return false;
364#else
365 int major;
366 int minor;
367 struct utsname uts;
368 if (uname(&uts) == -1) {
369 return false;
370 }
371
372 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
373 return false;
374 }
375
376 // Kernels before 3.4.* need the workaround.
377 return (major < 3) || ((major == 3) && (minor < 4));
378#endif
379}
Narayan Kamath973b4662014-03-31 13:41:26 +0100380
381// Utility to close down the Zygote socket file descriptors while
382// the child is still running as root with Zygote's privileges. Each
383// descriptor (if any) is closed via dup2(), replacing it with a valid
384// (open) descriptor to /dev/null.
385
386static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
387 if (!fdsToClose) {
388 return;
389 }
390 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200391 ScopedIntArrayRO ar(env, fdsToClose);
392 if (ar.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800393 RuntimeAbort(env, __LINE__, "Bad fd array");
Narayan Kamath973b4662014-03-31 13:41:26 +0100394 }
395 jsize i;
396 int devnull;
397 for (i = 0; i < count; i++) {
398 devnull = open("/dev/null", O_RDWR);
399 if (devnull < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700400 ALOGE("Failed to open /dev/null: %s", strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800401 RuntimeAbort(env, __LINE__, "Failed to open /dev/null");
Narayan Kamath973b4662014-03-31 13:41:26 +0100402 continue;
403 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700404 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100405 if (dup2(devnull, ar[i]) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700406 ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800407 RuntimeAbort(env, __LINE__, "Failed dup2()");
Narayan Kamath973b4662014-03-31 13:41:26 +0100408 }
409 close(devnull);
410 }
411}
412
413void SetThreadName(const char* thread_name) {
414 bool hasAt = false;
415 bool hasDot = false;
416 const char* s = thread_name;
417 while (*s) {
418 if (*s == '.') {
419 hasDot = true;
420 } else if (*s == '@') {
421 hasAt = true;
422 }
423 s++;
424 }
425 const int len = s - thread_name;
426 if (len < 15 || hasAt || !hasDot) {
427 s = thread_name;
428 } else {
429 s = thread_name + len - 15;
430 }
431 // pthread_setname_np fails rather than truncating long strings.
432 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
433 strlcpy(buf, s, sizeof(buf)-1);
434 errno = pthread_setname_np(pthread_self(), buf);
435 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700436 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100437 }
438}
439
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100440// The list of open zygote file descriptors.
441static FileDescriptorTable* gOpenFdTable = NULL;
442
Narayan Kamath973b4662014-03-31 13:41:26 +0100443// Utility routine to fork zygote and specialize the child process.
444static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
445 jint debug_flags, jobjectArray javaRlimits,
446 jlong permittedCapabilities, jlong effectiveCapabilities,
447 jint mount_external,
448 jstring java_se_info, jstring java_se_name,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700449 bool is_system_server, jintArray fdsToClose,
jgu212eacd062014-09-10 06:55:07 -0400450 jstring instructionSet, jstring dataDir) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100451 SetSigChldHandler();
452
Narayan Kamath3764a262016-08-30 15:36:19 +0100453 // Close any logging related FDs before we start evaluating the list of
454 // file descriptors.
455 __android_log_close();
456
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100457 // If this is the first fork for this zygote, create the open FD table.
458 // If it isn't, we just need to check whether the list of open files has
459 // changed (and it shouldn't in the normal case).
460 if (gOpenFdTable == NULL) {
461 gOpenFdTable = FileDescriptorTable::Create();
462 if (gOpenFdTable == NULL) {
463 RuntimeAbort(env, __LINE__, "Unable to construct file descriptor table.");
464 }
465 } else if (!gOpenFdTable->Restat()) {
466 RuntimeAbort(env, __LINE__, "Unable to restat file descriptor table.");
467 }
468
Vitalii Tomkiv1e52ce42016-05-18 17:43:02 -0700469 ResetNicePriority(env);
470
Narayan Kamath973b4662014-03-31 13:41:26 +0100471 pid_t pid = fork();
472
473 if (pid == 0) {
474 // The child process.
475 gMallocLeakZygoteChild = 1;
476
477 // Clean up any descriptors which must be closed immediately
478 DetachDescriptors(env, fdsToClose);
479
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100480 // Re-open all remaining open file descriptors so that they aren't shared
481 // with the zygote across a fork.
Narayan Kamath3764a262016-08-30 15:36:19 +0100482 if (!gOpenFdTable->ReopenOrDetach()) {
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100483 RuntimeAbort(env, __LINE__, "Unable to reopen whitelisted descriptors.");
484 }
485
Narayan Kamath973b4662014-03-31 13:41:26 +0100486 // Keep capabilities across UID change, unless we're staying root.
487 if (uid != 0) {
488 EnableKeepCapabilities(env);
489 }
490
491 DropCapabilitiesBoundingSet(env);
492
Calin Juravle79ec4c12014-10-24 16:16:49 +0100493 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
494 && android::NativeBridgeAvailable();
495 if (use_native_bridge) {
jgu212eacd062014-09-10 06:55:07 -0400496 ScopedUtfChars isa_string(env, instructionSet);
Calin Juravle79ec4c12014-10-24 16:16:49 +0100497 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400498 }
Calin Juravle6a4d2362014-10-28 12:16:21 +0000499 if (use_native_bridge && dataDir == NULL) {
500 // dataDir should never be null if we need to use a native bridge.
501 // In general, dataDir will never be null for normal applications. It can only happen in
502 // special cases (for isolated processes which are not associated with any app). These are
503 // launched by the framework and should not be emulated anyway.
504 use_native_bridge = false;
505 ALOGW("Native bridge will not be used because dataDir == NULL.");
506 }
jgu212eacd062014-09-10 06:55:07 -0400507
Calin Juravle79ec4c12014-10-24 16:16:49 +0100508 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700509 ALOGW("Failed to mount emulated storage: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100510 if (errno == ENOTCONN || errno == EROFS) {
511 // When device is actively encrypting, we get ENOTCONN here
512 // since FUSE was mounted before the framework restarted.
513 // When encrypted device is booting, we get EROFS since
514 // FUSE hasn't been created yet by init.
515 // In either case, continue without external storage.
516 } else {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800517 RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage");
Narayan Kamath973b4662014-03-31 13:41:26 +0100518 }
519 }
520
Colin Cross0161bbc2014-06-03 13:26:58 -0700521 if (!is_system_server) {
522 int rc = createProcessGroup(uid, getpid());
523 if (rc != 0) {
Colin Cross3089bed2014-07-14 15:07:04 -0700524 if (rc == -EROFS) {
525 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
526 } else {
527 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
528 }
Colin Cross0161bbc2014-06-03 13:26:58 -0700529 }
530 }
531
Narayan Kamath973b4662014-03-31 13:41:26 +0100532 SetGids(env, javaGids);
533
534 SetRLimits(env, javaRlimits);
535
Calin Juravle79ec4c12014-10-24 16:16:49 +0100536 if (use_native_bridge) {
537 ScopedUtfChars isa_string(env, instructionSet);
538 ScopedUtfChars data_dir(env, dataDir);
539 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400540 }
541
Narayan Kamath973b4662014-03-31 13:41:26 +0100542 int rc = setresgid(gid, gid, gid);
543 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700544 ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800545 RuntimeAbort(env, __LINE__, "setresgid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100546 }
547
548 rc = setresuid(uid, uid, uid);
549 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700550 ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800551 RuntimeAbort(env, __LINE__, "setresuid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100552 }
553
Narayan Kamath973b4662014-03-31 13:41:26 +0100554 if (NeedsNoRandomizeWorkaround()) {
555 // Work around ARM kernel ASLR lossage (http://b/5817320).
556 int old_personality = personality(0xffffffff);
557 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
558 if (new_personality == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700559 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100560 }
561 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100562
563 SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
564
565 SetSchedulerPolicy(env);
566
Colin Cross18cd9f52014-06-13 12:58:55 -0700567 const char* se_info_c_str = NULL;
568 ScopedUtfChars* se_info = NULL;
569 if (java_se_info != NULL) {
570 se_info = new ScopedUtfChars(env, java_se_info);
571 se_info_c_str = se_info->c_str();
572 if (se_info_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800573 RuntimeAbort(env, __LINE__, "se_info_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700574 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100575 }
Colin Cross18cd9f52014-06-13 12:58:55 -0700576 const char* se_name_c_str = NULL;
577 ScopedUtfChars* se_name = NULL;
578 if (java_se_name != NULL) {
579 se_name = new ScopedUtfChars(env, java_se_name);
580 se_name_c_str = se_name->c_str();
581 if (se_name_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800582 RuntimeAbort(env, __LINE__, "se_name_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700583 }
584 }
585 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
586 if (rc == -1) {
587 ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
588 is_system_server, se_info_c_str, se_name_c_str);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800589 RuntimeAbort(env, __LINE__, "selinux_android_setcontext failed");
Colin Cross18cd9f52014-06-13 12:58:55 -0700590 }
591
592 // Make it easier to debug audit logs by setting the main thread's name to the
593 // nice name rather than "app_process".
594 if (se_info_c_str == NULL && is_system_server) {
595 se_name_c_str = "system_server";
596 }
597 if (se_info_c_str != NULL) {
598 SetThreadName(se_name_c_str);
599 }
600
601 delete se_info;
602 delete se_name;
Narayan Kamath973b4662014-03-31 13:41:26 +0100603
604 UnsetSigChldHandler();
605
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700606 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000607 is_system_server, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100608 if (env->ExceptionCheck()) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800609 RuntimeAbort(env, __LINE__, "Error calling post fork hooks.");
Narayan Kamath973b4662014-03-31 13:41:26 +0100610 }
611 } else if (pid > 0) {
612 // the parent process
613 }
614 return pid;
615}
616} // anonymous namespace
617
618namespace android {
619
620static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
621 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
622 jint debug_flags, jobjectArray rlimits,
623 jint mount_external, jstring se_info, jstring se_name,
jgu212eacd062014-09-10 06:55:07 -0400624 jintArray fdsToClose, jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700625 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800626
627 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900628 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
629 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800630 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800631 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900632 capabilities |= (1LL << CAP_NET_RAW);
633 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800634 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700635
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800636 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
637 bool gid_wakelock_found = false;
638 if (gid == AID_WAKELOCK) {
639 gid_wakelock_found = true;
640 } else if (gids != NULL) {
641 jsize gids_num = env->GetArrayLength(gids);
642 ScopedIntArrayRO ar(env, gids);
643 if (ar.get() == NULL) {
644 RuntimeAbort(env, __LINE__, "Bad gids array");
645 }
646 for (int i = 0; i < gids_num; i++) {
647 if (ar[i] == AID_WAKELOCK) {
648 gid_wakelock_found = true;
649 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700650 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800651 }
652 }
653 if (gid_wakelock_found) {
654 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700655 }
656
Narayan Kamath973b4662014-03-31 13:41:26 +0100657 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700658 rlimits, capabilities, capabilities, mount_external, se_info,
Andreas Gampea103ebe2014-09-24 15:37:53 -0700659 se_name, false, fdsToClose, instructionSet, appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100660}
661
662static jint com_android_internal_os_Zygote_nativeForkSystemServer(
663 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
664 jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
665 jlong effectiveCapabilities) {
666 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
667 debug_flags, rlimits,
668 permittedCapabilities, effectiveCapabilities,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700669 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
jgu212eacd062014-09-10 06:55:07 -0400670 NULL, NULL);
Narayan Kamath973b4662014-03-31 13:41:26 +0100671 if (pid > 0) {
672 // The zygote process checks whether the child process has died or not.
673 ALOGI("System server process %d has been created", pid);
674 gSystemServerPid = pid;
675 // There is a slight window that the system server process has crashed
676 // but it went unnoticed because we haven't published its pid yet. So
677 // we recheck here just to make sure that all is well.
678 int status;
679 if (waitpid(pid, &status, WNOHANG) == pid) {
680 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800681 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100682 }
683 }
684 return pid;
685}
686
Robert Sesek54e387d2016-12-02 17:27:50 -0500687static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
688 JNIEnv* env, jclass, jstring path) {
689 ScopedUtfChars path_native(env, path);
690 const char* path_cstr = path_native.c_str();
691 if (!path_cstr) {
692 RuntimeAbort(env, __LINE__, "path_cstr == NULL");
693 }
694 FileDescriptorWhitelist::Get()->Allow(path_cstr);
695}
696
doheon1.lee885b7422016-01-20 13:07:27 +0900697static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
698 // Zygote process unmount root storage space initially before every child processes are forked.
699 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400700 // and no need unmount storage operation in MountEmulatedStorage method.
701 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
702
703 // See storage config details at http://source.android.com/tech/storage/
704 // Create private mount namespace shared by all children
705 if (unshare(CLONE_NEWNS) == -1) {
706 RuntimeAbort(env, __LINE__, "Failed to unshare()");
707 return;
708 }
709
710 // Mark rootfs as being a slave so that changes from default
711 // namespace only flow into our children.
712 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
713 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
714 return;
715 }
716
717 // Create a staging tmpfs that is shared by our children; they will
718 // bind mount storage into their respective private namespaces, which
719 // are isolated from each other.
720 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
721 if (target_base != nullptr) {
722#define STRINGIFY_UID(x) __STRING(x)
723 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
724 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
725 ALOGE("Failed to mount tmpfs to %s", target_base);
726 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
727 return;
728 }
729#undef STRINGIFY_UID
730 }
doheon1.lee885b7422016-01-20 13:07:27 +0900731
732 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +0900733}
734
Daniel Micay76f6a862015-09-19 17:31:01 -0400735static const JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700736 { "nativeForkAndSpecialize",
jgu212eacd062014-09-10 06:55:07 -0400737 "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +0100738 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
739 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +0900740 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -0500741 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
742 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +0900743 { "nativeUnmountStorageOnInit", "()V",
744 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit }
Narayan Kamath973b4662014-03-31 13:41:26 +0100745};
746
747int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800748 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
749 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000750 "(IZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +0100751
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800752 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +0100753}
754} // namespace android