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