com_android_internal_os_Zygote.cpp revision 6f372daa9d31fb6843a24fe12669a1f73e7ca8ab
1/*
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#define LOG_TAG "Zygote"
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 <list>
24#include <sstream>
25#include <string>
26
27#include <fcntl.h>
28#include <grp.h>
29#include <inttypes.h>
30#include <mntent.h>
31#include <paths.h>
32#include <signal.h>
33#include <stdlib.h>
34#include <sys/capability.h>
35#include <sys/cdefs.h>
36#include <sys/personality.h>
37#include <sys/prctl.h>
38#include <sys/resource.h>
39#include <sys/stat.h>
40#include <sys/time.h>
41#include <sys/types.h>
42#include <sys/utsname.h>
43#include <sys/wait.h>
44#include <unistd.h>
45
46#include "android-base/logging.h"
47#include <cutils/fs.h>
48#include <cutils/multiuser.h>
49#include <cutils/sched_policy.h>
50#include <private/android_filesystem_config.h>
51#include <utils/String8.h>
52#include <selinux/android.h>
53#include <processgroup/processgroup.h>
54
55#include "core_jni_helpers.h"
56#include "JNIHelp.h"
57#include "ScopedLocalRef.h"
58#include "ScopedPrimitiveArray.h"
59#include "ScopedUtfChars.h"
60#include "fd_utils.h"
61
62#include "nativebridge/native_bridge.h"
63
64namespace {
65
66using android::String8;
67
68static pid_t gSystemServerPid = 0;
69
70static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
71static jclass gZygoteClass;
72static jmethodID gCallPostForkChildHooks;
73
74// Must match values in com.android.internal.os.Zygote.
75enum MountExternalKind {
76  MOUNT_EXTERNAL_NONE = 0,
77  MOUNT_EXTERNAL_DEFAULT = 1,
78  MOUNT_EXTERNAL_READ = 2,
79  MOUNT_EXTERNAL_WRITE = 3,
80};
81
82static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
83  std::ostringstream oss;
84  oss << __FILE__ << ":" << line << ": " << msg;
85  env->FatalError(oss.str().c_str());
86}
87
88// This signal handler is for zygote mode, since the zygote must reap its children
89static void SigChldHandler(int /*signal_number*/) {
90  pid_t pid;
91  int status;
92
93  // It's necessary to save and restore the errno during this function.
94  // Since errno is stored per thread, changing it here modifies the errno
95  // on the thread on which this signal handler executes. If a signal occurs
96  // between a call and an errno check, it's possible to get the errno set
97  // here.
98  // See b/23572286 for extra information.
99  int saved_errno = errno;
100
101  while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
102     // Log process-death status that we care about.  In general it is
103     // not safe to call LOG(...) from a signal handler because of
104     // possible reentrancy.  However, we know a priori that the
105     // current implementation of LOG() is safe to call from a SIGCHLD
106     // handler in the zygote process.  If the LOG() implementation
107     // changes its locking strategy or its use of syscalls within the
108     // lazy-init critical section, its use here may become unsafe.
109    if (WIFEXITED(status)) {
110      if (WEXITSTATUS(status)) {
111        ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
112      }
113    } else if (WIFSIGNALED(status)) {
114      if (WTERMSIG(status) != SIGKILL) {
115        ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
116      }
117      if (WCOREDUMP(status)) {
118        ALOGI("Process %d dumped core.", pid);
119      }
120    }
121
122    // If the just-crashed process is the system_server, bring down zygote
123    // so that it is restarted by init and system server will be restarted
124    // from there.
125    if (pid == gSystemServerPid) {
126      ALOGE("Exit zygote because system server (%d) has terminated", pid);
127      kill(getpid(), SIGKILL);
128    }
129  }
130
131  // Note that we shouldn't consider ECHILD an error because
132  // the secondary zygote might have no children left to wait for.
133  if (pid < 0 && errno != ECHILD) {
134    ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
135  }
136
137  errno = saved_errno;
138}
139
140// Configures the SIGCHLD handler for the zygote process. This is configured
141// very late, because earlier in the runtime we may fork() and exec()
142// other processes, and we want to waitpid() for those rather than
143// have them be harvested immediately.
144//
145// This ends up being called repeatedly before each fork(), but there's
146// no real harm in that.
147static void SetSigChldHandler() {
148  struct sigaction sa;
149  memset(&sa, 0, sizeof(sa));
150  sa.sa_handler = SigChldHandler;
151
152  int err = sigaction(SIGCHLD, &sa, NULL);
153  if (err < 0) {
154    ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
155  }
156}
157
158// Resets nice priority for zygote process. Zygote priority can be set
159// to high value during boot phase to speed it up. We want to ensure
160// zygote is running at normal priority before childs are forked from it.
161//
162// This ends up being called repeatedly before each fork(), but there's
163// no real harm in that.
164static void ResetNicePriority(JNIEnv* env) {
165  errno = 0;
166  int prio = getpriority(PRIO_PROCESS, 0);
167  if (prio == -1 && errno != 0) {
168    ALOGW("getpriority failed: %s\n", strerror(errno));
169  }
170  if (prio != 0 && setpriority(PRIO_PROCESS, 0, 0) != 0) {
171    ALOGE("setpriority(%d, 0, 0) failed: %s", PRIO_PROCESS, strerror(errno));
172    RuntimeAbort(env, __LINE__, "setpriority failed");
173  }
174}
175
176// Sets the SIGCHLD handler back to default behavior in zygote children.
177static void UnsetSigChldHandler() {
178  struct sigaction sa;
179  memset(&sa, 0, sizeof(sa));
180  sa.sa_handler = SIG_DFL;
181
182  int err = sigaction(SIGCHLD, &sa, NULL);
183  if (err < 0) {
184    ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
185  }
186}
187
188// Calls POSIX setgroups() using the int[] object as an argument.
189// A NULL argument is tolerated.
190static void SetGids(JNIEnv* env, jintArray javaGids) {
191  if (javaGids == NULL) {
192    return;
193  }
194
195  ScopedIntArrayRO gids(env, javaGids);
196  if (gids.get() == NULL) {
197    RuntimeAbort(env, __LINE__, "Getting gids int array failed");
198  }
199  int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
200  if (rc == -1) {
201    std::ostringstream oss;
202    oss << "setgroups failed: " << strerror(errno) << ", gids.size=" << gids.size();
203    RuntimeAbort(env, __LINE__, oss.str().c_str());
204  }
205}
206
207// Sets the resource limits via setrlimit(2) for the values in the
208// two-dimensional array of integers that's passed in. The second dimension
209// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
210// treated as an empty array.
211static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
212  if (javaRlimits == NULL) {
213    return;
214  }
215
216  rlimit rlim;
217  memset(&rlim, 0, sizeof(rlim));
218
219  for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
220    ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
221    ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
222    if (javaRlimit.size() != 3) {
223      RuntimeAbort(env, __LINE__, "rlimits array must have a second dimension of size 3");
224    }
225
226    rlim.rlim_cur = javaRlimit[1];
227    rlim.rlim_max = javaRlimit[2];
228
229    int rc = setrlimit(javaRlimit[0], &rlim);
230    if (rc == -1) {
231      ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
232            rlim.rlim_max);
233      RuntimeAbort(env, __LINE__, "setrlimit failed");
234    }
235  }
236}
237
238// The debug malloc library needs to know whether it's the zygote or a child.
239extern "C" int gMallocLeakZygoteChild;
240
241static void EnableKeepCapabilities(JNIEnv* env) {
242  int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
243  if (rc == -1) {
244    RuntimeAbort(env, __LINE__, "prctl(PR_SET_KEEPCAPS) failed");
245  }
246}
247
248static void DropCapabilitiesBoundingSet(JNIEnv* env) {
249  for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
250    int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
251    if (rc == -1) {
252      if (errno == EINVAL) {
253        ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
254              "your kernel is compiled with file capabilities support");
255      } else {
256        ALOGE("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
257        RuntimeAbort(env, __LINE__, "prctl(PR_CAPBSET_DROP) failed");
258      }
259    }
260  }
261}
262
263static void SetInheritable(JNIEnv* env, uint64_t inheritable) {
264  __user_cap_header_struct capheader;
265  memset(&capheader, 0, sizeof(capheader));
266  capheader.version = _LINUX_CAPABILITY_VERSION_3;
267  capheader.pid = 0;
268
269  __user_cap_data_struct capdata[2];
270  if (capget(&capheader, &capdata[0]) == -1) {
271    ALOGE("capget failed: %s", strerror(errno));
272    RuntimeAbort(env, __LINE__, "capget failed");
273  }
274
275  capdata[0].inheritable = inheritable;
276  capdata[1].inheritable = inheritable >> 32;
277
278  if (capset(&capheader, &capdata[0]) == -1) {
279    ALOGE("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
280    RuntimeAbort(env, __LINE__, "capset failed");
281  }
282}
283
284static void SetCapabilities(JNIEnv* env, uint64_t permitted, uint64_t effective,
285                            uint64_t inheritable) {
286  __user_cap_header_struct capheader;
287  memset(&capheader, 0, sizeof(capheader));
288  capheader.version = _LINUX_CAPABILITY_VERSION_3;
289  capheader.pid = 0;
290
291  __user_cap_data_struct capdata[2];
292  memset(&capdata, 0, sizeof(capdata));
293  capdata[0].effective = effective;
294  capdata[1].effective = effective >> 32;
295  capdata[0].permitted = permitted;
296  capdata[1].permitted = permitted >> 32;
297  capdata[0].inheritable = inheritable;
298  capdata[1].inheritable = inheritable >> 32;
299
300  if (capset(&capheader, &capdata[0]) == -1) {
301    ALOGE("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") failed: %s", permitted,
302          effective, inheritable, strerror(errno));
303    RuntimeAbort(env, __LINE__, "capset failed");
304  }
305}
306
307static void SetSchedulerPolicy(JNIEnv* env) {
308  errno = -set_sched_policy(0, SP_DEFAULT);
309  if (errno != 0) {
310    ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
311    RuntimeAbort(env, __LINE__, "set_sched_policy(0, SP_DEFAULT) failed");
312  }
313}
314
315static int UnmountTree(const char* path) {
316    size_t path_len = strlen(path);
317
318    FILE* fp = setmntent("/proc/mounts", "r");
319    if (fp == NULL) {
320        ALOGE("Error opening /proc/mounts: %s", strerror(errno));
321        return -errno;
322    }
323
324    // Some volumes can be stacked on each other, so force unmount in
325    // reverse order to give us the best chance of success.
326    std::list<std::string> toUnmount;
327    mntent* mentry;
328    while ((mentry = getmntent(fp)) != NULL) {
329        if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
330            toUnmount.push_front(std::string(mentry->mnt_dir));
331        }
332    }
333    endmntent(fp);
334
335    for (auto path : toUnmount) {
336        if (umount2(path.c_str(), MNT_DETACH)) {
337            ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
338        }
339    }
340    return 0;
341}
342
343// Create a private mount namespace and bind mount appropriate emulated
344// storage for the given user.
345static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
346        bool force_mount_namespace) {
347    // See storage config details at http://source.android.com/tech/storage/
348
349    String8 storageSource;
350    if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
351        storageSource = "/mnt/runtime/default";
352    } else if (mount_mode == MOUNT_EXTERNAL_READ) {
353        storageSource = "/mnt/runtime/read";
354    } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
355        storageSource = "/mnt/runtime/write";
356    } else if (!force_mount_namespace) {
357        // Sane default of no storage visible
358        return true;
359    }
360
361    // Create a second private mount namespace for our process
362    if (unshare(CLONE_NEWNS) == -1) {
363        ALOGW("Failed to unshare(): %s", strerror(errno));
364        return false;
365    }
366
367    if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
368            NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
369        ALOGW("Failed to mount %s to /storage: %s", storageSource.string(), strerror(errno));
370        return false;
371    }
372
373    // Mount user-specific symlink helper into place
374    userid_t user_id = multiuser_get_user_id(uid);
375    const String8 userSource(String8::format("/mnt/user/%d", user_id));
376    if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
377        return false;
378    }
379    if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
380            NULL, MS_BIND, NULL)) == -1) {
381        ALOGW("Failed to mount %s to /storage/self: %s", userSource.string(), strerror(errno));
382        return false;
383    }
384
385    return true;
386}
387
388static bool NeedsNoRandomizeWorkaround() {
389#if !defined(__arm__)
390    return false;
391#else
392    int major;
393    int minor;
394    struct utsname uts;
395    if (uname(&uts) == -1) {
396        return false;
397    }
398
399    if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
400        return false;
401    }
402
403    // Kernels before 3.4.* need the workaround.
404    return (major < 3) || ((major == 3) && (minor < 4));
405#endif
406}
407
408// Utility to close down the Zygote socket file descriptors while
409// the child is still running as root with Zygote's privileges.  Each
410// descriptor (if any) is closed via dup2(), replacing it with a valid
411// (open) descriptor to /dev/null.
412
413static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
414  if (!fdsToClose) {
415    return;
416  }
417  jsize count = env->GetArrayLength(fdsToClose);
418  ScopedIntArrayRO ar(env, fdsToClose);
419  if (ar.get() == NULL) {
420      RuntimeAbort(env, __LINE__, "Bad fd array");
421  }
422  jsize i;
423  int devnull;
424  for (i = 0; i < count; i++) {
425    devnull = open("/dev/null", O_RDWR);
426    if (devnull < 0) {
427      ALOGE("Failed to open /dev/null: %s", strerror(errno));
428      RuntimeAbort(env, __LINE__, "Failed to open /dev/null");
429      continue;
430    }
431    ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
432    if (dup2(devnull, ar[i]) < 0) {
433      ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
434      RuntimeAbort(env, __LINE__, "Failed dup2()");
435    }
436    close(devnull);
437  }
438}
439
440void SetThreadName(const char* thread_name) {
441  bool hasAt = false;
442  bool hasDot = false;
443  const char* s = thread_name;
444  while (*s) {
445    if (*s == '.') {
446      hasDot = true;
447    } else if (*s == '@') {
448      hasAt = true;
449    }
450    s++;
451  }
452  const int len = s - thread_name;
453  if (len < 15 || hasAt || !hasDot) {
454    s = thread_name;
455  } else {
456    s = thread_name + len - 15;
457  }
458  // pthread_setname_np fails rather than truncating long strings.
459  char buf[16];       // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
460  strlcpy(buf, s, sizeof(buf)-1);
461  errno = pthread_setname_np(pthread_self(), buf);
462  if (errno != 0) {
463    ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
464  }
465}
466
467// The list of open zygote file descriptors.
468static FileDescriptorTable* gOpenFdTable = NULL;
469
470static void FillFileDescriptorVector(JNIEnv* env,
471                                     jintArray java_fds,
472                                     std::vector<int>* fds) {
473  CHECK(fds != nullptr);
474  if (java_fds != nullptr) {
475    ScopedIntArrayRO ar(env, java_fds);
476    if (ar.get() == nullptr) {
477      RuntimeAbort(env, __LINE__, "Bad fd array");
478    }
479    fds->reserve(ar.size());
480    for (size_t i = 0; i < ar.size(); ++i) {
481      fds->push_back(ar[i]);
482    }
483  }
484}
485
486// Utility routine to fork zygote and specialize the child process.
487static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
488                                     jint debug_flags, jobjectArray javaRlimits,
489                                     jlong permittedCapabilities, jlong effectiveCapabilities,
490                                     jint mount_external,
491                                     jstring java_se_info, jstring java_se_name,
492                                     bool is_system_server, jintArray fdsToClose,
493                                     jintArray fdsToIgnore,
494                                     jstring instructionSet, jstring dataDir) {
495  SetSigChldHandler();
496
497  sigset_t sigchld;
498  sigemptyset(&sigchld);
499  sigaddset(&sigchld, SIGCHLD);
500
501  // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
502  // log, which would result in the logging FDs we close being reopened.
503  // This would cause failures because the FDs are not whitelisted.
504  //
505  // Note that the zygote process is single threaded at this point.
506  if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
507    ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
508    RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_BLOCK, { SIGCHLD }) failed.");
509  }
510
511  // Close any logging related FDs before we start evaluating the list of
512  // file descriptors.
513  __android_log_close();
514
515  // If this is the first fork for this zygote, create the open FD table.
516  // If it isn't, we just need to check whether the list of open files has
517  // changed (and it shouldn't in the normal case).
518  std::vector<int> fds_to_ignore;
519  FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore);
520  if (gOpenFdTable == NULL) {
521    gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore);
522    if (gOpenFdTable == NULL) {
523      RuntimeAbort(env, __LINE__, "Unable to construct file descriptor table.");
524    }
525  } else if (!gOpenFdTable->Restat(fds_to_ignore)) {
526    RuntimeAbort(env, __LINE__, "Unable to restat file descriptor table.");
527  }
528
529  ResetNicePriority(env);
530
531  pid_t pid = fork();
532
533  if (pid == 0) {
534    // The child process.
535    gMallocLeakZygoteChild = 1;
536
537    // Clean up any descriptors which must be closed immediately
538    DetachDescriptors(env, fdsToClose);
539
540    // Re-open all remaining open file descriptors so that they aren't shared
541    // with the zygote across a fork.
542    if (!gOpenFdTable->ReopenOrDetach()) {
543      RuntimeAbort(env, __LINE__, "Unable to reopen whitelisted descriptors.");
544    }
545
546    if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
547      ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
548      RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed.");
549    }
550
551    // Keep capabilities across UID change, unless we're staying root.
552    if (uid != 0) {
553      EnableKeepCapabilities(env);
554    }
555
556    SetInheritable(env, permittedCapabilities);
557    DropCapabilitiesBoundingSet(env);
558
559    bool use_native_bridge = !is_system_server && (instructionSet != NULL)
560        && android::NativeBridgeAvailable();
561    if (use_native_bridge) {
562      ScopedUtfChars isa_string(env, instructionSet);
563      use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
564    }
565    if (use_native_bridge && dataDir == NULL) {
566      // dataDir should never be null if we need to use a native bridge.
567      // In general, dataDir will never be null for normal applications. It can only happen in
568      // special cases (for isolated processes which are not associated with any app). These are
569      // launched by the framework and should not be emulated anyway.
570      use_native_bridge = false;
571      ALOGW("Native bridge will not be used because dataDir == NULL.");
572    }
573
574    if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
575      ALOGW("Failed to mount emulated storage: %s", strerror(errno));
576      if (errno == ENOTCONN || errno == EROFS) {
577        // When device is actively encrypting, we get ENOTCONN here
578        // since FUSE was mounted before the framework restarted.
579        // When encrypted device is booting, we get EROFS since
580        // FUSE hasn't been created yet by init.
581        // In either case, continue without external storage.
582      } else {
583        RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage");
584      }
585    }
586
587    if (!is_system_server) {
588        int rc = createProcessGroup(uid, getpid());
589        if (rc != 0) {
590            if (rc == -EROFS) {
591                ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
592            } else {
593                ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
594            }
595        }
596    }
597
598    SetGids(env, javaGids);
599
600    SetRLimits(env, javaRlimits);
601
602    if (use_native_bridge) {
603      ScopedUtfChars isa_string(env, instructionSet);
604      ScopedUtfChars data_dir(env, dataDir);
605      android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
606    }
607
608    int rc = setresgid(gid, gid, gid);
609    if (rc == -1) {
610      ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
611      RuntimeAbort(env, __LINE__, "setresgid failed");
612    }
613
614    rc = setresuid(uid, uid, uid);
615    if (rc == -1) {
616      ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
617      RuntimeAbort(env, __LINE__, "setresuid failed");
618    }
619
620    if (NeedsNoRandomizeWorkaround()) {
621        // Work around ARM kernel ASLR lossage (http://b/5817320).
622        int old_personality = personality(0xffffffff);
623        int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
624        if (new_personality == -1) {
625            ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
626        }
627    }
628
629    SetCapabilities(env, permittedCapabilities, effectiveCapabilities, permittedCapabilities);
630
631    SetSchedulerPolicy(env);
632
633    const char* se_info_c_str = NULL;
634    ScopedUtfChars* se_info = NULL;
635    if (java_se_info != NULL) {
636        se_info = new ScopedUtfChars(env, java_se_info);
637        se_info_c_str = se_info->c_str();
638        if (se_info_c_str == NULL) {
639          RuntimeAbort(env, __LINE__, "se_info_c_str == NULL");
640        }
641    }
642    const char* se_name_c_str = NULL;
643    ScopedUtfChars* se_name = NULL;
644    if (java_se_name != NULL) {
645        se_name = new ScopedUtfChars(env, java_se_name);
646        se_name_c_str = se_name->c_str();
647        if (se_name_c_str == NULL) {
648          RuntimeAbort(env, __LINE__, "se_name_c_str == NULL");
649        }
650    }
651    rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
652    if (rc == -1) {
653      ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
654            is_system_server, se_info_c_str, se_name_c_str);
655      RuntimeAbort(env, __LINE__, "selinux_android_setcontext failed");
656    }
657
658    // Make it easier to debug audit logs by setting the main thread's name to the
659    // nice name rather than "app_process".
660    if (se_info_c_str == NULL && is_system_server) {
661      se_name_c_str = "system_server";
662    }
663    if (se_info_c_str != NULL) {
664      SetThreadName(se_name_c_str);
665    }
666
667    delete se_info;
668    delete se_name;
669
670    UnsetSigChldHandler();
671
672    env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
673                              is_system_server, instructionSet);
674    if (env->ExceptionCheck()) {
675      RuntimeAbort(env, __LINE__, "Error calling post fork hooks.");
676    }
677  } else if (pid > 0) {
678    // the parent process
679
680    // We blocked SIGCHLD prior to a fork, we unblock it here.
681    if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
682      ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
683      RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed.");
684    }
685  }
686  return pid;
687}
688}  // anonymous namespace
689
690namespace android {
691
692static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
693        JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
694        jint debug_flags, jobjectArray rlimits,
695        jint mount_external, jstring se_info, jstring se_name,
696        jintArray fdsToClose,
697        jintArray fdsToIgnore,
698        jstring instructionSet, jstring appDataDir) {
699    jlong capabilities = 0;
700
701    // Grant CAP_WAKE_ALARM to the Bluetooth process.
702    // Additionally, allow bluetooth to open packet sockets so it can start the DHCP client.
703    // TODO: consider making such functionality an RPC to netd.
704    if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
705      capabilities |= (1LL << CAP_WAKE_ALARM);
706      capabilities |= (1LL << CAP_NET_RAW);
707      capabilities |= (1LL << CAP_NET_BIND_SERVICE);
708    }
709
710    // Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
711    bool gid_wakelock_found = false;
712    if (gid == AID_WAKELOCK) {
713      gid_wakelock_found = true;
714    } else if (gids != NULL) {
715      jsize gids_num = env->GetArrayLength(gids);
716      ScopedIntArrayRO ar(env, gids);
717      if (ar.get() == NULL) {
718        RuntimeAbort(env, __LINE__, "Bad gids array");
719      }
720      for (int i = 0; i < gids_num; i++) {
721        if (ar[i] == AID_WAKELOCK) {
722          gid_wakelock_found = true;
723          break;
724        }
725      }
726    }
727    if (gid_wakelock_found) {
728      capabilities |= (1LL << CAP_BLOCK_SUSPEND);
729    }
730
731    return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
732            rlimits, capabilities, capabilities, mount_external, se_info,
733            se_name, false, fdsToClose, fdsToIgnore, instructionSet, appDataDir);
734}
735
736static jint com_android_internal_os_Zygote_nativeForkSystemServer(
737        JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
738        jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
739        jlong effectiveCapabilities) {
740  pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
741                                      debug_flags, rlimits,
742                                      permittedCapabilities, effectiveCapabilities,
743                                      MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
744                                      NULL, NULL, NULL);
745  if (pid > 0) {
746      // The zygote process checks whether the child process has died or not.
747      ALOGI("System server process %d has been created", pid);
748      gSystemServerPid = pid;
749      // There is a slight window that the system server process has crashed
750      // but it went unnoticed because we haven't published its pid yet. So
751      // we recheck here just to make sure that all is well.
752      int status;
753      if (waitpid(pid, &status, WNOHANG) == pid) {
754          ALOGE("System server process %d has died. Restarting Zygote!", pid);
755          RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
756      }
757  }
758  return pid;
759}
760
761static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
762        JNIEnv* env, jclass, jstring path) {
763    ScopedUtfChars path_native(env, path);
764    const char* path_cstr = path_native.c_str();
765    if (!path_cstr) {
766        RuntimeAbort(env, __LINE__, "path_cstr == NULL");
767    }
768    FileDescriptorWhitelist::Get()->Allow(path_cstr);
769}
770
771static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
772    // Zygote process unmount root storage space initially before every child processes are forked.
773    // Every forked child processes (include SystemServer) only mount their own root storage space
774    // and no need unmount storage operation in MountEmulatedStorage method.
775    // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
776
777    // See storage config details at http://source.android.com/tech/storage/
778    // Create private mount namespace shared by all children
779    if (unshare(CLONE_NEWNS) == -1) {
780        RuntimeAbort(env, __LINE__, "Failed to unshare()");
781        return;
782    }
783
784    // Mark rootfs as being a slave so that changes from default
785    // namespace only flow into our children.
786    if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
787        RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
788        return;
789    }
790
791    // Create a staging tmpfs that is shared by our children; they will
792    // bind mount storage into their respective private namespaces, which
793    // are isolated from each other.
794    const char* target_base = getenv("EMULATED_STORAGE_TARGET");
795    if (target_base != nullptr) {
796#define STRINGIFY_UID(x) __STRING(x)
797        if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
798                  "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
799            ALOGE("Failed to mount tmpfs to %s", target_base);
800            RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
801            return;
802        }
803#undef STRINGIFY_UID
804    }
805
806    UnmountTree("/storage");
807}
808
809static const JNINativeMethod gMethods[] = {
810    { "nativeForkAndSpecialize",
811      "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[ILjava/lang/String;Ljava/lang/String;)I",
812      (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
813    { "nativeForkSystemServer", "(II[II[[IJJ)I",
814      (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
815    { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
816      (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
817    { "nativeUnmountStorageOnInit", "()V",
818      (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit }
819};
820
821int register_com_android_internal_os_Zygote(JNIEnv* env) {
822  gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
823  gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
824                                                   "(IZLjava/lang/String;)V");
825
826  return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
827}
828}  // namespace android
829