blob: f7cfe0ec31daa1c2352421d6670573ad71cc37a5 [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
Colin Cross18cd9f52014-06-13 12:58:55 -070023#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080024#include <grp.h>
25#include <inttypes.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010026#include <paths.h>
27#include <signal.h>
28#include <stdlib.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>
Dan Albert46d84442014-11-18 16:07:51 -080037#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070038
39#include <cutils/fs.h>
40#include <cutils/multiuser.h>
41#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070042#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070043#include <utils/String8.h>
44#include <selinux/android.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070045#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070046
Andreas Gampeed6b9df2014-11-20 22:02:20 -080047#include "core_jni_helpers.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010048#include "JNIHelp.h"
49#include "ScopedLocalRef.h"
50#include "ScopedPrimitiveArray.h"
51#include "ScopedUtfChars.h"
52
jgu212eacd062014-09-10 06:55:07 -040053#include "nativebridge/native_bridge.h"
54
Narayan Kamath973b4662014-03-31 13:41:26 +010055namespace {
56
57using android::String8;
58
59static pid_t gSystemServerPid = 0;
60
61static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
62static jclass gZygoteClass;
63static jmethodID gCallPostForkChildHooks;
64
65// Must match values in com.android.internal.os.Zygote.
66enum MountExternalKind {
67 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070068 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -070069 MOUNT_EXTERNAL_READ = 2,
70 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +010071};
72
73static void RuntimeAbort(JNIEnv* env) {
74 env->FatalError("RuntimeAbort");
75}
76
77// This signal handler is for zygote mode, since the zygote must reap its children
78static void SigChldHandler(int /*signal_number*/) {
79 pid_t pid;
80 int status;
81
82 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
83 // Log process-death status that we care about. In general it is
84 // not safe to call LOG(...) from a signal handler because of
85 // possible reentrancy. However, we know a priori that the
86 // current implementation of LOG() is safe to call from a SIGCHLD
87 // handler in the zygote process. If the LOG() implementation
88 // changes its locking strategy or its use of syscalls within the
89 // lazy-init critical section, its use here may become unsafe.
90 if (WIFEXITED(status)) {
91 if (WEXITSTATUS(status)) {
92 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +010093 }
94 } else if (WIFSIGNALED(status)) {
95 if (WTERMSIG(status) != SIGKILL) {
Narayan Kamath160992d2014-04-14 14:46:07 +010096 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +010097 }
Narayan Kamath973b4662014-03-31 13:41:26 +010098 if (WCOREDUMP(status)) {
99 ALOGI("Process %d dumped core.", pid);
100 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100101 }
102
103 // If the just-crashed process is the system_server, bring down zygote
104 // so that it is restarted by init and system server will be restarted
105 // from there.
106 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800107 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100108 kill(getpid(), SIGKILL);
109 }
110 }
111
Narayan Kamath160992d2014-04-14 14:46:07 +0100112 // Note that we shouldn't consider ECHILD an error because
113 // the secondary zygote might have no children left to wait for.
114 if (pid < 0 && errno != ECHILD) {
115 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100116 }
117}
118
119// Configures the SIGCHLD handler for the zygote process. This is configured
120// very late, because earlier in the runtime we may fork() and exec()
121// other processes, and we want to waitpid() for those rather than
122// have them be harvested immediately.
123//
124// This ends up being called repeatedly before each fork(), but there's
125// no real harm in that.
126static void SetSigChldHandler() {
127 struct sigaction sa;
128 memset(&sa, 0, sizeof(sa));
129 sa.sa_handler = SigChldHandler;
130
131 int err = sigaction(SIGCHLD, &sa, NULL);
132 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700133 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100134 }
135}
136
137// Sets the SIGCHLD handler back to default behavior in zygote children.
138static void UnsetSigChldHandler() {
139 struct sigaction sa;
140 memset(&sa, 0, sizeof(sa));
141 sa.sa_handler = SIG_DFL;
142
143 int err = sigaction(SIGCHLD, &sa, NULL);
144 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700145 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100146 }
147}
148
149// Calls POSIX setgroups() using the int[] object as an argument.
150// A NULL argument is tolerated.
151static void SetGids(JNIEnv* env, jintArray javaGids) {
152 if (javaGids == NULL) {
153 return;
154 }
155
156 ScopedIntArrayRO gids(env, javaGids);
157 if (gids.get() == NULL) {
158 RuntimeAbort(env);
159 }
160 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
161 if (rc == -1) {
162 ALOGE("setgroups failed");
163 RuntimeAbort(env);
164 }
165}
166
167// Sets the resource limits via setrlimit(2) for the values in the
168// two-dimensional array of integers that's passed in. The second dimension
169// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
170// treated as an empty array.
171static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
172 if (javaRlimits == NULL) {
173 return;
174 }
175
176 rlimit rlim;
177 memset(&rlim, 0, sizeof(rlim));
178
179 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
180 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
181 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
182 if (javaRlimit.size() != 3) {
183 ALOGE("rlimits array must have a second dimension of size 3");
184 RuntimeAbort(env);
185 }
186
187 rlim.rlim_cur = javaRlimit[1];
188 rlim.rlim_max = javaRlimit[2];
189
190 int rc = setrlimit(javaRlimit[0], &rlim);
191 if (rc == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800192 ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
193 rlim.rlim_max);
Narayan Kamath973b4662014-03-31 13:41:26 +0100194 RuntimeAbort(env);
195 }
196 }
197}
198
Narayan Kamath973b4662014-03-31 13:41:26 +0100199// The debug malloc library needs to know whether it's the zygote or a child.
200extern "C" int gMallocLeakZygoteChild;
201
202static void EnableKeepCapabilities(JNIEnv* env) {
203 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
204 if (rc == -1) {
205 ALOGE("prctl(PR_SET_KEEPCAPS) failed");
206 RuntimeAbort(env);
207 }
208}
209
210static void DropCapabilitiesBoundingSet(JNIEnv* env) {
211 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
212 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
213 if (rc == -1) {
214 if (errno == EINVAL) {
215 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
216 "your kernel is compiled with file capabilities support");
217 } else {
218 ALOGE("prctl(PR_CAPBSET_DROP) failed");
219 RuntimeAbort(env);
220 }
221 }
222 }
223}
224
225static void SetCapabilities(JNIEnv* env, int64_t permitted, int64_t effective) {
226 __user_cap_header_struct capheader;
227 memset(&capheader, 0, sizeof(capheader));
228 capheader.version = _LINUX_CAPABILITY_VERSION_3;
229 capheader.pid = 0;
230
231 __user_cap_data_struct capdata[2];
232 memset(&capdata, 0, sizeof(capdata));
233 capdata[0].effective = effective;
234 capdata[1].effective = effective >> 32;
235 capdata[0].permitted = permitted;
236 capdata[1].permitted = permitted >> 32;
237
238 if (capset(&capheader, &capdata[0]) == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800239 ALOGE("capset(%" PRId64 ", %" PRId64 ") failed", permitted, effective);
Narayan Kamath973b4662014-03-31 13:41:26 +0100240 RuntimeAbort(env);
241 }
242}
243
244static void SetSchedulerPolicy(JNIEnv* env) {
245 errno = -set_sched_policy(0, SP_DEFAULT);
246 if (errno != 0) {
247 ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
248 RuntimeAbort(env);
249 }
250}
251
Narayan Kamath973b4662014-03-31 13:41:26 +0100252// Create a private mount namespace and bind mount appropriate emulated
253// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700254static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
255 bool force_mount_namespace) {
256 // See storage config details at http://source.android.com/tech/storage/
257
258 // Create a second private mount namespace for our process
259 if (unshare(CLONE_NEWNS) == -1) {
260 ALOGW("Failed to unshare(): %s", strerror(errno));
261 return false;
262 }
263
264 // Unmount storage provided by root namespace and mount requested view
265 umount2("/storage", MNT_FORCE);
266
267 String8 storageSource;
268 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
269 storageSource = "/mnt/runtime_default";
270 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
271 storageSource = "/mnt/runtime_read";
272 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
273 storageSource = "/mnt/runtime_write";
274 } else {
275 // Sane default of no storage visible
276 return true;
277 }
278 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
279 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
280 ALOGW("Failed to mount %s to /storage: %s", storageSource.string(), strerror(errno));
281 return false;
282 }
283
284 // Mount user-specific symlink helpers into place
285 userid_t user_id = multiuser_get_user_id(uid);
286 const String8 userSource(String8::format("/mnt/user/%d", user_id));
287 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
288 return false;
289 }
290 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
291 NULL, MS_BIND, NULL)) == -1) {
292 ALOGW("Failed to mount %s to /storage/self: %s", userSource.string(), strerror(errno));
293 return false;
294 }
295
Narayan Kamath973b4662014-03-31 13:41:26 +0100296 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100297}
298
Narayan Kamath973b4662014-03-31 13:41:26 +0100299static bool NeedsNoRandomizeWorkaround() {
300#if !defined(__arm__)
301 return false;
302#else
303 int major;
304 int minor;
305 struct utsname uts;
306 if (uname(&uts) == -1) {
307 return false;
308 }
309
310 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
311 return false;
312 }
313
314 // Kernels before 3.4.* need the workaround.
315 return (major < 3) || ((major == 3) && (minor < 4));
316#endif
317}
Narayan Kamath973b4662014-03-31 13:41:26 +0100318
319// Utility to close down the Zygote socket file descriptors while
320// the child is still running as root with Zygote's privileges. Each
321// descriptor (if any) is closed via dup2(), replacing it with a valid
322// (open) descriptor to /dev/null.
323
324static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
325 if (!fdsToClose) {
326 return;
327 }
328 jsize count = env->GetArrayLength(fdsToClose);
329 jint *ar = env->GetIntArrayElements(fdsToClose, 0);
330 if (!ar) {
331 ALOGE("Bad fd array");
332 RuntimeAbort(env);
333 }
334 jsize i;
335 int devnull;
336 for (i = 0; i < count; i++) {
337 devnull = open("/dev/null", O_RDWR);
338 if (devnull < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700339 ALOGE("Failed to open /dev/null: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100340 RuntimeAbort(env);
341 continue;
342 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700343 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100344 if (dup2(devnull, ar[i]) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700345 ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100346 RuntimeAbort(env);
347 }
348 close(devnull);
349 }
350}
351
352void SetThreadName(const char* thread_name) {
353 bool hasAt = false;
354 bool hasDot = false;
355 const char* s = thread_name;
356 while (*s) {
357 if (*s == '.') {
358 hasDot = true;
359 } else if (*s == '@') {
360 hasAt = true;
361 }
362 s++;
363 }
364 const int len = s - thread_name;
365 if (len < 15 || hasAt || !hasDot) {
366 s = thread_name;
367 } else {
368 s = thread_name + len - 15;
369 }
370 // pthread_setname_np fails rather than truncating long strings.
371 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
372 strlcpy(buf, s, sizeof(buf)-1);
373 errno = pthread_setname_np(pthread_self(), buf);
374 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700375 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100376 }
377}
378
379// Utility routine to fork zygote and specialize the child process.
380static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
381 jint debug_flags, jobjectArray javaRlimits,
382 jlong permittedCapabilities, jlong effectiveCapabilities,
383 jint mount_external,
384 jstring java_se_info, jstring java_se_name,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700385 bool is_system_server, jintArray fdsToClose,
jgu212eacd062014-09-10 06:55:07 -0400386 jstring instructionSet, jstring dataDir) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100387 SetSigChldHandler();
388
389 pid_t pid = fork();
390
391 if (pid == 0) {
392 // The child process.
393 gMallocLeakZygoteChild = 1;
394
395 // Clean up any descriptors which must be closed immediately
396 DetachDescriptors(env, fdsToClose);
397
398 // Keep capabilities across UID change, unless we're staying root.
399 if (uid != 0) {
400 EnableKeepCapabilities(env);
401 }
402
403 DropCapabilitiesBoundingSet(env);
404
Calin Juravle79ec4c12014-10-24 16:16:49 +0100405 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
406 && android::NativeBridgeAvailable();
407 if (use_native_bridge) {
jgu212eacd062014-09-10 06:55:07 -0400408 ScopedUtfChars isa_string(env, instructionSet);
Calin Juravle79ec4c12014-10-24 16:16:49 +0100409 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400410 }
Calin Juravle6a4d2362014-10-28 12:16:21 +0000411 if (use_native_bridge && dataDir == NULL) {
412 // dataDir should never be null if we need to use a native bridge.
413 // In general, dataDir will never be null for normal applications. It can only happen in
414 // special cases (for isolated processes which are not associated with any app). These are
415 // launched by the framework and should not be emulated anyway.
416 use_native_bridge = false;
417 ALOGW("Native bridge will not be used because dataDir == NULL.");
418 }
jgu212eacd062014-09-10 06:55:07 -0400419
Calin Juravle79ec4c12014-10-24 16:16:49 +0100420 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700421 ALOGW("Failed to mount emulated storage: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100422 if (errno == ENOTCONN || errno == EROFS) {
423 // When device is actively encrypting, we get ENOTCONN here
424 // since FUSE was mounted before the framework restarted.
425 // When encrypted device is booting, we get EROFS since
426 // FUSE hasn't been created yet by init.
427 // In either case, continue without external storage.
428 } else {
429 ALOGE("Cannot continue without emulated storage");
430 RuntimeAbort(env);
431 }
432 }
433
Colin Cross0161bbc2014-06-03 13:26:58 -0700434 if (!is_system_server) {
435 int rc = createProcessGroup(uid, getpid());
436 if (rc != 0) {
Colin Cross3089bed2014-07-14 15:07:04 -0700437 if (rc == -EROFS) {
438 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
439 } else {
440 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
441 }
Colin Cross0161bbc2014-06-03 13:26:58 -0700442 }
443 }
444
Narayan Kamath973b4662014-03-31 13:41:26 +0100445 SetGids(env, javaGids);
446
447 SetRLimits(env, javaRlimits);
448
Calin Juravle79ec4c12014-10-24 16:16:49 +0100449 if (use_native_bridge) {
450 ScopedUtfChars isa_string(env, instructionSet);
451 ScopedUtfChars data_dir(env, dataDir);
452 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400453 }
454
Narayan Kamath973b4662014-03-31 13:41:26 +0100455 int rc = setresgid(gid, gid, gid);
456 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700457 ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100458 RuntimeAbort(env);
459 }
460
461 rc = setresuid(uid, uid, uid);
462 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700463 ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100464 RuntimeAbort(env);
465 }
466
Narayan Kamath973b4662014-03-31 13:41:26 +0100467 if (NeedsNoRandomizeWorkaround()) {
468 // Work around ARM kernel ASLR lossage (http://b/5817320).
469 int old_personality = personality(0xffffffff);
470 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
471 if (new_personality == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700472 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100473 }
474 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100475
476 SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
477
478 SetSchedulerPolicy(env);
479
Colin Cross18cd9f52014-06-13 12:58:55 -0700480 const char* se_info_c_str = NULL;
481 ScopedUtfChars* se_info = NULL;
482 if (java_se_info != NULL) {
483 se_info = new ScopedUtfChars(env, java_se_info);
484 se_info_c_str = se_info->c_str();
485 if (se_info_c_str == NULL) {
486 ALOGE("se_info_c_str == NULL");
487 RuntimeAbort(env);
488 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100489 }
Colin Cross18cd9f52014-06-13 12:58:55 -0700490 const char* se_name_c_str = NULL;
491 ScopedUtfChars* se_name = NULL;
492 if (java_se_name != NULL) {
493 se_name = new ScopedUtfChars(env, java_se_name);
494 se_name_c_str = se_name->c_str();
495 if (se_name_c_str == NULL) {
496 ALOGE("se_name_c_str == NULL");
497 RuntimeAbort(env);
498 }
499 }
500 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
501 if (rc == -1) {
502 ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
503 is_system_server, se_info_c_str, se_name_c_str);
504 RuntimeAbort(env);
505 }
506
507 // Make it easier to debug audit logs by setting the main thread's name to the
508 // nice name rather than "app_process".
509 if (se_info_c_str == NULL && is_system_server) {
510 se_name_c_str = "system_server";
511 }
512 if (se_info_c_str != NULL) {
513 SetThreadName(se_name_c_str);
514 }
515
516 delete se_info;
517 delete se_name;
Narayan Kamath973b4662014-03-31 13:41:26 +0100518
519 UnsetSigChldHandler();
520
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700521 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
522 is_system_server ? NULL : instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100523 if (env->ExceptionCheck()) {
524 ALOGE("Error calling post fork hooks.");
525 RuntimeAbort(env);
526 }
527 } else if (pid > 0) {
528 // the parent process
529 }
530 return pid;
531}
532} // anonymous namespace
533
534namespace android {
535
536static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
537 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
538 jint debug_flags, jobjectArray rlimits,
539 jint mount_external, jstring se_info, jstring se_name,
jgu212eacd062014-09-10 06:55:07 -0400540 jintArray fdsToClose, jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700541 // Grant CAP_WAKE_ALARM to the Bluetooth process.
542 jlong capabilities = 0;
543 if (uid == AID_BLUETOOTH) {
544 capabilities |= (1LL << CAP_WAKE_ALARM);
545 }
546
Narayan Kamath973b4662014-03-31 13:41:26 +0100547 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700548 rlimits, capabilities, capabilities, mount_external, se_info,
Andreas Gampea103ebe2014-09-24 15:37:53 -0700549 se_name, false, fdsToClose, instructionSet, appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100550}
551
552static jint com_android_internal_os_Zygote_nativeForkSystemServer(
553 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
554 jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
555 jlong effectiveCapabilities) {
556 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
557 debug_flags, rlimits,
558 permittedCapabilities, effectiveCapabilities,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700559 MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
jgu212eacd062014-09-10 06:55:07 -0400560 NULL, NULL);
Narayan Kamath973b4662014-03-31 13:41:26 +0100561 if (pid > 0) {
562 // The zygote process checks whether the child process has died or not.
563 ALOGI("System server process %d has been created", pid);
564 gSystemServerPid = pid;
565 // There is a slight window that the system server process has crashed
566 // but it went unnoticed because we haven't published its pid yet. So
567 // we recheck here just to make sure that all is well.
568 int status;
569 if (waitpid(pid, &status, WNOHANG) == pid) {
570 ALOGE("System server process %d has died. Restarting Zygote!", pid);
571 RuntimeAbort(env);
572 }
573 }
574 return pid;
575}
576
577static JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700578 { "nativeForkAndSpecialize",
jgu212eacd062014-09-10 06:55:07 -0400579 "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +0100580 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
581 { "nativeForkSystemServer", "(II[II[[IJJ)I",
582 (void *) com_android_internal_os_Zygote_nativeForkSystemServer }
583};
584
585int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800586 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
587 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700588 "(ILjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +0100589
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800590 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +0100591}
592} // namespace android
593