2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "Zygote"
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>
33 #include <sys/capability.h>
34 #include <sys/personality.h>
35 #include <sys/prctl.h>
36 #include <sys/resource.h>
38 #include <sys/types.h>
39 #include <sys/utsname.h>
43 #include <cutils/fs.h>
44 #include <cutils/multiuser.h>
45 #include <cutils/sched_policy.h>
46 #include <private/android_filesystem_config.h>
47 #include <utils/String8.h>
48 #include <selinux/android.h>
49 #include <processgroup/processgroup.h>
51 #include "core_jni_helpers.h"
53 #include "ScopedLocalRef.h"
54 #include "ScopedPrimitiveArray.h"
55 #include "ScopedUtfChars.h"
57 #include "nativebridge/native_bridge.h"
61 using android::String8;
63 static pid_t gSystemServerPid = 0;
65 static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
66 static jclass gZygoteClass;
67 static jmethodID gCallPostForkChildHooks;
69 // Must match values in com.android.internal.os.Zygote.
70 enum MountExternalKind {
71 MOUNT_EXTERNAL_NONE = 0,
72 MOUNT_EXTERNAL_DEFAULT = 1,
73 MOUNT_EXTERNAL_READ = 2,
74 MOUNT_EXTERNAL_WRITE = 3,
77 static void RuntimeAbort(JNIEnv* env) {
78 env->FatalError("RuntimeAbort");
81 // This signal handler is for zygote mode, since the zygote must reap its children
82 static void SigChldHandler(int /*signal_number*/) {
86 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
87 // Log process-death status that we care about. In general it is
88 // not safe to call LOG(...) from a signal handler because of
89 // possible reentrancy. However, we know a priori that the
90 // current implementation of LOG() is safe to call from a SIGCHLD
91 // handler in the zygote process. If the LOG() implementation
92 // changes its locking strategy or its use of syscalls within the
93 // lazy-init critical section, its use here may become unsafe.
94 if (WIFEXITED(status)) {
95 if (WEXITSTATUS(status)) {
96 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
98 } else if (WIFSIGNALED(status)) {
99 if (WTERMSIG(status) != SIGKILL) {
100 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
102 if (WCOREDUMP(status)) {
103 ALOGI("Process %d dumped core.", pid);
107 // If the just-crashed process is the system_server, bring down zygote
108 // so that it is restarted by init and system server will be restarted
110 if (pid == gSystemServerPid) {
111 ALOGE("Exit zygote because system server (%d) has terminated", pid);
112 kill(getpid(), SIGKILL);
116 // Note that we shouldn't consider ECHILD an error because
117 // the secondary zygote might have no children left to wait for.
118 if (pid < 0 && errno != ECHILD) {
119 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
123 // Configures the SIGCHLD handler for the zygote process. This is configured
124 // very late, because earlier in the runtime we may fork() and exec()
125 // other processes, and we want to waitpid() for those rather than
126 // have them be harvested immediately.
128 // This ends up being called repeatedly before each fork(), but there's
129 // no real harm in that.
130 static void SetSigChldHandler() {
132 memset(&sa, 0, sizeof(sa));
133 sa.sa_handler = SigChldHandler;
135 int err = sigaction(SIGCHLD, &sa, NULL);
137 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
141 // Sets the SIGCHLD handler back to default behavior in zygote children.
142 static void UnsetSigChldHandler() {
144 memset(&sa, 0, sizeof(sa));
145 sa.sa_handler = SIG_DFL;
147 int err = sigaction(SIGCHLD, &sa, NULL);
149 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
153 // Calls POSIX setgroups() using the int[] object as an argument.
154 // A NULL argument is tolerated.
155 static void SetGids(JNIEnv* env, jintArray javaGids) {
156 if (javaGids == NULL) {
160 ScopedIntArrayRO gids(env, javaGids);
161 if (gids.get() == NULL) {
164 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
166 ALOGE("setgroups failed");
171 // Sets the resource limits via setrlimit(2) for the values in the
172 // two-dimensional array of integers that's passed in. The second dimension
173 // contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
174 // treated as an empty array.
175 static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
176 if (javaRlimits == NULL) {
181 memset(&rlim, 0, sizeof(rlim));
183 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
184 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
185 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
186 if (javaRlimit.size() != 3) {
187 ALOGE("rlimits array must have a second dimension of size 3");
191 rlim.rlim_cur = javaRlimit[1];
192 rlim.rlim_max = javaRlimit[2];
194 int rc = setrlimit(javaRlimit[0], &rlim);
196 ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
203 // The debug malloc library needs to know whether it's the zygote or a child.
204 extern "C" int gMallocLeakZygoteChild;
206 static void EnableKeepCapabilities(JNIEnv* env) {
207 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
209 ALOGE("prctl(PR_SET_KEEPCAPS) failed");
214 static void DropCapabilitiesBoundingSet(JNIEnv* env) {
215 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
216 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
218 if (errno == EINVAL) {
219 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
220 "your kernel is compiled with file capabilities support");
222 ALOGE("prctl(PR_CAPBSET_DROP) failed");
229 static void SetCapabilities(JNIEnv* env, int64_t permitted, int64_t effective) {
230 __user_cap_header_struct capheader;
231 memset(&capheader, 0, sizeof(capheader));
232 capheader.version = _LINUX_CAPABILITY_VERSION_3;
235 __user_cap_data_struct capdata[2];
236 memset(&capdata, 0, sizeof(capdata));
237 capdata[0].effective = effective;
238 capdata[1].effective = effective >> 32;
239 capdata[0].permitted = permitted;
240 capdata[1].permitted = permitted >> 32;
242 if (capset(&capheader, &capdata[0]) == -1) {
243 ALOGE("capset(%" PRId64 ", %" PRId64 ") failed", permitted, effective);
248 static void SetSchedulerPolicy(JNIEnv* env) {
249 errno = -set_sched_policy(0, SP_DEFAULT);
251 ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
256 static int UnmountTree(const char* path) {
257 size_t path_len = strlen(path);
259 FILE* fp = setmntent("/proc/mounts", "r");
261 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
265 // Some volumes can be stacked on each other, so force unmount in
266 // reverse order to give us the best chance of success.
267 std::list<std::string> toUnmount;
269 while ((mentry = getmntent(fp)) != NULL) {
270 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
271 toUnmount.push_front(std::string(mentry->mnt_dir));
276 for (auto path : toUnmount) {
277 if (umount2(path.c_str(), MNT_DETACH)) {
278 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
284 // Create a private mount namespace and bind mount appropriate emulated
285 // storage for the given user.
286 static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
287 bool force_mount_namespace) {
288 // See storage config details at http://source.android.com/tech/storage/
290 // Create a second private mount namespace for our process
291 if (unshare(CLONE_NEWNS) == -1) {
292 ALOGW("Failed to unshare(): %s", strerror(errno));
296 // Unmount storage provided by root namespace and mount requested view
297 UnmountTree("/storage");
299 String8 storageSource;
300 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
301 storageSource = "/mnt/runtime/default";
302 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
303 storageSource = "/mnt/runtime/read";
304 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
305 storageSource = "/mnt/runtime/write";
307 // Sane default of no storage visible
310 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
311 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
312 ALOGW("Failed to mount %s to /storage: %s", storageSource.string(), strerror(errno));
316 // Mount user-specific symlink helper into place
317 userid_t user_id = multiuser_get_user_id(uid);
318 const String8 userSource(String8::format("/mnt/user/%d", user_id));
319 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
322 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
323 NULL, MS_BIND, NULL)) == -1) {
324 ALOGW("Failed to mount %s to /storage/self: %s", userSource.string(), strerror(errno));
331 static bool NeedsNoRandomizeWorkaround() {
332 #if !defined(__arm__)
338 if (uname(&uts) == -1) {
342 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
346 // Kernels before 3.4.* need the workaround.
347 return (major < 3) || ((major == 3) && (minor < 4));
351 // Utility to close down the Zygote socket file descriptors while
352 // the child is still running as root with Zygote's privileges. Each
353 // descriptor (if any) is closed via dup2(), replacing it with a valid
354 // (open) descriptor to /dev/null.
356 static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
360 jsize count = env->GetArrayLength(fdsToClose);
361 jint *ar = env->GetIntArrayElements(fdsToClose, 0);
363 ALOGE("Bad fd array");
368 for (i = 0; i < count; i++) {
369 devnull = open("/dev/null", O_RDWR);
371 ALOGE("Failed to open /dev/null: %s", strerror(errno));
375 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
376 if (dup2(devnull, ar[i]) < 0) {
377 ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
384 void SetThreadName(const char* thread_name) {
387 const char* s = thread_name;
391 } else if (*s == '@') {
396 const int len = s - thread_name;
397 if (len < 15 || hasAt || !hasDot) {
400 s = thread_name + len - 15;
402 // pthread_setname_np fails rather than truncating long strings.
403 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
404 strlcpy(buf, s, sizeof(buf)-1);
405 errno = pthread_setname_np(pthread_self(), buf);
407 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
411 // Utility routine to fork zygote and specialize the child process.
412 static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
413 jint debug_flags, jobjectArray javaRlimits,
414 jlong permittedCapabilities, jlong effectiveCapabilities,
416 jstring java_se_info, jstring java_se_name,
417 bool is_system_server, jintArray fdsToClose,
418 jstring instructionSet, jstring dataDir) {
424 // The child process.
425 gMallocLeakZygoteChild = 1;
427 // Clean up any descriptors which must be closed immediately
428 DetachDescriptors(env, fdsToClose);
430 // Keep capabilities across UID change, unless we're staying root.
432 EnableKeepCapabilities(env);
435 DropCapabilitiesBoundingSet(env);
437 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
438 && android::NativeBridgeAvailable();
439 if (use_native_bridge) {
440 ScopedUtfChars isa_string(env, instructionSet);
441 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
443 if (use_native_bridge && dataDir == NULL) {
444 // dataDir should never be null if we need to use a native bridge.
445 // In general, dataDir will never be null for normal applications. It can only happen in
446 // special cases (for isolated processes which are not associated with any app). These are
447 // launched by the framework and should not be emulated anyway.
448 use_native_bridge = false;
449 ALOGW("Native bridge will not be used because dataDir == NULL.");
452 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
453 ALOGW("Failed to mount emulated storage: %s", strerror(errno));
454 if (errno == ENOTCONN || errno == EROFS) {
455 // When device is actively encrypting, we get ENOTCONN here
456 // since FUSE was mounted before the framework restarted.
457 // When encrypted device is booting, we get EROFS since
458 // FUSE hasn't been created yet by init.
459 // In either case, continue without external storage.
461 ALOGE("Cannot continue without emulated storage");
466 if (!is_system_server) {
467 int rc = createProcessGroup(uid, getpid());
470 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
472 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
477 SetGids(env, javaGids);
479 SetRLimits(env, javaRlimits);
481 if (use_native_bridge) {
482 ScopedUtfChars isa_string(env, instructionSet);
483 ScopedUtfChars data_dir(env, dataDir);
484 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
487 int rc = setresgid(gid, gid, gid);
489 ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
493 rc = setresuid(uid, uid, uid);
495 ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
499 if (NeedsNoRandomizeWorkaround()) {
500 // Work around ARM kernel ASLR lossage (http://b/5817320).
501 int old_personality = personality(0xffffffff);
502 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
503 if (new_personality == -1) {
504 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
508 SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
510 SetSchedulerPolicy(env);
512 const char* se_info_c_str = NULL;
513 ScopedUtfChars* se_info = NULL;
514 if (java_se_info != NULL) {
515 se_info = new ScopedUtfChars(env, java_se_info);
516 se_info_c_str = se_info->c_str();
517 if (se_info_c_str == NULL) {
518 ALOGE("se_info_c_str == NULL");
522 const char* se_name_c_str = NULL;
523 ScopedUtfChars* se_name = NULL;
524 if (java_se_name != NULL) {
525 se_name = new ScopedUtfChars(env, java_se_name);
526 se_name_c_str = se_name->c_str();
527 if (se_name_c_str == NULL) {
528 ALOGE("se_name_c_str == NULL");
532 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
534 ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
535 is_system_server, se_info_c_str, se_name_c_str);
539 // Make it easier to debug audit logs by setting the main thread's name to the
540 // nice name rather than "app_process".
541 if (se_info_c_str == NULL && is_system_server) {
542 se_name_c_str = "system_server";
544 if (se_info_c_str != NULL) {
545 SetThreadName(se_name_c_str);
551 UnsetSigChldHandler();
553 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
554 is_system_server ? NULL : instructionSet);
555 if (env->ExceptionCheck()) {
556 ALOGE("Error calling post fork hooks.");
559 } else if (pid > 0) {
560 // the parent process
564 } // anonymous namespace
568 static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
569 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
570 jint debug_flags, jobjectArray rlimits,
571 jint mount_external, jstring se_info, jstring se_name,
572 jintArray fdsToClose, jstring instructionSet, jstring appDataDir) {
573 // Grant CAP_WAKE_ALARM to the Bluetooth process.
574 jlong capabilities = 0;
575 if (uid == AID_BLUETOOTH) {
576 capabilities |= (1LL << CAP_WAKE_ALARM);
579 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
580 rlimits, capabilities, capabilities, mount_external, se_info,
581 se_name, false, fdsToClose, instructionSet, appDataDir);
584 static jint com_android_internal_os_Zygote_nativeForkSystemServer(
585 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
586 jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
587 jlong effectiveCapabilities) {
588 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
589 debug_flags, rlimits,
590 permittedCapabilities, effectiveCapabilities,
591 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
594 // The zygote process checks whether the child process has died or not.
595 ALOGI("System server process %d has been created", pid);
596 gSystemServerPid = pid;
597 // There is a slight window that the system server process has crashed
598 // but it went unnoticed because we haven't published its pid yet. So
599 // we recheck here just to make sure that all is well.
601 if (waitpid(pid, &status, WNOHANG) == pid) {
602 ALOGE("System server process %d has died. Restarting Zygote!", pid);
609 static JNINativeMethod gMethods[] = {
610 { "nativeForkAndSpecialize",
611 "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I",
612 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
613 { "nativeForkSystemServer", "(II[II[[IJJ)I",
614 (void *) com_android_internal_os_Zygote_nativeForkSystemServer }
617 int register_com_android_internal_os_Zygote(JNIEnv* env) {
618 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
619 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
620 "(ILjava/lang/String;)V");
622 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
624 } // namespace android