blob: 76db5d354c8cb097f9a72771acf53dd058ac931a [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,
Narayan Kamath973b4662014-03-31 13:41:26 +010069};
70
71static void RuntimeAbort(JNIEnv* env) {
72 env->FatalError("RuntimeAbort");
73}
74
75// This signal handler is for zygote mode, since the zygote must reap its children
76static void SigChldHandler(int /*signal_number*/) {
77 pid_t pid;
78 int status;
79
80 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
81 // Log process-death status that we care about. In general it is
82 // not safe to call LOG(...) from a signal handler because of
83 // possible reentrancy. However, we know a priori that the
84 // current implementation of LOG() is safe to call from a SIGCHLD
85 // handler in the zygote process. If the LOG() implementation
86 // changes its locking strategy or its use of syscalls within the
87 // lazy-init critical section, its use here may become unsafe.
88 if (WIFEXITED(status)) {
89 if (WEXITSTATUS(status)) {
90 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +010091 }
92 } else if (WIFSIGNALED(status)) {
93 if (WTERMSIG(status) != SIGKILL) {
Narayan Kamath160992d2014-04-14 14:46:07 +010094 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +010095 }
Narayan Kamath973b4662014-03-31 13:41:26 +010096 if (WCOREDUMP(status)) {
97 ALOGI("Process %d dumped core.", pid);
98 }
Narayan Kamath973b4662014-03-31 13:41:26 +010099 }
100
101 // If the just-crashed process is the system_server, bring down zygote
102 // so that it is restarted by init and system server will be restarted
103 // from there.
104 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800105 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100106 kill(getpid(), SIGKILL);
107 }
108 }
109
Narayan Kamath160992d2014-04-14 14:46:07 +0100110 // Note that we shouldn't consider ECHILD an error because
111 // the secondary zygote might have no children left to wait for.
112 if (pid < 0 && errno != ECHILD) {
113 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100114 }
115}
116
117// Configures the SIGCHLD handler for the zygote process. This is configured
118// very late, because earlier in the runtime we may fork() and exec()
119// other processes, and we want to waitpid() for those rather than
120// have them be harvested immediately.
121//
122// This ends up being called repeatedly before each fork(), but there's
123// no real harm in that.
124static void SetSigChldHandler() {
125 struct sigaction sa;
126 memset(&sa, 0, sizeof(sa));
127 sa.sa_handler = SigChldHandler;
128
129 int err = sigaction(SIGCHLD, &sa, NULL);
130 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700131 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100132 }
133}
134
135// Sets the SIGCHLD handler back to default behavior in zygote children.
136static void UnsetSigChldHandler() {
137 struct sigaction sa;
138 memset(&sa, 0, sizeof(sa));
139 sa.sa_handler = SIG_DFL;
140
141 int err = sigaction(SIGCHLD, &sa, NULL);
142 if (err < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700143 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100144 }
145}
146
147// Calls POSIX setgroups() using the int[] object as an argument.
148// A NULL argument is tolerated.
149static void SetGids(JNIEnv* env, jintArray javaGids) {
150 if (javaGids == NULL) {
151 return;
152 }
153
154 ScopedIntArrayRO gids(env, javaGids);
155 if (gids.get() == NULL) {
156 RuntimeAbort(env);
157 }
158 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
159 if (rc == -1) {
160 ALOGE("setgroups failed");
161 RuntimeAbort(env);
162 }
163}
164
165// Sets the resource limits via setrlimit(2) for the values in the
166// two-dimensional array of integers that's passed in. The second dimension
167// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
168// treated as an empty array.
169static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
170 if (javaRlimits == NULL) {
171 return;
172 }
173
174 rlimit rlim;
175 memset(&rlim, 0, sizeof(rlim));
176
177 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
178 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
179 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
180 if (javaRlimit.size() != 3) {
181 ALOGE("rlimits array must have a second dimension of size 3");
182 RuntimeAbort(env);
183 }
184
185 rlim.rlim_cur = javaRlimit[1];
186 rlim.rlim_max = javaRlimit[2];
187
188 int rc = setrlimit(javaRlimit[0], &rlim);
189 if (rc == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800190 ALOGE("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
191 rlim.rlim_max);
Narayan Kamath973b4662014-03-31 13:41:26 +0100192 RuntimeAbort(env);
193 }
194 }
195}
196
Narayan Kamath973b4662014-03-31 13:41:26 +0100197// The debug malloc library needs to know whether it's the zygote or a child.
198extern "C" int gMallocLeakZygoteChild;
199
200static void EnableKeepCapabilities(JNIEnv* env) {
201 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
202 if (rc == -1) {
203 ALOGE("prctl(PR_SET_KEEPCAPS) failed");
204 RuntimeAbort(env);
205 }
206}
207
208static void DropCapabilitiesBoundingSet(JNIEnv* env) {
209 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
210 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
211 if (rc == -1) {
212 if (errno == EINVAL) {
213 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
214 "your kernel is compiled with file capabilities support");
215 } else {
216 ALOGE("prctl(PR_CAPBSET_DROP) failed");
217 RuntimeAbort(env);
218 }
219 }
220 }
221}
222
223static void SetCapabilities(JNIEnv* env, int64_t permitted, int64_t effective) {
224 __user_cap_header_struct capheader;
225 memset(&capheader, 0, sizeof(capheader));
226 capheader.version = _LINUX_CAPABILITY_VERSION_3;
227 capheader.pid = 0;
228
229 __user_cap_data_struct capdata[2];
230 memset(&capdata, 0, sizeof(capdata));
231 capdata[0].effective = effective;
232 capdata[1].effective = effective >> 32;
233 capdata[0].permitted = permitted;
234 capdata[1].permitted = permitted >> 32;
235
236 if (capset(&capheader, &capdata[0]) == -1) {
Dan Albert46d84442014-11-18 16:07:51 -0800237 ALOGE("capset(%" PRId64 ", %" PRId64 ") failed", permitted, effective);
Narayan Kamath973b4662014-03-31 13:41:26 +0100238 RuntimeAbort(env);
239 }
240}
241
242static void SetSchedulerPolicy(JNIEnv* env) {
243 errno = -set_sched_policy(0, SP_DEFAULT);
244 if (errno != 0) {
245 ALOGE("set_sched_policy(0, SP_DEFAULT) failed");
246 RuntimeAbort(env);
247 }
248}
249
Narayan Kamath973b4662014-03-31 13:41:26 +0100250// Create a private mount namespace and bind mount appropriate emulated
251// storage for the given user.
jgu212eacd062014-09-10 06:55:07 -0400252static bool MountEmulatedStorage(uid_t uid, jint mount_mode, bool force_mount_namespace) {
253 if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100254 return true;
255 }
256
Narayan Kamath973b4662014-03-31 13:41:26 +0100257 // Create a second private mount namespace for our process
258 if (unshare(CLONE_NEWNS) == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700259 ALOGW("Failed to unshare(): %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100260 return false;
261 }
262
jgu212eacd062014-09-10 06:55:07 -0400263 if (mount_mode == MOUNT_EXTERNAL_NONE) {
264 return true;
265 }
266
267 // See storage config details at http://source.android.com/tech/storage/
268 userid_t user_id = multiuser_get_user_id(uid);
269
Jeff Sharkey48877892015-03-18 11:27:19 -0700270 // Bind mount user-specific storage into place
271 const String8 source(String8::format("/mnt/user/%d", user_id));
272 const String8 target(String8::format("/storage/self"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100273
Jeff Sharkey48877892015-03-18 11:27:19 -0700274 if (fs_prepare_dir(source.string(), 0755, 0, 0) == -1) {
275 return false;
276 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100277
Jeff Sharkey48877892015-03-18 11:27:19 -0700278 if (TEMP_FAILURE_RETRY(mount(source.string(), target.string(), NULL, MS_BIND, NULL)) == -1) {
279 ALOGW("Failed to mount %s to %s: %s", source.string(), target.string(), strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100280 return false;
281 }
282
283 return true;
284}
285
Narayan Kamath973b4662014-03-31 13:41:26 +0100286static bool NeedsNoRandomizeWorkaround() {
287#if !defined(__arm__)
288 return false;
289#else
290 int major;
291 int minor;
292 struct utsname uts;
293 if (uname(&uts) == -1) {
294 return false;
295 }
296
297 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
298 return false;
299 }
300
301 // Kernels before 3.4.* need the workaround.
302 return (major < 3) || ((major == 3) && (minor < 4));
303#endif
304}
Narayan Kamath973b4662014-03-31 13:41:26 +0100305
306// Utility to close down the Zygote socket file descriptors while
307// the child is still running as root with Zygote's privileges. Each
308// descriptor (if any) is closed via dup2(), replacing it with a valid
309// (open) descriptor to /dev/null.
310
311static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
312 if (!fdsToClose) {
313 return;
314 }
315 jsize count = env->GetArrayLength(fdsToClose);
316 jint *ar = env->GetIntArrayElements(fdsToClose, 0);
317 if (!ar) {
318 ALOGE("Bad fd array");
319 RuntimeAbort(env);
320 }
321 jsize i;
322 int devnull;
323 for (i = 0; i < count; i++) {
324 devnull = open("/dev/null", O_RDWR);
325 if (devnull < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700326 ALOGE("Failed to open /dev/null: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100327 RuntimeAbort(env);
328 continue;
329 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700330 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100331 if (dup2(devnull, ar[i]) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700332 ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100333 RuntimeAbort(env);
334 }
335 close(devnull);
336 }
337}
338
339void SetThreadName(const char* thread_name) {
340 bool hasAt = false;
341 bool hasDot = false;
342 const char* s = thread_name;
343 while (*s) {
344 if (*s == '.') {
345 hasDot = true;
346 } else if (*s == '@') {
347 hasAt = true;
348 }
349 s++;
350 }
351 const int len = s - thread_name;
352 if (len < 15 || hasAt || !hasDot) {
353 s = thread_name;
354 } else {
355 s = thread_name + len - 15;
356 }
357 // pthread_setname_np fails rather than truncating long strings.
358 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
359 strlcpy(buf, s, sizeof(buf)-1);
360 errno = pthread_setname_np(pthread_self(), buf);
361 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700362 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100363 }
364}
365
366// Utility routine to fork zygote and specialize the child process.
367static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
368 jint debug_flags, jobjectArray javaRlimits,
369 jlong permittedCapabilities, jlong effectiveCapabilities,
370 jint mount_external,
371 jstring java_se_info, jstring java_se_name,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700372 bool is_system_server, jintArray fdsToClose,
jgu212eacd062014-09-10 06:55:07 -0400373 jstring instructionSet, jstring dataDir) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100374 SetSigChldHandler();
375
376 pid_t pid = fork();
377
378 if (pid == 0) {
379 // The child process.
380 gMallocLeakZygoteChild = 1;
381
382 // Clean up any descriptors which must be closed immediately
383 DetachDescriptors(env, fdsToClose);
384
385 // Keep capabilities across UID change, unless we're staying root.
386 if (uid != 0) {
387 EnableKeepCapabilities(env);
388 }
389
390 DropCapabilitiesBoundingSet(env);
391
Calin Juravle79ec4c12014-10-24 16:16:49 +0100392 bool use_native_bridge = !is_system_server && (instructionSet != NULL)
393 && android::NativeBridgeAvailable();
394 if (use_native_bridge) {
jgu212eacd062014-09-10 06:55:07 -0400395 ScopedUtfChars isa_string(env, instructionSet);
Calin Juravle79ec4c12014-10-24 16:16:49 +0100396 use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400397 }
Calin Juravle6a4d2362014-10-28 12:16:21 +0000398 if (use_native_bridge && dataDir == NULL) {
399 // dataDir should never be null if we need to use a native bridge.
400 // In general, dataDir will never be null for normal applications. It can only happen in
401 // special cases (for isolated processes which are not associated with any app). These are
402 // launched by the framework and should not be emulated anyway.
403 use_native_bridge = false;
404 ALOGW("Native bridge will not be used because dataDir == NULL.");
405 }
jgu212eacd062014-09-10 06:55:07 -0400406
Calin Juravle79ec4c12014-10-24 16:16:49 +0100407 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700408 ALOGW("Failed to mount emulated storage: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100409 if (errno == ENOTCONN || errno == EROFS) {
410 // When device is actively encrypting, we get ENOTCONN here
411 // since FUSE was mounted before the framework restarted.
412 // When encrypted device is booting, we get EROFS since
413 // FUSE hasn't been created yet by init.
414 // In either case, continue without external storage.
415 } else {
416 ALOGE("Cannot continue without emulated storage");
417 RuntimeAbort(env);
418 }
419 }
420
Colin Cross0161bbc2014-06-03 13:26:58 -0700421 if (!is_system_server) {
422 int rc = createProcessGroup(uid, getpid());
423 if (rc != 0) {
Colin Cross3089bed2014-07-14 15:07:04 -0700424 if (rc == -EROFS) {
425 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
426 } else {
427 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
428 }
Colin Cross0161bbc2014-06-03 13:26:58 -0700429 }
430 }
431
Narayan Kamath973b4662014-03-31 13:41:26 +0100432 SetGids(env, javaGids);
433
434 SetRLimits(env, javaRlimits);
435
Calin Juravle79ec4c12014-10-24 16:16:49 +0100436 if (use_native_bridge) {
437 ScopedUtfChars isa_string(env, instructionSet);
438 ScopedUtfChars data_dir(env, dataDir);
439 android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
jgu212eacd062014-09-10 06:55:07 -0400440 }
441
Narayan Kamath973b4662014-03-31 13:41:26 +0100442 int rc = setresgid(gid, gid, gid);
443 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700444 ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100445 RuntimeAbort(env);
446 }
447
448 rc = setresuid(uid, uid, uid);
449 if (rc == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700450 ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100451 RuntimeAbort(env);
452 }
453
Narayan Kamath973b4662014-03-31 13:41:26 +0100454 if (NeedsNoRandomizeWorkaround()) {
455 // Work around ARM kernel ASLR lossage (http://b/5817320).
456 int old_personality = personality(0xffffffff);
457 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
458 if (new_personality == -1) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700459 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100460 }
461 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100462
463 SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
464
465 SetSchedulerPolicy(env);
466
Colin Cross18cd9f52014-06-13 12:58:55 -0700467 const char* se_info_c_str = NULL;
468 ScopedUtfChars* se_info = NULL;
469 if (java_se_info != NULL) {
470 se_info = new ScopedUtfChars(env, java_se_info);
471 se_info_c_str = se_info->c_str();
472 if (se_info_c_str == NULL) {
473 ALOGE("se_info_c_str == NULL");
474 RuntimeAbort(env);
475 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100476 }
Colin Cross18cd9f52014-06-13 12:58:55 -0700477 const char* se_name_c_str = NULL;
478 ScopedUtfChars* se_name = NULL;
479 if (java_se_name != NULL) {
480 se_name = new ScopedUtfChars(env, java_se_name);
481 se_name_c_str = se_name->c_str();
482 if (se_name_c_str == NULL) {
483 ALOGE("se_name_c_str == NULL");
484 RuntimeAbort(env);
485 }
486 }
487 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
488 if (rc == -1) {
489 ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
490 is_system_server, se_info_c_str, se_name_c_str);
491 RuntimeAbort(env);
492 }
493
494 // Make it easier to debug audit logs by setting the main thread's name to the
495 // nice name rather than "app_process".
496 if (se_info_c_str == NULL && is_system_server) {
497 se_name_c_str = "system_server";
498 }
499 if (se_info_c_str != NULL) {
500 SetThreadName(se_name_c_str);
501 }
502
503 delete se_info;
504 delete se_name;
Narayan Kamath973b4662014-03-31 13:41:26 +0100505
506 UnsetSigChldHandler();
507
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700508 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
509 is_system_server ? NULL : instructionSet);
Narayan Kamath973b4662014-03-31 13:41:26 +0100510 if (env->ExceptionCheck()) {
511 ALOGE("Error calling post fork hooks.");
512 RuntimeAbort(env);
513 }
514 } else if (pid > 0) {
515 // the parent process
516 }
517 return pid;
518}
519} // anonymous namespace
520
521namespace android {
522
523static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
524 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
525 jint debug_flags, jobjectArray rlimits,
526 jint mount_external, jstring se_info, jstring se_name,
jgu212eacd062014-09-10 06:55:07 -0400527 jintArray fdsToClose, jstring instructionSet, jstring appDataDir) {
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700528 // Grant CAP_WAKE_ALARM to the Bluetooth process.
529 jlong capabilities = 0;
530 if (uid == AID_BLUETOOTH) {
531 capabilities |= (1LL << CAP_WAKE_ALARM);
532 }
533
Narayan Kamath973b4662014-03-31 13:41:26 +0100534 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -0700535 rlimits, capabilities, capabilities, mount_external, se_info,
Andreas Gampea103ebe2014-09-24 15:37:53 -0700536 se_name, false, fdsToClose, instructionSet, appDataDir);
Narayan Kamath973b4662014-03-31 13:41:26 +0100537}
538
539static jint com_android_internal_os_Zygote_nativeForkSystemServer(
540 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
541 jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
542 jlong effectiveCapabilities) {
543 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
544 debug_flags, rlimits,
545 permittedCapabilities, effectiveCapabilities,
jgu212eacd062014-09-10 06:55:07 -0400546 MOUNT_EXTERNAL_NONE, NULL, NULL, true, NULL,
547 NULL, NULL);
Narayan Kamath973b4662014-03-31 13:41:26 +0100548 if (pid > 0) {
549 // The zygote process checks whether the child process has died or not.
550 ALOGI("System server process %d has been created", pid);
551 gSystemServerPid = pid;
552 // There is a slight window that the system server process has crashed
553 // but it went unnoticed because we haven't published its pid yet. So
554 // we recheck here just to make sure that all is well.
555 int status;
556 if (waitpid(pid, &status, WNOHANG) == pid) {
557 ALOGE("System server process %d has died. Restarting Zygote!", pid);
558 RuntimeAbort(env);
559 }
560 }
561 return pid;
562}
563
564static JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700565 { "nativeForkAndSpecialize",
jgu212eacd062014-09-10 06:55:07 -0400566 "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +0100567 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
568 { "nativeForkSystemServer", "(II[II[[IJJ)I",
569 (void *) com_android_internal_os_Zygote_nativeForkSystemServer }
570};
571
572int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800573 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
574 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700575 "(ILjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +0100576
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800577 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +0100578}
579} // namespace android
580