OSDN Git Service

Merge tag 'android-6.0.1_r66' into marshmallow-x86
[android-x86/frameworks-base.git] / core / jni / com_android_internal_os_Zygote.cpp
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 <string>
25
26 #include <fcntl.h>
27 #include <grp.h>
28 #include <inttypes.h>
29 #include <mntent.h>
30 #include <paths.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <sys/capability.h>
34 #include <sys/personality.h>
35 #include <sys/prctl.h>
36 #include <sys/resource.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <sys/utsname.h>
40 #include <sys/wait.h>
41 #include <unistd.h>
42
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>
50
51 #include "core_jni_helpers.h"
52 #include "JNIHelp.h"
53 #include "ScopedLocalRef.h"
54 #include "ScopedPrimitiveArray.h"
55 #include "ScopedUtfChars.h"
56
57 #include "nativebridge/native_bridge.h"
58
59 namespace {
60
61 using android::String8;
62
63 static pid_t gSystemServerPid = 0;
64
65 static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
66 static jclass gZygoteClass;
67 static jmethodID gCallPostForkChildHooks;
68
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,
75 };
76
77 static void RuntimeAbort(JNIEnv* env) {
78   env->FatalError("RuntimeAbort");
79 }
80
81 // This signal handler is for zygote mode, since the zygote must reap its children
82 static void SigChldHandler(int /*signal_number*/) {
83   pid_t pid;
84   int status;
85
86   // It's necessary to save and restore the errno during this function.
87   // Since errno is stored per thread, changing it here modifies the errno
88   // on the thread on which this signal handler executes. If a signal occurs
89   // between a call and an errno check, it's possible to get the errno set
90   // here.
91   // See b/23572286 for extra information.
92   int saved_errno = errno;
93
94   while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
95      // Log process-death status that we care about.  In general it is
96      // not safe to call LOG(...) from a signal handler because of
97      // possible reentrancy.  However, we know a priori that the
98      // current implementation of LOG() is safe to call from a SIGCHLD
99      // handler in the zygote process.  If the LOG() implementation
100      // changes its locking strategy or its use of syscalls within the
101      // lazy-init critical section, its use here may become unsafe.
102     if (WIFEXITED(status)) {
103       if (WEXITSTATUS(status)) {
104         ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
105       }
106     } else if (WIFSIGNALED(status)) {
107       if (WTERMSIG(status) != SIGKILL) {
108         ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
109       }
110       if (WCOREDUMP(status)) {
111         ALOGI("Process %d dumped core.", pid);
112       }
113     }
114
115     // If the just-crashed process is the system_server, bring down zygote
116     // so that it is restarted by init and system server will be restarted
117     // from there.
118     if (pid == gSystemServerPid) {
119       ALOGE("Exit zygote because system server (%d) has terminated", pid);
120       kill(getpid(), SIGKILL);
121     }
122   }
123
124   // Note that we shouldn't consider ECHILD an error because
125   // the secondary zygote might have no children left to wait for.
126   if (pid < 0 && errno != ECHILD) {
127     ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
128   }
129
130   errno = saved_errno;
131 }
132
133 // Configures the SIGCHLD handler for the zygote process. This is configured
134 // very late, because earlier in the runtime we may fork() and exec()
135 // other processes, and we want to waitpid() for those rather than
136 // have them be harvested immediately.
137 //
138 // This ends up being called repeatedly before each fork(), but there's
139 // no real harm in that.
140 static void SetSigChldHandler() {
141   struct sigaction sa;
142   memset(&sa, 0, sizeof(sa));
143   sa.sa_handler = SigChldHandler;
144
145   int err = sigaction(SIGCHLD, &sa, NULL);
146   if (err < 0) {
147     ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
148   }
149 }
150
151 // Sets the SIGCHLD handler back to default behavior in zygote children.
152 static void UnsetSigChldHandler() {
153   struct sigaction sa;
154   memset(&sa, 0, sizeof(sa));
155   sa.sa_handler = SIG_DFL;
156
157   int err = sigaction(SIGCHLD, &sa, NULL);
158   if (err < 0) {
159     ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
160   }
161 }
162
163 // Calls POSIX setgroups() using the int[] object as an argument.
164 // A NULL argument is tolerated.
165 static void SetGids(JNIEnv* env, jintArray javaGids) {
166   if (javaGids == NULL) {
167     return;
168   }
169
170   ScopedIntArrayRO gids(env, javaGids);
171   if (gids.get() == NULL) {
172       RuntimeAbort(env);
173   }
174   int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
175   if (rc == -1) {
176     ALOGE("setgroups failed");
177     RuntimeAbort(env);
178   }
179 }
180
181 // Sets the resource limits via setrlimit(2) for the values in the
182 // two-dimensional array of integers that's passed in. The second dimension
183 // contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
184 // treated as an empty array.
185 static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
186   if (javaRlimits == NULL) {
187     return;
188   }
189
190   rlimit rlim;
191   memset(&rlim, 0, sizeof(rlim));
192
193   for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
194     ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
195     ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
196     if (javaRlimit.size() != 3) {
197       ALOGE("rlimits array must have a second dimension of size 3");
198       RuntimeAbort(env);
199     }
200
201     rlim.rlim_cur = javaRlimit[1];
202     rlim.rlim_max = javaRlimit[2];
203
204     int rc = setrlimit(javaRlimit[0], &rlim);
205     if (rc == -1) {
206       ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
207             rlim.rlim_max);
208       RuntimeAbort(env);
209     }
210   }
211 }
212
213 // The debug malloc library needs to know whether it's the zygote or a child.
214 extern "C" int gMallocLeakZygoteChild;
215
216 static void EnableKeepCapabilities(JNIEnv* env) {
217   int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
218   if (rc == -1) {
219     ALOGE("prctl(PR_SET_KEEPCAPS) failed");
220     RuntimeAbort(env);
221   }
222 }
223
224 static void DropCapabilitiesBoundingSet(JNIEnv* env) {
225   for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
226     int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
227     if (rc == -1) {
228       if (errno == EINVAL) {
229         ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
230               "your kernel is compiled with file capabilities support");
231       } else {
232         ALOGE("prctl(PR_CAPBSET_DROP) failed");
233         RuntimeAbort(env);
234       }
235     }
236   }
237 }
238
239 static 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) {
253     ALOGE("capset(%" PRId64 ", %" PRId64 ") failed", permitted, effective);
254     RuntimeAbort(env);
255   }
256 }
257
258 static 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");
262     RuntimeAbort(env);
263   }
264 }
265
266 static 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
294 // Create a private mount namespace and bind mount appropriate emulated
295 // storage for the given user.
296 static 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
300     // Create a second private mount namespace for our process
301     if (unshare(CLONE_NEWNS) == -1) {
302         ALOGW("Failed to unshare(): %s", strerror(errno));
303         return false;
304     }
305
306     String8 storageSource;
307     if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
308         storageSource = "/mnt/runtime/default";
309     } else if (mount_mode == MOUNT_EXTERNAL_READ) {
310         storageSource = "/mnt/runtime/read";
311     } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
312         storageSource = "/mnt/runtime/write";
313     } else {
314         // Sane default of no storage visible
315         return true;
316     }
317     if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
318             NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
319         ALOGW("Failed to mount %s to /storage: %s", storageSource.string(), strerror(errno));
320         return false;
321     }
322
323     // Mount user-specific symlink helper into place
324     userid_t user_id = multiuser_get_user_id(uid);
325     const String8 userSource(String8::format("/mnt/user/%d", user_id));
326     if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
327         return false;
328     }
329     if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
330             NULL, MS_BIND, NULL)) == -1) {
331         ALOGW("Failed to mount %s to /storage/self: %s", userSource.string(), strerror(errno));
332         return false;
333     }
334
335     return true;
336 }
337
338 static bool NeedsNoRandomizeWorkaround() {
339 #if !defined(__arm__)
340     return false;
341 #else
342     int major;
343     int minor;
344     struct utsname uts;
345     if (uname(&uts) == -1) {
346         return false;
347     }
348
349     if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
350         return false;
351     }
352
353     // Kernels before 3.4.* need the workaround.
354     return (major < 3) || ((major == 3) && (minor < 4));
355 #endif
356 }
357
358 // Utility to close down the Zygote socket file descriptors while
359 // the child is still running as root with Zygote's privileges.  Each
360 // descriptor (if any) is closed via dup2(), replacing it with a valid
361 // (open) descriptor to /dev/null.
362
363 static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
364   if (!fdsToClose) {
365     return;
366   }
367   jsize count = env->GetArrayLength(fdsToClose);
368   jint *ar = env->GetIntArrayElements(fdsToClose, 0);
369   if (!ar) {
370       ALOGE("Bad fd array");
371       RuntimeAbort(env);
372   }
373   jsize i;
374   int devnull;
375   for (i = 0; i < count; i++) {
376     devnull = open("/dev/null", O_RDWR);
377     if (devnull < 0) {
378       ALOGE("Failed to open /dev/null: %s", strerror(errno));
379       RuntimeAbort(env);
380       continue;
381     }
382     ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
383     if (dup2(devnull, ar[i]) < 0) {
384       ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
385       RuntimeAbort(env);
386     }
387     close(devnull);
388   }
389 }
390
391 void 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) {
414     ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
415   }
416 }
417
418 #ifdef ENABLE_SCHED_BOOST
419 static 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
439 // Utility routine to fork zygote and specialize the child process.
440 static 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,
445                                      bool is_system_server, jintArray fdsToClose,
446                                      jstring instructionSet, jstring dataDir) {
447   SetSigChldHandler();
448
449 #ifdef ENABLE_SCHED_BOOST
450   SetForkLoad(true);
451 #endif
452
453   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 #ifdef _COMPATIBILITY_ENHANCEMENT_PACKAGE_
469     bool use_native_bridge = !is_system_server && android::NativeBridgeAvailable();
470 #else
471     bool use_native_bridge = !is_system_server && (instructionSet != NULL)
472             && android::NativeBridgeAvailable();
473 #endif
474     if (use_native_bridge) {
475 #ifdef _COMPATIBILITY_ENHANCEMENT_PACKAGE_
476       if (instructionSet != NULL) {
477         ScopedUtfChars isa_string(env, instructionSet);
478         use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
479       } else {
480       use_native_bridge = android::NeedsNativeBridge(NULL);
481       instructionSet = env->NewStringUTF("arm"
482 #ifdef __LP64__
483           "64"
484 #endif
485         );
486      }
487 #else
488       ScopedUtfChars isa_string(env, instructionSet);
489       use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
490 #endif
491      }
492
493 #ifndef _COMPATIBILITY_ENHANCEMENT_PACKAGE_
494     if (use_native_bridge && dataDir == NULL) {
495         // dataDir should never be null if we need to use a native bridge.
496         // In general, dataDir will never be null for normal applications. It can only happen in
497         // special cases (for isolated processes which are not associated with any app). These are
498         // launched by the framework and should not be emulated anyway.
499         use_native_bridge = false;
500         ALOGW("Native bridge will not be used because dataDir == NULL.");
501     }
502 #endif
503
504     if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
505       ALOGW("Failed to mount emulated storage: %s", strerror(errno));
506       if (errno == ENOTCONN || errno == EROFS) {
507         // When device is actively encrypting, we get ENOTCONN here
508         // since FUSE was mounted before the framework restarted.
509         // When encrypted device is booting, we get EROFS since
510         // FUSE hasn't been created yet by init.
511         // In either case, continue without external storage.
512       } else {
513         ALOGE("Cannot continue without emulated storage");
514         RuntimeAbort(env);
515       }
516     }
517
518     if (!is_system_server) {
519         int rc = createProcessGroup(uid, getpid());
520         if (rc != 0) {
521             if (rc == -EROFS) {
522                 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
523             } else {
524                 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
525             }
526         }
527     }
528
529     SetGids(env, javaGids);
530
531     SetRLimits(env, javaRlimits);
532
533     if (use_native_bridge) {
534       ScopedUtfChars isa_string(env, instructionSet);
535 #ifdef _COMPATIBILITY_ENHANCEMENT_PACKAGE_
536       if (dataDir != NULL) {
537 #endif
538           ScopedUtfChars data_dir(env, dataDir);
539           android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
540 #ifdef _COMPATIBILITY_ENHANCEMENT_PACKAGE_
541       } else {
542           android::PreInitializeNativeBridge(NULL, isa_string.c_str());
543       }
544 #endif
545     }
546
547     int rc = setresgid(gid, gid, gid);
548     if (rc == -1) {
549       ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
550       RuntimeAbort(env);
551     }
552
553     rc = setresuid(uid, uid, uid);
554     if (rc == -1) {
555       ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
556       RuntimeAbort(env);
557     }
558
559     if (NeedsNoRandomizeWorkaround()) {
560         // Work around ARM kernel ASLR lossage (http://b/5817320).
561         int old_personality = personality(0xffffffff);
562         int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
563         if (new_personality == -1) {
564             ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
565         }
566     }
567
568     SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
569
570     SetSchedulerPolicy(env);
571
572     const char* se_info_c_str = NULL;
573     ScopedUtfChars* se_info = NULL;
574     if (java_se_info != NULL) {
575         se_info = new ScopedUtfChars(env, java_se_info);
576         se_info_c_str = se_info->c_str();
577         if (se_info_c_str == NULL) {
578           ALOGE("se_info_c_str == NULL");
579           RuntimeAbort(env);
580         }
581     }
582     const char* se_name_c_str = NULL;
583     ScopedUtfChars* se_name = NULL;
584     if (java_se_name != NULL) {
585         se_name = new ScopedUtfChars(env, java_se_name);
586         se_name_c_str = se_name->c_str();
587         if (se_name_c_str == NULL) {
588           ALOGE("se_name_c_str == NULL");
589           RuntimeAbort(env);
590         }
591     }
592     rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
593     if (rc == -1) {
594       ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
595             is_system_server, se_info_c_str, se_name_c_str);
596       RuntimeAbort(env);
597     }
598
599     // Make it easier to debug audit logs by setting the main thread's name to the
600     // nice name rather than "app_process".
601     if (se_info_c_str == NULL && is_system_server) {
602       se_name_c_str = "system_server";
603     }
604     if (se_info_c_str != NULL) {
605       SetThreadName(se_name_c_str);
606     }
607
608     delete se_info;
609     delete se_name;
610
611     UnsetSigChldHandler();
612
613     env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
614                               is_system_server ? NULL : instructionSet);
615     if (env->ExceptionCheck()) {
616       ALOGE("Error calling post fork hooks.");
617       RuntimeAbort(env);
618     }
619   } else if (pid > 0) {
620     // the parent process
621
622 #ifdef ENABLE_SCHED_BOOST
623     // unset scheduler knob
624     SetForkLoad(false);
625 #endif
626
627   }
628   return pid;
629 }
630 }  // anonymous namespace
631
632 namespace android {
633
634 static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
635         JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
636         jint debug_flags, jobjectArray rlimits,
637         jint mount_external, jstring se_info, jstring se_name,
638         jintArray fdsToClose, jstring instructionSet, jstring appDataDir) {
639     // Grant CAP_WAKE_ALARM to the Bluetooth process.
640     jlong capabilities = 0;
641     if (uid == AID_BLUETOOTH) {
642         capabilities |= (1LL << CAP_WAKE_ALARM);
643     }
644
645     return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
646             rlimits, capabilities, capabilities, mount_external, se_info,
647             se_name, false, fdsToClose, instructionSet, appDataDir);
648 }
649
650 static jint com_android_internal_os_Zygote_nativeForkSystemServer(
651         JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
652         jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
653         jlong effectiveCapabilities) {
654   pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
655                                       debug_flags, rlimits,
656                                       permittedCapabilities, effectiveCapabilities,
657                                       MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
658                                       NULL, NULL);
659   if (pid > 0) {
660       // The zygote process checks whether the child process has died or not.
661       ALOGI("System server process %d has been created", pid);
662       gSystemServerPid = pid;
663       // There is a slight window that the system server process has crashed
664       // but it went unnoticed because we haven't published its pid yet. So
665       // we recheck here just to make sure that all is well.
666       int status;
667       if (waitpid(pid, &status, WNOHANG) == pid) {
668           ALOGE("System server process %d has died. Restarting Zygote!", pid);
669           RuntimeAbort(env);
670       }
671   }
672   return pid;
673 }
674
675 static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
676     // Zygote process unmount root storage space initially before every child processes are forked.
677     // Every forked child processes (include SystemServer) only mount their own root storage space
678     // And no need unmount storage operation in MountEmulatedStorage method.
679     // Zygote process does not utilize root storage spaces and unshared its mount namespace from the ART.
680
681     UnmountTree("/storage");
682     return;
683 }
684
685 static JNINativeMethod gMethods[] = {
686     { "nativeForkAndSpecialize",
687       "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I",
688       (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
689     { "nativeForkSystemServer", "(II[II[[IJJ)I",
690       (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
691     { "nativeUnmountStorageOnInit", "()V",
692       (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit }
693 };
694
695 int register_com_android_internal_os_Zygote(JNIEnv* env) {
696   gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
697   gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
698                                                    "(ILjava/lang/String;)V");
699
700   return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
701 }
702 }  // namespace android
703