blob: bfbeca10478aa2cfe4d882856c36e4cdbd84585e [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
23#include <grp.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070024#include <fcntl.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010025#include <paths.h>
26#include <signal.h>
27#include <stdlib.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010028#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070029#include <sys/capability.h>
30#include <sys/personality.h>
31#include <sys/prctl.h>
32#include <sys/resource.h>
33#include <sys/stat.h>
34#include <sys/types.h>
35#include <sys/utsname.h>
36#include <sys/wait.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010037
Colin Cross18cd9f52014-06-13 12:58:55 -070038
39#include <cutils/fs.h>
40#include <cutils/multiuser.h>
41#include <cutils/sched_policy.h>
42#include <utils/String8.h>
43#include <selinux/android.h>
44
45#include "android_runtime/AndroidRuntime.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010046#include "JNIHelp.h"
47#include "ScopedLocalRef.h"
48#include "ScopedPrimitiveArray.h"
49#include "ScopedUtfChars.h"
50
Narayan Kamath973b4662014-03-31 13:41:26 +010051namespace {
52
53using android::String8;
54
55static pid_t gSystemServerPid = 0;
56
57static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
58static jclass gZygoteClass;
59static jmethodID gCallPostForkChildHooks;
60
61// Must match values in com.android.internal.os.Zygote.
62enum MountExternalKind {
63 MOUNT_EXTERNAL_NONE = 0,
64 MOUNT_EXTERNAL_SINGLEUSER = 1,
65 MOUNT_EXTERNAL_MULTIUSER = 2,
66 MOUNT_EXTERNAL_MULTIUSER_ALL = 3,
67};
68
69static void RuntimeAbort(JNIEnv* env) {
70 env->FatalError("RuntimeAbort");
71}
72
73// This signal handler is for zygote mode, since the zygote must reap its children
74static void SigChldHandler(int /*signal_number*/) {
75 pid_t pid;
76 int status;
77
78 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
79 // Log process-death status that we care about. In general it is
80 // not safe to call LOG(...) from a signal handler because of
81 // possible reentrancy. However, we know a priori that the
82 // current implementation of LOG() is safe to call from a SIGCHLD
83 // handler in the zygote process. If the LOG() implementation
84 // changes its locking strategy or its use of syscalls within the
85 // lazy-init critical section, its use here may become unsafe.
86 if (WIFEXITED(status)) {
87 if (WEXITSTATUS(status)) {
88 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +010089 }
90 } else if (WIFSIGNALED(status)) {
91 if (WTERMSIG(status) != SIGKILL) {
Narayan Kamath160992d2014-04-14 14:46:07 +010092 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +010093 }
Narayan Kamath973b4662014-03-31 13:41:26 +010094 if (WCOREDUMP(status)) {
95 ALOGI("Process %d dumped core.", pid);
96 }
Narayan Kamath973b4662014-03-31 13:41:26 +010097 }
98
99 // If the just-crashed process is the system_server, bring down zygote
100 // so that it is restarted by init and system server will be restarted
101 // from there.
102 if (pid == gSystemServerPid) {
103 ALOGE("Exit zygote because system server (%d) has terminated");
104 kill(getpid(), SIGKILL);
105 }
106 }
107
Narayan Kamath160992d2014-04-14 14:46:07 +0100108 // Note that we shouldn't consider ECHILD an error because
109 // the secondary zygote might have no children left to wait for.
110 if (pid < 0 && errno != ECHILD) {
111 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100112 }
113}
114
115// Configures the SIGCHLD handler for the zygote process. This is configured
116// very late, because earlier in the runtime we may fork() and exec()
117// other processes, and we want to waitpid() for those rather than
118// have them be harvested immediately.
119//
120// This ends up being called repeatedly before each fork(), but there's
121// no real harm in that.
122static void SetSigChldHandler() {
123 struct sigaction sa;
124 memset(&sa, 0, sizeof(sa));
125 sa.sa_handler = SigChldHandler;
126
127 int err = sigaction(SIGCHLD, &sa, NULL);
128 if (err < 0) {
129 ALOGW("Error setting SIGCHLD handler: %d", errno);
130 }
131}
132
133// Sets the SIGCHLD handler back to default behavior in zygote children.
134static void UnsetSigChldHandler() {
135 struct sigaction sa;
136 memset(&sa, 0, sizeof(sa));
137 sa.sa_handler = SIG_DFL;
138
139 int err = sigaction(SIGCHLD, &sa, NULL);
140 if (err < 0) {
141 ALOGW("Error unsetting SIGCHLD handler: %d", errno);
142 }
143}
144
145// Calls POSIX setgroups() using the int[] object as an argument.
146// A NULL argument is tolerated.
147static void SetGids(JNIEnv* env, jintArray javaGids) {
148 if (javaGids == NULL) {
149 return;
150 }
151
152 ScopedIntArrayRO gids(env, javaGids);
153 if (gids.get() == NULL) {
154 RuntimeAbort(env);
155 }
156 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
157 if (rc == -1) {
158 ALOGE("setgroups failed");
159 RuntimeAbort(env);
160 }
161}
162
163// Sets the resource limits via setrlimit(2) for the values in the
164// two-dimensional array of integers that's passed in. The second dimension
165// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
166// treated as an empty array.
167static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
168 if (javaRlimits == NULL) {
169 return;
170 }
171
172 rlimit rlim;
173 memset(&rlim, 0, sizeof(rlim));
174
175 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
176 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
177 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
178 if (javaRlimit.size() != 3) {
179 ALOGE("rlimits array must have a second dimension of size 3");
180 RuntimeAbort(env);
181 }
182
183 rlim.rlim_cur = javaRlimit[1];
184 rlim.rlim_max = javaRlimit[2];
185
186 int rc = setrlimit(javaRlimit[0], &rlim);
187 if (rc == -1) {
188 ALOGE("setrlimit(%d, {%d, %d}) failed", javaRlimit[0], rlim.rlim_cur, rlim.rlim_max);
189 RuntimeAbort(env);
190 }
191 }
192}
193
Narayan Kamath973b4662014-03-31 13:41:26 +0100194// The debug malloc library needs to know whether it's the zygote or a child.
195extern "C" int gMallocLeakZygoteChild;
196
197static void EnableKeepCapabilities(JNIEnv* env) {
198 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
199 if (rc == -1) {
200 ALOGE("prctl(PR_SET_KEEPCAPS) failed");
201 RuntimeAbort(env);
202 }
203}
204
205static void DropCapabilitiesBoundingSet(JNIEnv* env) {
206 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
207 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
208 if (rc == -1) {
209 if (errno == EINVAL) {
210 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
211 "your kernel is compiled with file capabilities support");
212 } else {
213 ALOGE("prctl(PR_CAPBSET_DROP) failed");
214 RuntimeAbort(env);
215 }
216 }
217 }
218}
219
220static void SetCapabilities(JNIEnv* env, int64_t permitted, int64_t effective) {
221 __user_cap_header_struct capheader;
222 memset(&capheader, 0, sizeof(capheader));
223 capheader.version = _LINUX_CAPABILITY_VERSION_3;
224 capheader.pid = 0;
225
226 __user_cap_data_struct capdata[2];
227 memset(&capdata, 0, sizeof(capdata));
228 capdata[0].effective = effective;
229 capdata[1].effective = effective >> 32;
230 capdata[0].permitted = permitted;
231 capdata[1].permitted = permitted >> 32;
232
233 if (capset(&capheader, &capdata[0]) == -1) {
234 ALOGE("capset(%lld, %lld) failed", permitted, effective);
235 RuntimeAbort(env);
236 }
237}
238
239static void SetSchedulerPolicy(JNIEnv* env) {
240 errno = -set_sched_policy(0, SP_DEFAULT);
241 if (errno != 0) {
242 ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
243 RuntimeAbort(env);
244 }
245}
246
Narayan Kamath973b4662014-03-31 13:41:26 +0100247// Create a private mount namespace and bind mount appropriate emulated
248// storage for the given user.
249static bool MountEmulatedStorage(uid_t uid, jint mount_mode) {
250 if (mount_mode == MOUNT_EXTERNAL_NONE) {
251 return true;
252 }
253
254 // See storage config details at http://source.android.com/tech/storage/
255 userid_t user_id = multiuser_get_user_id(uid);
256
257 // Create a second private mount namespace for our process
258 if (unshare(CLONE_NEWNS) == -1) {
259 ALOGW("Failed to unshare(): %d", errno);
260 return false;
261 }
262
263 // Create bind mounts to expose external storage
264 if (mount_mode == MOUNT_EXTERNAL_MULTIUSER || mount_mode == MOUNT_EXTERNAL_MULTIUSER_ALL) {
265 // These paths must already be created by init.rc
266 const char* source = getenv("EMULATED_STORAGE_SOURCE");
267 const char* target = getenv("EMULATED_STORAGE_TARGET");
268 const char* legacy = getenv("EXTERNAL_STORAGE");
269 if (source == NULL || target == NULL || legacy == NULL) {
270 ALOGW("Storage environment undefined; unable to provide external storage");
271 return false;
272 }
273
274 // Prepare source paths
275
276 // /mnt/shell/emulated/0
277 const String8 source_user(String8::format("%s/%d", source, user_id));
278 // /storage/emulated/0
279 const String8 target_user(String8::format("%s/%d", target, user_id));
280
281 if (fs_prepare_dir(source_user.string(), 0000, 0, 0) == -1
282 || fs_prepare_dir(target_user.string(), 0000, 0, 0) == -1) {
283 return false;
284 }
285
286 if (mount_mode == MOUNT_EXTERNAL_MULTIUSER_ALL) {
287 // Mount entire external storage tree for all users
288 if (TEMP_FAILURE_RETRY(mount(source, target, NULL, MS_BIND, NULL)) == -1) {
289 ALOGW("Failed to mount %s to %s :%d", source, target, errno);
290 return false;
291 }
292 } else {
293 // Only mount user-specific external storage
294 if (TEMP_FAILURE_RETRY(
295 mount(source_user.string(), target_user.string(), NULL, MS_BIND, NULL)) == -1) {
296 ALOGW("Failed to mount %s to %s: %d", source_user.string(), target_user.string(), errno);
297 return false;
298 }
299 }
300
301 if (fs_prepare_dir(legacy, 0000, 0, 0) == -1) {
302 return false;
303 }
304
305 // Finally, mount user-specific path into place for legacy users
306 if (TEMP_FAILURE_RETRY(
307 mount(target_user.string(), legacy, NULL, MS_BIND | MS_REC, NULL)) == -1) {
308 ALOGW("Failed to mount %s to %s: %d", target_user.string(), legacy, errno);
309 return false;
310 }
311 } else {
312 ALOGW("Mount mode %d unsupported", mount_mode);
313 return false;
314 }
315
316 return true;
317}
318
Narayan Kamath973b4662014-03-31 13:41:26 +0100319static bool NeedsNoRandomizeWorkaround() {
320#if !defined(__arm__)
321 return false;
322#else
323 int major;
324 int minor;
325 struct utsname uts;
326 if (uname(&uts) == -1) {
327 return false;
328 }
329
330 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
331 return false;
332 }
333
334 // Kernels before 3.4.* need the workaround.
335 return (major < 3) || ((major == 3) && (minor < 4));
336#endif
337}
Narayan Kamath973b4662014-03-31 13:41:26 +0100338
339// Utility to close down the Zygote socket file descriptors while
340// the child is still running as root with Zygote's privileges. Each
341// descriptor (if any) is closed via dup2(), replacing it with a valid
342// (open) descriptor to /dev/null.
343
344static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
345 if (!fdsToClose) {
346 return;
347 }
348 jsize count = env->GetArrayLength(fdsToClose);
349 jint *ar = env->GetIntArrayElements(fdsToClose, 0);
350 if (!ar) {
351 ALOGE("Bad fd array");
352 RuntimeAbort(env);
353 }
354 jsize i;
355 int devnull;
356 for (i = 0; i < count; i++) {
357 devnull = open("/dev/null", O_RDWR);
358 if (devnull < 0) {
359 ALOGE("Failed to open /dev/null");
360 RuntimeAbort(env);
361 continue;
362 }
363 ALOGV("Switching descriptor %d to /dev/null: %d", ar[i], errno);
364 if (dup2(devnull, ar[i]) < 0) {
365 ALOGE("Failed dup2() on descriptor %d", ar[i]);
366 RuntimeAbort(env);
367 }
368 close(devnull);
369 }
370}
371
372void SetThreadName(const char* thread_name) {
373 bool hasAt = false;
374 bool hasDot = false;
375 const char* s = thread_name;
376 while (*s) {
377 if (*s == '.') {
378 hasDot = true;
379 } else if (*s == '@') {
380 hasAt = true;
381 }
382 s++;
383 }
384 const int len = s - thread_name;
385 if (len < 15 || hasAt || !hasDot) {
386 s = thread_name;
387 } else {
388 s = thread_name + len - 15;
389 }
390 // pthread_setname_np fails rather than truncating long strings.
391 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
392 strlcpy(buf, s, sizeof(buf)-1);
393 errno = pthread_setname_np(pthread_self(), buf);
394 if (errno != 0) {
395 ALOGW("Unable to set the name of current thread to '%s'", buf);
396 }
397}
398
399// Utility routine to fork zygote and specialize the child process.
400static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
401 jint debug_flags, jobjectArray javaRlimits,
402 jlong permittedCapabilities, jlong effectiveCapabilities,
403 jint mount_external,
404 jstring java_se_info, jstring java_se_name,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700405 bool is_system_server, jintArray fdsToClose,
406 jstring instructionSet) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100407 SetSigChldHandler();
408
409 pid_t pid = fork();
410
411 if (pid == 0) {
412 // The child process.
413 gMallocLeakZygoteChild = 1;
414
415 // Clean up any descriptors which must be closed immediately
416 DetachDescriptors(env, fdsToClose);
417
418 // Keep capabilities across UID change, unless we're staying root.
419 if (uid != 0) {
420 EnableKeepCapabilities(env);
421 }
422
423 DropCapabilitiesBoundingSet(env);
424
425 if (!MountEmulatedStorage(uid, mount_external)) {
426 ALOGW("Failed to mount emulated storage: %d", errno);
427 if (errno == ENOTCONN || errno == EROFS) {
428 // When device is actively encrypting, we get ENOTCONN here
429 // since FUSE was mounted before the framework restarted.
430 // When encrypted device is booting, we get EROFS since
431 // FUSE hasn't been created yet by init.
432 // In either case, continue without external storage.
433 } else {
434 ALOGE("Cannot continue without emulated storage");
435 RuntimeAbort(env);
436 }
437 }
438
439 SetGids(env, javaGids);
440
441 SetRLimits(env, javaRlimits);
442
443 int rc = setresgid(gid, gid, gid);
444 if (rc == -1) {
445 ALOGE("setresgid(%d) failed", gid);
446 RuntimeAbort(env);
447 }
448
449 rc = setresuid(uid, uid, uid);
450 if (rc == -1) {
451 ALOGE("setresuid(%d) failed", uid);
452 RuntimeAbort(env);
453 }
454
Narayan Kamath973b4662014-03-31 13:41:26 +0100455 if (NeedsNoRandomizeWorkaround()) {
456 // Work around ARM kernel ASLR lossage (http://b/5817320).
457 int old_personality = personality(0xffffffff);
458 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
459 if (new_personality == -1) {
460 ALOGW("personality(%d) failed", new_personality);
461 }
462 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100463
464 SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
465
466 SetSchedulerPolicy(env);
467
Colin Cross18cd9f52014-06-13 12:58:55 -0700468 const char* se_info_c_str = NULL;
469 ScopedUtfChars* se_info = NULL;
470 if (java_se_info != NULL) {
471 se_info = new ScopedUtfChars(env, java_se_info);
472 se_info_c_str = se_info->c_str();
473 if (se_info_c_str == NULL) {
474 ALOGE("se_info_c_str == NULL");
475 RuntimeAbort(env);
476 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100477 }
Colin Cross18cd9f52014-06-13 12:58:55 -0700478 const char* se_name_c_str = NULL;
479 ScopedUtfChars* se_name = NULL;
480 if (java_se_name != NULL) {
481 se_name = new ScopedUtfChars(env, java_se_name);
482 se_name_c_str = se_name->c_str();
483 if (se_name_c_str == NULL) {
484 ALOGE("se_name_c_str == NULL");
485 RuntimeAbort(env);
486 }
487 }
488 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
489 if (rc == -1) {
490 ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
491 is_system_server, se_info_c_str, se_name_c_str);
492 RuntimeAbort(env);
493 }
494
495 // Make it easier to debug audit logs by setting the main thread's name to the
496 // nice name rather than "app_process".
497 if (se_info_c_str == NULL && is_system_server) {
498 se_name_c_str = "system_server";
499 }
500 if (se_info_c_str != NULL) {
501 SetThreadName(se_name_c_str);
502 }
503
504 delete se_info;
505 delete se_name;
Narayan Kamath973b4662014-03-31 13:41:26 +0100506
507 UnsetSigChldHandler();
508
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700509 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
510 is_system_server ? NULL : instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100511 if (env->ExceptionCheck()) {
512 ALOGE("Error calling post fork hooks.");
513 RuntimeAbort(env);
514 }
515 } else if (pid > 0) {
516 // the parent process
517 }
518 return pid;
519}
520} // anonymous namespace
521
522namespace android {
523
524static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
525 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
526 jint debug_flags, jobjectArray rlimits,
527 jint mount_external, jstring se_info, jstring se_name,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700528 jintArray fdsToClose, jstring instructionSet) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100529 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700530 rlimits, 0, 0, mount_external, se_info, se_name, false, fdsToClose, instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100531}
532
533static jint com_android_internal_os_Zygote_nativeForkSystemServer(
534 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
535 jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
536 jlong effectiveCapabilities) {
537 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
538 debug_flags, rlimits,
539 permittedCapabilities, effectiveCapabilities,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700540 MOUNT_EXTERNAL_NONE, NULL, NULL, true, NULL, NULL);
Narayan Kamath973b4662014-03-31 13:41:26 +0100541 if (pid > 0) {
542 // The zygote process checks whether the child process has died or not.
543 ALOGI("System server process %d has been created", pid);
544 gSystemServerPid = pid;
545 // There is a slight window that the system server process has crashed
546 // but it went unnoticed because we haven't published its pid yet. So
547 // we recheck here just to make sure that all is well.
548 int status;
549 if (waitpid(pid, &status, WNOHANG) == pid) {
550 ALOGE("System server process %d has died. Restarting Zygote!", pid);
551 RuntimeAbort(env);
552 }
553 }
554 return pid;
555}
556
557static JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700558 { "nativeForkAndSpecialize",
559 "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +0100560 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
561 { "nativeForkSystemServer", "(II[II[[IJJ)I",
562 (void *) com_android_internal_os_Zygote_nativeForkSystemServer }
563};
564
565int register_com_android_internal_os_Zygote(JNIEnv* env) {
566 gZygoteClass = (jclass) env->NewGlobalRef(env->FindClass(kZygoteClassName));
567 if (gZygoteClass == NULL) {
568 RuntimeAbort(env);
569 }
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700570 gCallPostForkChildHooks = env->GetStaticMethodID(gZygoteClass, "callPostForkChildHooks",
571 "(ILjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +0100572
573 return AndroidRuntime::registerNativeMethods(env, "com/android/internal/os/Zygote",
574 gMethods, NELEM(gMethods));
575}
576} // namespace android
577