blob: b4f69fbeb9aaa12805d6d55bc08a869c7c845ebe [file] [log] [blame]
Elliott Hughes01158d72011-09-19 19:47:10 -07001/*
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
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070017#include <grp.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070018#include <paths.h>
Elliott Hughesada2da92012-01-17 17:58:58 -080019#include <signal.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070020#include <stdlib.h>
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070021#include <sys/types.h>
22#include <sys/wait.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070023#include <unistd.h>
24
Elliott Hughesb6636b82012-04-24 10:41:16 -070025#include "cutils/sched_policy.h"
Elliott Hughes4ffd3132011-10-24 12:06:42 -070026#include "debugger.h"
27#include "jni_internal.h"
28#include "JniConstants.h"
29#include "JNIHelp.h"
30#include "ScopedLocalRef.h"
31#include "ScopedPrimitiveArray.h"
32#include "ScopedUtfChars.h"
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070033#include "thread.h"
34
Elliott Hughesb4807ec2012-01-17 18:33:04 -080035#if defined(HAVE_PRCTL)
36#include <sys/prctl.h>
37#endif
38
Elliott Hughes01158d72011-09-19 19:47:10 -070039namespace art {
40
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070041static pid_t gSystemServerPid = 0;
42
Elliott Hughes0512f022012-03-15 22:10:52 -070043static void Zygote_nativeExecShell(JNIEnv* env, jclass, jstring javaCommand) {
Elliott Hughes01158d72011-09-19 19:47:10 -070044 ScopedUtfChars command(env, javaCommand);
45 if (command.c_str() == NULL) {
46 return;
47 }
Elliott Hughesc1f143d2011-12-01 17:31:10 -080048 const char* argp[] = {_PATH_BSHELL, "-c", command.c_str(), NULL};
Elliott Hughes01158d72011-09-19 19:47:10 -070049 LOG(INFO) << "Exec: " << argp[0] << ' ' << argp[1] << ' ' << argp[2];
50
Elliott Hughesba8eee12012-01-24 20:25:24 -080051 execv(_PATH_BSHELL, const_cast<char**>(argp));
Elliott Hughes01158d72011-09-19 19:47:10 -070052 exit(127);
53}
54
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070055// This signal handler is for zygote mode, since the zygote must reap its children
Elliott Hughes1bac54f2012-03-16 12:48:31 -070056static void SigChldHandler(int /*signal_number*/) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070057 pid_t pid;
58 int status;
59
60 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
61 // Log process-death status that we care about. In general it is
62 // not safe to call LOG(...) from a signal handler because of
63 // possible reentrancy. However, we know a priori that the
64 // current implementation of LOG() is safe to call from a SIGCHLD
65 // handler in the zygote process. If the LOG() implementation
66 // changes its locking strategy or its use of syscalls within the
67 // lazy-init critical section, its use here may become unsafe.
68 if (WIFEXITED(status)) {
69 if (WEXITSTATUS(status)) {
70 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
71 } else if (false) {
72 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
73 }
74 } else if (WIFSIGNALED(status)) {
75 if (WTERMSIG(status) != SIGKILL) {
76 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
77 } else if (false) {
78 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
79 }
80#ifdef WCOREDUMP
81 if (WCOREDUMP(status)) {
82 LOG(INFO) << "Process " << pid << " dumped core";
83 }
84#endif /* ifdef WCOREDUMP */
85 }
86
87 // If the just-crashed process is the system_server, bring down zygote
88 // so that it is restarted by init and system server will be restarted
89 // from there.
90 if (pid == gSystemServerPid) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -070091 LOG(ERROR) << "Exit zygote because system server (" << pid << ") has terminated";
92 kill(getpid(), SIGKILL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070093 }
94 }
95
96 if (pid < 0) {
97 PLOG(WARNING) << "Zygote SIGCHLD error in waitpid";
98 }
99}
100
Elliott Hughes0512f022012-03-15 22:10:52 -0700101// Configures the SIGCHLD handler for the zygote process. This is configured
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700102// very late, because earlier in the runtime we may fork() and exec()
103// other processes, and we want to waitpid() for those rather than
104// have them be harvested immediately.
105//
106// This ends up being called repeatedly before each fork(), but there's
107// no real harm in that.
Elliott Hughes0512f022012-03-15 22:10:52 -0700108static void SetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700109 struct sigaction sa;
110 memset(&sa, 0, sizeof(sa));
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700111 sa.sa_handler = SigChldHandler;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700112
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700113 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700114 if (err < 0) {
115 PLOG(WARNING) << "Error setting SIGCHLD handler";
116 }
117}
118
Elliott Hughes0512f022012-03-15 22:10:52 -0700119// Sets the SIGCHLD handler back to default behavior in zygote children.
120static void UnsetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700121 struct sigaction sa;
122 memset(&sa, 0, sizeof(sa));
123 sa.sa_handler = SIG_DFL;
124
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700125 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700126 if (err < 0) {
127 PLOG(WARNING) << "Error unsetting SIGCHLD handler";
128 }
129}
130
131// Calls POSIX setgroups() using the int[] object as an argument.
132// A NULL argument is tolerated.
Elliott Hughes0512f022012-03-15 22:10:52 -0700133static int SetGids(JNIEnv* env, jintArray javaGids) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700134 if (javaGids == NULL) {
135 return 0;
136 }
137
138 COMPILE_ASSERT(sizeof(gid_t) == sizeof(jint), sizeof_gid_and_jint_are_differerent);
139 ScopedIntArrayRO gids(env, javaGids);
140 if (gids.get() == NULL) {
141 return -1;
142 }
143 return setgroups(gids.size(), (const gid_t *) &gids[0]);
144}
145
146// Sets the resource limits via setrlimit(2) for the values in the
147// two-dimensional array of integers that's passed in. The second dimension
148// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
149// treated as an empty array.
150//
151// -1 is returned on error.
Elliott Hughes0512f022012-03-15 22:10:52 -0700152static int SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700153 if (javaRlimits == NULL) {
154 return 0;
155 }
156
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700157 rlimit rlim;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700158 memset(&rlim, 0, sizeof(rlim));
159
160 for (int i = 0; i < env->GetArrayLength(javaRlimits); i++) {
161 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
162 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
163 if (javaRlimit.size() != 3) {
164 LOG(ERROR) << "rlimits array must have a second dimension of size 3";
165 return -1;
166 }
167
168 rlim.rlim_cur = javaRlimit[1];
169 rlim.rlim_max = javaRlimit[2];
170
171 int err = setrlimit(javaRlimit[0], &rlim);
172 if (err < 0) {
173 return -1;
174 }
175 }
176 return 0;
177}
178
Elliott Hughes76e36942012-03-16 13:44:56 -0700179#if defined(HAVE_ANDROID_OS)
180static void SetCapabilities(int64_t permitted, int64_t effective) {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700181 __user_cap_header_struct capheader;
182 __user_cap_data_struct capdata;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700183
184 memset(&capheader, 0, sizeof(capheader));
185 memset(&capdata, 0, sizeof(capdata));
186
187 capheader.version = _LINUX_CAPABILITY_VERSION;
188 capheader.pid = 0;
189
190 capdata.effective = effective;
191 capdata.permitted = permitted;
192
193 if (capset(&capheader, &capdata) != 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800194 PLOG(FATAL) << "capset(" << permitted << ", " << effective << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700195 }
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700196}
Elliott Hughes76e36942012-03-16 13:44:56 -0700197#else
198static void SetCapabilities(int64_t, int64_t) {}
199#endif
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700200
Elliott Hughes0512f022012-03-15 22:10:52 -0700201static void EnableDebugFeatures(uint32_t debug_flags) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700202 // Must match values in dalvik.system.Zygote.
203 enum {
204 DEBUG_ENABLE_DEBUGGER = 1,
205 DEBUG_ENABLE_CHECKJNI = 1 << 1,
206 DEBUG_ENABLE_ASSERT = 1 << 2,
207 DEBUG_ENABLE_SAFEMODE = 1 << 3,
208 DEBUG_ENABLE_JNI_LOGGING = 1 << 4,
209 };
210
211 if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
212 Runtime* runtime = Runtime::Current();
213 JavaVMExt* vm = runtime->GetJavaVM();
214 if (!vm->check_jni) {
215 LOG(DEBUG) << "Late-enabling -Xcheck:jni";
Elliott Hughes88c5c352012-03-15 18:49:48 -0700216 vm->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700217 // There's only one thread running at this point, so only one JNIEnv to fix up.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700218 Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700219 } else {
220 LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
221 }
222 debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
223 }
224
225 if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800226 gLogVerbosity.third_party_jni = true;
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700227 debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
228 }
229
230 Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
231#ifdef HAVE_ANDROID_OS
232 if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
233 /* To let a non-privileged gdbserver attach to this
234 * process, we must set its dumpable bit flag. However
235 * we are not interested in generating a coredump in
236 * case of a crash, so also set the coredump size to 0
237 * to disable that
238 */
239 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
240 PLOG(ERROR) << "could not set dumpable bit flag for pid " << getpid();
241 } else {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700242 rlimit rl;
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700243 rl.rlim_cur = 0;
244 rl.rlim_max = RLIM_INFINITY;
245 if (setrlimit(RLIMIT_CORE, &rl) < 0) {
246 PLOG(ERROR) << "could not disable core file generation for pid " << getpid();
247 }
248 }
249 }
250#endif
251 debug_flags &= ~DEBUG_ENABLE_DEBUGGER;
252
253 // These two are for backwards compatibility with Dalvik.
254 debug_flags &= ~DEBUG_ENABLE_ASSERT;
255 debug_flags &= ~DEBUG_ENABLE_SAFEMODE;
256
257 if (debug_flags != 0) {
258 LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
259 }
260}
261
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700262#ifdef HAVE_ANDROID_OS
263extern "C" int gMallocLeakZygoteChild;
264#endif
265
266// Utility routine to fork zygote and specialize the child process.
Elliott Hughes0512f022012-03-15 22:10:52 -0700267static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
268 jint debug_flags, jobjectArray javaRlimits,
269 jlong permittedCapabilities, jlong effectiveCapabilities) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700270 Runtime* runtime = Runtime::Current();
271 CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
272 if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
273 LOG(FATAL) << "pre-fork heap failed";
274 }
275
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700276 SetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700277
278 // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
279 Thread* self = Thread::Current();
280
281 // dvmDumpLoaderStats("zygote"); // TODO: ?
282 pid_t pid = fork();
283
284 if (pid == 0) {
285 // The child process
286
287#ifdef HAVE_ANDROID_OS
288 gMallocLeakZygoteChild = 1;
289
290 // keep caps across UID change, unless we're staying root */
291 if (uid != 0) {
292 int err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
293 if (err < 0) {
294 PLOG(FATAL) << "cannot PR_SET_KEEPCAPS";
295 }
296 }
297#endif // HAVE_ANDROID_OS
298
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700299 int err = SetGids(env, javaGids);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700300 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800301 PLOG(FATAL) << "setgroups failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700302 }
303
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700304 err = SetRLimits(env, javaRlimits);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700305 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800306 PLOG(FATAL) << "setrlimit failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700307 }
308
309 err = setgid(gid);
310 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800311 PLOG(FATAL) << "setgid(" << gid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700312 }
313
314 err = setuid(uid);
315 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800316 PLOG(FATAL) << "setuid(" << uid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700317 }
318
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800319 SetCapabilities(permittedCapabilities, effectiveCapabilities);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700320
Elliott Hughesb6636b82012-04-24 10:41:16 -0700321#if 1
322 UNIMPLEMENTED(WARNING) << "enable this code when cutils/sched_policy.h has SP_DEFAULT";
323#else
324 err = set_sched_policy(0, SP_DEFAULT);
325 if (err < 0) {
326 errno = -err;
327 PLOG(FATAL) << "set_sched_policy(0, SP_DEFAULT) failed";
328 }
329#endif
330
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700331 // Our system thread ID, etc, has changed so reset Thread state.
332 self->InitAfterFork();
333
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700334 EnableDebugFeatures(debug_flags);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700335
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700336 UnsetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700337 runtime->DidForkFromZygote();
338 } else if (pid > 0) {
339 // the parent process
340 }
341 return pid;
342}
343
Elliott Hughes0512f022012-03-15 22:10:52 -0700344static jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
345 jint debug_flags, jobjectArray rlimits) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700346 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, 0, 0);
Brian Carlstroma9f19782011-10-13 00:14:47 -0700347}
348
Elliott Hughes0512f022012-03-15 22:10:52 -0700349static jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
350 jint debug_flags, jobjectArray rlimits,
351 jlong permittedCapabilities, jlong effectiveCapabilities) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700352 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
353 debug_flags, rlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700354 permittedCapabilities, effectiveCapabilities);
355 if (pid > 0) {
356 // The zygote process checks whether the child process has died or not.
357 LOG(INFO) << "System server process " << pid << " has been created";
358 gSystemServerPid = pid;
359 // There is a slight window that the system server process has crashed
360 // but it went unnoticed because we haven't published its pid yet. So
361 // we recheck here just to make sure that all is well.
362 int status;
363 if (waitpid(pid, &status, WNOHANG) == pid) {
364 LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
365 }
366 }
367 return pid;
368}
369
Elliott Hughes01158d72011-09-19 19:47:10 -0700370static JNINativeMethod gMethods[] = {
371 NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
372 //NATIVE_METHOD(Zygote, nativeFork, "()I"),
Brian Carlstroma9f19782011-10-13 00:14:47 -0700373 NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700374 NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
Elliott Hughes01158d72011-09-19 19:47:10 -0700375};
376
Elliott Hughes01158d72011-09-19 19:47:10 -0700377void register_dalvik_system_Zygote(JNIEnv* env) {
378 jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
379}
380
381} // namespace art