blob: 3e111c01c1dac318c296476e0cc841a9bbd3b206 [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>
40#include <sys/types.h>
41#include <sys/utsname.h>
42#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080043#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070044
45#include <cutils/fs.h>
46#include <cutils/multiuser.h>
47#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070048#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070049#include <utils/String8.h>
50#include <selinux/android.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070051#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070052
Andreas Gampeed6b9df2014-11-20 22:02:20 -080053#include "core_jni_helpers.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010054#include "JNIHelp.h"
55#include "ScopedLocalRef.h"
56#include "ScopedPrimitiveArray.h"
57#include "ScopedUtfChars.h"
58
jgu212eacd062014-09-10 06:55:07 -040059#include "nativebridge/native_bridge.h"
60
Narayan Kamath973b4662014-03-31 13:41:26 +010061namespace {
62
63using android::String8;
64
65static pid_t gSystemServerPid = 0;
66
67static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
68static jclass gZygoteClass;
69static jmethodID gCallPostForkChildHooks;
70
71// Must match values in com.android.internal.os.Zygote.
72enum MountExternalKind {
73 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070074 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070075 MOUNT_EXTERNAL_READ = 2,
76 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010077};
78
Andreas Gampeb053cce2015-11-17 16:38:59 -080079static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
80 std::ostringstream oss;
81 oss << __FILE__ << ":" << line << ": " << msg;
82 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +010083}
84
85// This signal handler is for zygote mode, since the zygote must reap its children
86static void SigChldHandler(int /*signal_number*/) {
87 pid_t pid;
88 int status;
89
Christopher Ferrisa8a79542015-08-31 15:40:01 -070090 // It's necessary to save and restore the errno during this function.
91 // Since errno is stored per thread, changing it here modifies the errno
92 // on the thread on which this signal handler executes. If a signal occurs
93 // between a call and an errno check, it's possible to get the errno set
94 // here.
95 // See b/23572286 for extra information.
96 int saved_errno = errno;
97
Narayan Kamath973b4662014-03-31 13:41:26 +010098 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
99 // Log process-death status that we care about. In general it is
100 // not safe to call LOG(...) from a signal handler because of
101 // possible reentrancy. However, we know a priori that the
102 // current implementation of LOG() is safe to call from a SIGCHLD
103 // handler in the zygote process. If the LOG() implementation
104 // changes its locking strategy or its use of syscalls within the
105 // lazy-init critical section, its use here may become unsafe.
106 if (WIFEXITED(status)) {
107 if (WEXITSTATUS(status)) {
108 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100109 }
110 } else if (WIFSIGNALED(status)) {
111 if (WTERMSIG(status) != SIGKILL) {
Narayan Kamath160992d2014-04-14 14:46:07 +0100112 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100113 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100114 if (WCOREDUMP(status)) {
115 ALOGI("Process %d dumped core.", pid);
116 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100117 }
118
119 // If the just-crashed process is the system_server, bring down zygote
120 // so that it is restarted by init and system server will be restarted
121 // from there.
122 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800123 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100124 kill(getpid(), SIGKILL);
125 }
126 }
127
Narayan Kamath160992d2014-04-14 14:46:07 +0100128 // Note that we shouldn't consider ECHILD an error because
129 // the secondary zygote might have no children left to wait for.
130 if (pid < 0 && errno != ECHILD) {
131 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100132 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700133
134 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100135}
136
137// Configures the SIGCHLD handler for the zygote process. This is configured
138// very late, because earlier in the runtime we may fork() and exec()
139// other processes, and we want to waitpid() for those rather than
140// have them be harvested immediately.
141//
142// This ends up being called repeatedly before each fork(), but there's
143// no real harm in that.
144static void SetSigChldHandler() {
145 struct sigaction sa;
146 memset(&sa, 0, sizeof(sa));
147 sa.sa_handler = SigChldHandler;
148
149 int err = sigaction(SIGCHLD, &sa, NULL);
150 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700151 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100152 }
153}
154
155// Sets the SIGCHLD handler back to default behavior in zygote children.
156static void UnsetSigChldHandler() {
157 struct sigaction sa;
158 memset(&sa, 0, sizeof(sa));
159 sa.sa_handler = SIG_DFL;
160
161 int err = sigaction(SIGCHLD, &sa, NULL);
162 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700163 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100164 }
165}
166
167// Calls POSIX setgroups() using the int[] object as an argument.
168// A NULL argument is tolerated.
169static void SetGids(JNIEnv* env, jintArray javaGids) {
170 if (javaGids == NULL) {
171 return;
172 }
173
174 ScopedIntArrayRO gids(env, javaGids);
175 if (gids.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800176 RuntimeAbort(env, __LINE__, "Getting gids int array failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100177 }
178 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
179 if (rc == -1) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800180 RuntimeAbort(env, __LINE__, "setgroups failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100181 }
182}
183
184// Sets the resource limits via setrlimit(2) for the values in the
185// two-dimensional array of integers that's passed in. The second dimension
186// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
187// treated as an empty array.
188static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
189 if (javaRlimits == NULL) {
190 return;
191 }
192
193 rlimit rlim;
194 memset(&rlim, 0, sizeof(rlim));
195
196 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
197 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
198 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
199 if (javaRlimit.size() != 3) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800200 RuntimeAbort(env, __LINE__, "rlimits array must have a second dimension of size 3");
Narayan Kamath973b4662014-03-31 13:41:26 +0100201 }
202
203 rlim.rlim_cur = javaRlimit[1];
204 rlim.rlim_max = javaRlimit[2];
205
206 int rc = setrlimit(javaRlimit[0], &rlim);
207 if (rc == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800208 ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
209 rlim.rlim_max);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800210 RuntimeAbort(env, __LINE__, "setrlimit failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100211 }
212 }
213}
214
Narayan Kamath973b4662014-03-31 13:41:26 +0100215// The debug malloc library needs to know whether it's the zygote or a child.
216extern "C" int gMallocLeakZygoteChild;
217
218static void EnableKeepCapabilities(JNIEnv* env) {
219 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
220 if (rc == -1) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800221 RuntimeAbort(env, __LINE__, "prctl(PR_SET_KEEPCAPS) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100222 }
223}
224
225static void DropCapabilitiesBoundingSet(JNIEnv* env) {
226 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
227 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
228 if (rc == -1) {
229 if (errno == EINVAL) {
230 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
231 "your kernel is compiled with file capabilities support");
232 } else {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800233 RuntimeAbort(env, __LINE__, "prctl(PR_CAPBSET_DROP) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100234 }
235 }
236 }
237}
238
239static void SetCapabilities(JNIEnv* env, int64_t permitted, int64_t effective) {
240 __user_cap_header_struct capheader;
241 memset(&capheader, 0, sizeof(capheader));
242 capheader.version = _LINUX_CAPABILITY_VERSION_3;
243 capheader.pid = 0;
244
245 __user_cap_data_struct capdata[2];
246 memset(&capdata, 0, sizeof(capdata));
247 capdata[0].effective = effective;
248 capdata[1].effective = effective >> 32;
249 capdata[0].permitted = permitted;
250 capdata[1].permitted = permitted >> 32;
251
252 if (capset(&capheader, &capdata[0]) == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800253 ALOGE("capset(%" PRId64 ", %" PRId64 ") failed", permitted, effective);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800254 RuntimeAbort(env, __LINE__, "capset failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100255 }
256}
257
258static void SetSchedulerPolicy(JNIEnv* env) {
259 errno = -set_sched_policy(0, SP_DEFAULT);
260 if (errno != 0) {
261 ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
Andreas Gampeb053cce2015-11-17 16:38:59 -0800262 RuntimeAbort(env, __LINE__, "set_sched_policy(0, SP_DEFAULT) failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100263 }
264}
265
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700266static int UnmountTree(const char* path) {
267 size_t path_len = strlen(path);
268
269 FILE* fp = setmntent("/proc/mounts", "r");
270 if (fp == NULL) {
271 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
272 return -errno;
273 }
274
275 // Some volumes can be stacked on each other, so force unmount in
276 // reverse order to give us the best chance of success.
277 std::list<std::string> toUnmount;
278 mntent* mentry;
279 while ((mentry = getmntent(fp)) != NULL) {
280 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
281 toUnmount.push_front(std::string(mentry->mnt_dir));
282 }
283 }
284 endmntent(fp);
285
286 for (auto path : toUnmount) {
287 if (umount2(path.c_str(), MNT_DETACH)) {
288 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
289 }
290 }
291 return 0;
292}
293
Narayan Kamath973b4662014-03-31 13:41:26 +0100294// Create a private mount namespace and bind mount appropriate emulated
295// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700296static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
297 bool force_mount_namespace) {
298 // See storage config details at http://source.android.com/tech/storage/
299
Jeff Sharkey9527b222015-06-24 15:24:48 -0700300 String8 storageSource;
301 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700302 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700303 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700304 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700305 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700306 storageSource = "/mnt/runtime/write";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700307 } else {
308 // Sane default of no storage visible
309 return true;
310 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400311
312 // Create a second private mount namespace for our process
313 if (unshare(CLONE_NEWNS) == -1) {
314 ALOGW("Failed to unshare(): %s", strerror(errno));
315 return false;
316 }
317
Jeff Sharkey9527b222015-06-24 15:24:48 -0700318 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
319 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
320 ALOGW("Failed to mount %s to /storage: %s", storageSource.string(), strerror(errno));
321 return false;
322 }
323
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700324 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700325 userid_t user_id = multiuser_get_user_id(uid);
326 const String8 userSource(String8::format("/mnt/user/%d", user_id));
327 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
328 return false;
329 }
330 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
331 NULL, MS_BIND, NULL)) == -1) {
332 ALOGW("Failed to mount %s to /storage/self: %s", userSource.string(), strerror(errno));
333 return false;
334 }
335
Narayan Kamath973b4662014-03-31 13:41:26 +0100336 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100337}
338
Narayan Kamath973b4662014-03-31 13:41:26 +0100339static bool NeedsNoRandomizeWorkaround() {
340#if !defined(__arm__)
341 return false;
342#else
343 int major;
344 int minor;
345 struct utsname uts;
346 if (uname(&uts) == -1) {
347 return false;
348 }
349
350 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
351 return false;
352 }
353
354 // Kernels before 3.4.* need the workaround.
355 return (major < 3) || ((major == 3) && (minor < 4));
356#endif
357}
Narayan Kamath973b4662014-03-31 13:41:26 +0100358
359// Utility to close down the Zygote socket file descriptors while
360// the child is still running as root with Zygote's privileges. Each
361// descriptor (if any) is closed via dup2(), replacing it with a valid
362// (open) descriptor to /dev/null.
363
364static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
365 if (!fdsToClose) {
366 return;
367 }
368 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200369 ScopedIntArrayRO ar(env, fdsToClose);
370 if (ar.get() == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800371 RuntimeAbort(env, __LINE__, "Bad fd array");
Narayan Kamath973b4662014-03-31 13:41:26 +0100372 }
373 jsize i;
374 int devnull;
375 for (i = 0; i < count; i++) {
376 devnull = open("/dev/null", O_RDWR);
377 if (devnull < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700378 ALOGE("Failed to open /dev/null: %s", strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800379 RuntimeAbort(env, __LINE__, "Failed to open /dev/null");
Narayan Kamath973b4662014-03-31 13:41:26 +0100380 continue;
381 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700382 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100383 if (dup2(devnull, ar[i]) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700384 ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800385 RuntimeAbort(env, __LINE__, "Failed dup2()");
Narayan Kamath973b4662014-03-31 13:41:26 +0100386 }
387 close(devnull);
388 }
389}
390
391void SetThreadName(const char* thread_name) {
392 bool hasAt = false;
393 bool hasDot = false;
394 const char* s = thread_name;
395 while (*s) {
396 if (*s == '.') {
397 hasDot = true;
398 } else if (*s == '@') {
399 hasAt = true;
400 }
401 s++;
402 }
403 const int len = s - thread_name;
404 if (len < 15 || hasAt || !hasDot) {
405 s = thread_name;
406 } else {
407 s = thread_name + len - 15;
408 }
409 // pthread_setname_np fails rather than truncating long strings.
410 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
411 strlcpy(buf, s, sizeof(buf)-1);
412 errno = pthread_setname_np(pthread_self(), buf);
413 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700414 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100415 }
416}
417
Tim Murray6d43a8612015-08-05 14:31:05 -0700418#ifdef ENABLE_SCHED_BOOST
419static void SetForkLoad(bool boost) {
420 // set scheduler knob to boost forked processes
421 pid_t currentPid = getpid();
422 // fits at most "/proc/XXXXXXX/sched_init_task_load\0"
423 char schedPath[35];
424 snprintf(schedPath, sizeof(schedPath), "/proc/%u/sched_init_task_load", currentPid);
425 int schedBoostFile = open(schedPath, O_WRONLY);
426 if (schedBoostFile < 0) {
427 ALOGW("Unable to set zygote scheduler boost");
428 return;
429 }
430 if (boost) {
431 write(schedBoostFile, "100\0", 4);
432 } else {
433 write(schedBoostFile, "0\0", 2);
434 }
435 close(schedBoostFile);
436}
437#endif
438
Narayan Kamath973b4662014-03-31 13:41:26 +0100439// Utility routine to fork zygote and specialize the child process.
440static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
441 jint debug_flags, jobjectArray javaRlimits,
442 jlong permittedCapabilities, jlong effectiveCapabilities,
443 jint mount_external,
444 jstring java_se_info, jstring java_se_name,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700445 bool is_system_server, jintArray fdsToClose,
jgu212eacd062014-09-10 06:55:07 -0400446 jstring instructionSet, jstring dataDir) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100447 SetSigChldHandler();
448
Tim Murray6d43a8612015-08-05 14:31:05 -0700449#ifdef ENABLE_SCHED_BOOST
450 SetForkLoad(true);
451#endif
452
Narayan Kamath973b4662014-03-31 13:41:26 +0100453 pid_t pid = fork();
454
455 if (pid == 0) {
456 // The child process.
457 gMallocLeakZygoteChild = 1;
458
459 // Clean up any descriptors which must be closed immediately
460 DetachDescriptors(env, fdsToClose);
461
462 // Keep capabilities across UID change, unless we're staying root.
463 if (uid != 0) {
464 EnableKeepCapabilities(env);
465 }
466
467 DropCapabilitiesBoundingSet(env);
468
Calin Juravle79ec4c12014-10-24 16:16:49 +0100469 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
470 && android::NativeBridgeAvailable();
471 if (use_native_bridge) {
jgu212eacd062014-09-10 06:55:07 -0400472 ScopedUtfChars isa_string(env, instructionSet);
Calin Juravle79ec4c12014-10-24 16:16:49 +0100473 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400474 }
Calin Juravle6a4d2362014-10-28 12:16:21 +0000475 if (use_native_bridge && dataDir == NULL) {
476 // dataDir should never be null if we need to use a native bridge.
477 // In general, dataDir will never be null for normal applications. It can only happen in
478 // special cases (for isolated processes which are not associated with any app). These are
479 // launched by the framework and should not be emulated anyway.
480 use_native_bridge = false;
481 ALOGW("Native bridge will not be used because dataDir == NULL.");
482 }
jgu212eacd062014-09-10 06:55:07 -0400483
Calin Juravle79ec4c12014-10-24 16:16:49 +0100484 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700485 ALOGW("Failed to mount emulated storage: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100486 if (errno == ENOTCONN || errno == EROFS) {
487 // When device is actively encrypting, we get ENOTCONN here
488 // since FUSE was mounted before the framework restarted.
489 // When encrypted device is booting, we get EROFS since
490 // FUSE hasn't been created yet by init.
491 // In either case, continue without external storage.
492 } else {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800493 RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage");
Narayan Kamath973b4662014-03-31 13:41:26 +0100494 }
495 }
496
Colin Cross0161bbc2014-06-03 13:26:58 -0700497 if (!is_system_server) {
498 int rc = createProcessGroup(uid, getpid());
499 if (rc != 0) {
Colin Cross3089bed2014-07-14 15:07:04 -0700500 if (rc == -EROFS) {
501 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
502 } else {
503 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
504 }
Colin Cross0161bbc2014-06-03 13:26:58 -0700505 }
506 }
507
Narayan Kamath973b4662014-03-31 13:41:26 +0100508 SetGids(env, javaGids);
509
510 SetRLimits(env, javaRlimits);
511
Calin Juravle79ec4c12014-10-24 16:16:49 +0100512 if (use_native_bridge) {
513 ScopedUtfChars isa_string(env, instructionSet);
514 ScopedUtfChars data_dir(env, dataDir);
515 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400516 }
517
Narayan Kamath973b4662014-03-31 13:41:26 +0100518 int rc = setresgid(gid, gid, gid);
519 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700520 ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800521 RuntimeAbort(env, __LINE__, "setresgid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100522 }
523
524 rc = setresuid(uid, uid, uid);
525 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700526 ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
Andreas Gampeb053cce2015-11-17 16:38:59 -0800527 RuntimeAbort(env, __LINE__, "setresuid failed");
Narayan Kamath973b4662014-03-31 13:41:26 +0100528 }
529
Narayan Kamath973b4662014-03-31 13:41:26 +0100530 if (NeedsNoRandomizeWorkaround()) {
531 // Work around ARM kernel ASLR lossage (http://b/5817320).
532 int old_personality = personality(0xffffffff);
533 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
534 if (new_personality == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700535 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100536 }
537 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100538
539 SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
540
541 SetSchedulerPolicy(env);
542
Colin Cross18cd9f52014-06-13 12:58:55 -0700543 const char* se_info_c_str = NULL;
544 ScopedUtfChars* se_info = NULL;
545 if (java_se_info != NULL) {
546 se_info = new ScopedUtfChars(env, java_se_info);
547 se_info_c_str = se_info->c_str();
548 if (se_info_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800549 RuntimeAbort(env, __LINE__, "se_info_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700550 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100551 }
Colin Cross18cd9f52014-06-13 12:58:55 -0700552 const char* se_name_c_str = NULL;
553 ScopedUtfChars* se_name = NULL;
554 if (java_se_name != NULL) {
555 se_name = new ScopedUtfChars(env, java_se_name);
556 se_name_c_str = se_name->c_str();
557 if (se_name_c_str == NULL) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800558 RuntimeAbort(env, __LINE__, "se_name_c_str == NULL");
Colin Cross18cd9f52014-06-13 12:58:55 -0700559 }
560 }
561 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
562 if (rc == -1) {
563 ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
564 is_system_server, se_info_c_str, se_name_c_str);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800565 RuntimeAbort(env, __LINE__, "selinux_android_setcontext failed");
Colin Cross18cd9f52014-06-13 12:58:55 -0700566 }
567
568 // Make it easier to debug audit logs by setting the main thread's name to the
569 // nice name rather than "app_process".
570 if (se_info_c_str == NULL && is_system_server) {
571 se_name_c_str = "system_server";
572 }
573 if (se_info_c_str != NULL) {
574 SetThreadName(se_name_c_str);
575 }
576
577 delete se_info;
578 delete se_name;
Narayan Kamath973b4662014-03-31 13:41:26 +0100579
580 UnsetSigChldHandler();
581
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700582 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000583 is_system_server, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100584 if (env->ExceptionCheck()) {
Andreas Gampeb053cce2015-11-17 16:38:59 -0800585 RuntimeAbort(env, __LINE__, "Error calling post fork hooks.");
Narayan Kamath973b4662014-03-31 13:41:26 +0100586 }
587 } else if (pid > 0) {
588 // the parent process
Tim Murray6d43a8612015-08-05 14:31:05 -0700589
590#ifdef ENABLE_SCHED_BOOST
591 // unset scheduler knob
592 SetForkLoad(false);
593#endif
594
Narayan Kamath973b4662014-03-31 13:41:26 +0100595 }
596 return pid;
597}
598} // anonymous namespace
599
600namespace android {
601
602static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
603 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
604 jint debug_flags, jobjectArray rlimits,
605 jint mount_external, jstring se_info, jstring se_name,
jgu212eacd062014-09-10 06:55:07 -0400606 jintArray fdsToClose, jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700607 jlong capabilities = 0;
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800608
609 // Grant CAP_WAKE_ALARM to the Bluetooth process.
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900610 // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
611 // TODO: consider making such functionality an RPC to netd.
Pavlin Radoslavov2956bee2016-01-27 16:22:15 -0800612 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800613 capabilities |= (1LL << CAP_WAKE_ALARM);
Erik Kline0f6ae2e2016-02-22 15:42:07 +0900614 capabilities |= (1LL << CAP_NET_RAW);
615 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800616 }
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700617
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800618 // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
619 bool gid_wakelock_found = false;
620 if (gid == AID_WAKELOCK) {
621 gid_wakelock_found = true;
622 } else if (gids != NULL) {
623 jsize gids_num = env->GetArrayLength(gids);
624 ScopedIntArrayRO ar(env, gids);
625 if (ar.get() == NULL) {
626 RuntimeAbort(env, __LINE__, "Bad gids array");
627 }
628 for (int i = 0; i < gids_num; i++) {
629 if (ar[i] == AID_WAKELOCK) {
630 gid_wakelock_found = true;
631 break;
Sharvil Nanavatibabe8152015-08-31 23:25:06 -0700632 }
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -0800633 }
634 }
635 if (gid_wakelock_found) {
636 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700637 }
638
Narayan Kamath973b4662014-03-31 13:41:26 +0100639 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700640 rlimits, capabilities, capabilities, mount_external, se_info,
Andreas Gampea103ebe2014-09-24 15:37:53 -0700641 se_name, false, fdsToClose, instructionSet, appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100642}
643
644static jint com_android_internal_os_Zygote_nativeForkSystemServer(
645 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
646 jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
647 jlong effectiveCapabilities) {
648 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
649 debug_flags, rlimits,
650 permittedCapabilities, effectiveCapabilities,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700651 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
jgu212eacd062014-09-10 06:55:07 -0400652 NULL, NULL);
Narayan Kamath973b4662014-03-31 13:41:26 +0100653 if (pid > 0) {
654 // The zygote process checks whether the child process has died or not.
655 ALOGI("System server process %d has been created", pid);
656 gSystemServerPid = pid;
657 // There is a slight window that the system server process has crashed
658 // but it went unnoticed because we haven't published its pid yet. So
659 // we recheck here just to make sure that all is well.
660 int status;
661 if (waitpid(pid, &status, WNOHANG) == pid) {
662 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -0800663 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +0100664 }
665 }
666 return pid;
667}
668
doheon1.lee885b7422016-01-20 13:07:27 +0900669static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
670 // Zygote process unmount root storage space initially before every child processes are forked.
671 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -0400672 // and no need unmount storage operation in MountEmulatedStorage method.
673 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
674
675 // See storage config details at http://source.android.com/tech/storage/
676 // Create private mount namespace shared by all children
677 if (unshare(CLONE_NEWNS) == -1) {
678 RuntimeAbort(env, __LINE__, "Failed to unshare()");
679 return;
680 }
681
682 // Mark rootfs as being a slave so that changes from default
683 // namespace only flow into our children.
684 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
685 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
686 return;
687 }
688
689 // Create a staging tmpfs that is shared by our children; they will
690 // bind mount storage into their respective private namespaces, which
691 // are isolated from each other.
692 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
693 if (target_base != nullptr) {
694#define STRINGIFY_UID(x) __STRING(x)
695 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
696 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
697 ALOGE("Failed to mount tmpfs to %s", target_base);
698 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
699 return;
700 }
701#undef STRINGIFY_UID
702 }
doheon1.lee885b7422016-01-20 13:07:27 +0900703
704 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +0900705}
706
Daniel Micay76f6a862015-09-19 17:31:01 -0400707static const JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700708 { "nativeForkAndSpecialize",
jgu212eacd062014-09-10 06:55:07 -0400709 "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +0100710 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
711 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +0900712 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
713 { "nativeUnmountStorageOnInit", "()V",
714 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit }
Narayan Kamath973b4662014-03-31 13:41:26 +0100715};
716
717int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800718 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
719 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Nicolas Geoffraya8772352015-12-11 15:01:04 +0000720 "(IZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +0100721
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800722 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +0100723}
724} // namespace android
725