blob: 0649d96c5379f556bf13eac908709f91edf348d7 [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
Brian Carlstrom154cef62012-05-02 22:34:03 -070039#if defined(__linux__)
40#include <sys/personality.h>
41#endif
42
Elliott Hughes01158d72011-09-19 19:47:10 -070043namespace art {
44
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070045static pid_t gSystemServerPid = 0;
46
Elliott Hughes0512f022012-03-15 22:10:52 -070047static void Zygote_nativeExecShell(JNIEnv* env, jclass, jstring javaCommand) {
Elliott Hughes01158d72011-09-19 19:47:10 -070048 ScopedUtfChars command(env, javaCommand);
49 if (command.c_str() == NULL) {
50 return;
51 }
Elliott Hughesc1f143d2011-12-01 17:31:10 -080052 const char* argp[] = {_PATH_BSHELL, "-c", command.c_str(), NULL};
Elliott Hughes01158d72011-09-19 19:47:10 -070053 LOG(INFO) << "Exec: " << argp[0] << ' ' << argp[1] << ' ' << argp[2];
54
Elliott Hughesba8eee12012-01-24 20:25:24 -080055 execv(_PATH_BSHELL, const_cast<char**>(argp));
Elliott Hughes01158d72011-09-19 19:47:10 -070056 exit(127);
57}
58
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070059// This signal handler is for zygote mode, since the zygote must reap its children
Elliott Hughes1bac54f2012-03-16 12:48:31 -070060static void SigChldHandler(int /*signal_number*/) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070061 pid_t pid;
62 int status;
63
64 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
65 // Log process-death status that we care about. In general it is
66 // not safe to call LOG(...) from a signal handler because of
67 // possible reentrancy. However, we know a priori that the
68 // current implementation of LOG() is safe to call from a SIGCHLD
69 // handler in the zygote process. If the LOG() implementation
70 // changes its locking strategy or its use of syscalls within the
71 // lazy-init critical section, its use here may become unsafe.
72 if (WIFEXITED(status)) {
73 if (WEXITSTATUS(status)) {
74 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
75 } else if (false) {
76 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
77 }
78 } else if (WIFSIGNALED(status)) {
79 if (WTERMSIG(status) != SIGKILL) {
80 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
81 } else if (false) {
82 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
83 }
84#ifdef WCOREDUMP
85 if (WCOREDUMP(status)) {
86 LOG(INFO) << "Process " << pid << " dumped core";
87 }
88#endif /* ifdef WCOREDUMP */
89 }
90
91 // If the just-crashed process is the system_server, bring down zygote
92 // so that it is restarted by init and system server will be restarted
93 // from there.
94 if (pid == gSystemServerPid) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -070095 LOG(ERROR) << "Exit zygote because system server (" << pid << ") has terminated";
96 kill(getpid(), SIGKILL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070097 }
98 }
99
100 if (pid < 0) {
101 PLOG(WARNING) << "Zygote SIGCHLD error in waitpid";
102 }
103}
104
Elliott Hughes0512f022012-03-15 22:10:52 -0700105// Configures the SIGCHLD handler for the zygote process. This is configured
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700106// very late, because earlier in the runtime we may fork() and exec()
107// other processes, and we want to waitpid() for those rather than
108// have them be harvested immediately.
109//
110// This ends up being called repeatedly before each fork(), but there's
111// no real harm in that.
Elliott Hughes0512f022012-03-15 22:10:52 -0700112static void SetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700113 struct sigaction sa;
114 memset(&sa, 0, sizeof(sa));
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700115 sa.sa_handler = SigChldHandler;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700116
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700117 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700118 if (err < 0) {
119 PLOG(WARNING) << "Error setting SIGCHLD handler";
120 }
121}
122
Elliott Hughes0512f022012-03-15 22:10:52 -0700123// Sets the SIGCHLD handler back to default behavior in zygote children.
124static void UnsetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700125 struct sigaction sa;
126 memset(&sa, 0, sizeof(sa));
127 sa.sa_handler = SIG_DFL;
128
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700129 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700130 if (err < 0) {
131 PLOG(WARNING) << "Error unsetting SIGCHLD handler";
132 }
133}
134
135// Calls POSIX setgroups() using the int[] object as an argument.
136// A NULL argument is tolerated.
Elliott Hughes0512f022012-03-15 22:10:52 -0700137static int SetGids(JNIEnv* env, jintArray javaGids) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700138 if (javaGids == NULL) {
139 return 0;
140 }
141
142 COMPILE_ASSERT(sizeof(gid_t) == sizeof(jint), sizeof_gid_and_jint_are_differerent);
143 ScopedIntArrayRO gids(env, javaGids);
144 if (gids.get() == NULL) {
145 return -1;
146 }
147 return setgroups(gids.size(), (const gid_t *) &gids[0]);
148}
149
150// Sets the resource limits via setrlimit(2) for the values in the
151// two-dimensional array of integers that's passed in. The second dimension
152// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
153// treated as an empty array.
154//
155// -1 is returned on error.
Elliott Hughes0512f022012-03-15 22:10:52 -0700156static int SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700157 if (javaRlimits == NULL) {
158 return 0;
159 }
160
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700161 rlimit rlim;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700162 memset(&rlim, 0, sizeof(rlim));
163
164 for (int i = 0; i < env->GetArrayLength(javaRlimits); i++) {
165 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
166 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
167 if (javaRlimit.size() != 3) {
168 LOG(ERROR) << "rlimits array must have a second dimension of size 3";
169 return -1;
170 }
171
172 rlim.rlim_cur = javaRlimit[1];
173 rlim.rlim_max = javaRlimit[2];
174
175 int err = setrlimit(javaRlimit[0], &rlim);
176 if (err < 0) {
177 return -1;
178 }
179 }
180 return 0;
181}
182
Elliott Hughes76e36942012-03-16 13:44:56 -0700183#if defined(HAVE_ANDROID_OS)
184static void SetCapabilities(int64_t permitted, int64_t effective) {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700185 __user_cap_header_struct capheader;
186 __user_cap_data_struct capdata;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700187
188 memset(&capheader, 0, sizeof(capheader));
189 memset(&capdata, 0, sizeof(capdata));
190
191 capheader.version = _LINUX_CAPABILITY_VERSION;
192 capheader.pid = 0;
193
194 capdata.effective = effective;
195 capdata.permitted = permitted;
196
197 if (capset(&capheader, &capdata) != 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800198 PLOG(FATAL) << "capset(" << permitted << ", " << effective << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700199 }
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700200}
Elliott Hughes76e36942012-03-16 13:44:56 -0700201#else
202static void SetCapabilities(int64_t, int64_t) {}
203#endif
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700204
Elliott Hughes0512f022012-03-15 22:10:52 -0700205static void EnableDebugFeatures(uint32_t debug_flags) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700206 // Must match values in dalvik.system.Zygote.
207 enum {
208 DEBUG_ENABLE_DEBUGGER = 1,
209 DEBUG_ENABLE_CHECKJNI = 1 << 1,
210 DEBUG_ENABLE_ASSERT = 1 << 2,
211 DEBUG_ENABLE_SAFEMODE = 1 << 3,
212 DEBUG_ENABLE_JNI_LOGGING = 1 << 4,
213 };
214
215 if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
216 Runtime* runtime = Runtime::Current();
217 JavaVMExt* vm = runtime->GetJavaVM();
218 if (!vm->check_jni) {
219 LOG(DEBUG) << "Late-enabling -Xcheck:jni";
Elliott Hughes88c5c352012-03-15 18:49:48 -0700220 vm->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700221 // There's only one thread running at this point, so only one JNIEnv to fix up.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700222 Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700223 } else {
224 LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
225 }
226 debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
227 }
228
229 if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800230 gLogVerbosity.third_party_jni = true;
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700231 debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
232 }
233
234 Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
235#ifdef HAVE_ANDROID_OS
236 if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
237 /* To let a non-privileged gdbserver attach to this
238 * process, we must set its dumpable bit flag. However
239 * we are not interested in generating a coredump in
240 * case of a crash, so also set the coredump size to 0
241 * to disable that
242 */
243 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
244 PLOG(ERROR) << "could not set dumpable bit flag for pid " << getpid();
245 } else {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700246 rlimit rl;
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700247 rl.rlim_cur = 0;
248 rl.rlim_max = RLIM_INFINITY;
249 if (setrlimit(RLIMIT_CORE, &rl) < 0) {
250 PLOG(ERROR) << "could not disable core file generation for pid " << getpid();
251 }
252 }
253 }
254#endif
255 debug_flags &= ~DEBUG_ENABLE_DEBUGGER;
256
257 // These two are for backwards compatibility with Dalvik.
258 debug_flags &= ~DEBUG_ENABLE_ASSERT;
259 debug_flags &= ~DEBUG_ENABLE_SAFEMODE;
260
261 if (debug_flags != 0) {
262 LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
263 }
264}
265
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700266#ifdef HAVE_ANDROID_OS
267extern "C" int gMallocLeakZygoteChild;
268#endif
269
270// Utility routine to fork zygote and specialize the child process.
Elliott Hughes0512f022012-03-15 22:10:52 -0700271static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
272 jint debug_flags, jobjectArray javaRlimits,
273 jlong permittedCapabilities, jlong effectiveCapabilities) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700274 Runtime* runtime = Runtime::Current();
275 CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
276 if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
277 LOG(FATAL) << "pre-fork heap failed";
278 }
279
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700280 SetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700281
282 // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
283 Thread* self = Thread::Current();
284
285 // dvmDumpLoaderStats("zygote"); // TODO: ?
286 pid_t pid = fork();
287
288 if (pid == 0) {
289 // The child process
290
291#ifdef HAVE_ANDROID_OS
292 gMallocLeakZygoteChild = 1;
293
294 // keep caps across UID change, unless we're staying root */
295 if (uid != 0) {
296 int err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
297 if (err < 0) {
298 PLOG(FATAL) << "cannot PR_SET_KEEPCAPS";
299 }
300 }
301#endif // HAVE_ANDROID_OS
302
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700303 int err = SetGids(env, javaGids);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700304 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800305 PLOG(FATAL) << "setgroups failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700306 }
307
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700308 err = SetRLimits(env, javaRlimits);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700309 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800310 PLOG(FATAL) << "setrlimit failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700311 }
312
313 err = setgid(gid);
314 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800315 PLOG(FATAL) << "setgid(" << gid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700316 }
317
318 err = setuid(uid);
319 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800320 PLOG(FATAL) << "setuid(" << uid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700321 }
322
Brian Carlstrom154cef62012-05-02 22:34:03 -0700323#if defined(__linux__)
Elliott Hughes51e53862012-05-02 17:17:28 -0700324 // Work around ARM kernel ASLR lossage (http://b/5817320).
325 int old_personality = personality(0xffffffff);
326 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
327 if (new_personality == -1) {
328 PLOG(WARNING) << "personality(" << new_personality << ") failed";
329 }
Brian Carlstrom154cef62012-05-02 22:34:03 -0700330#endif
Elliott Hughes51e53862012-05-02 17:17:28 -0700331
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800332 SetCapabilities(permittedCapabilities, effectiveCapabilities);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700333
Elliott Hughesb6636b82012-04-24 10:41:16 -0700334 err = set_sched_policy(0, SP_DEFAULT);
335 if (err < 0) {
336 errno = -err;
337 PLOG(FATAL) << "set_sched_policy(0, SP_DEFAULT) failed";
338 }
Elliott Hughesb6636b82012-04-24 10:41:16 -0700339
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700340 // Our system thread ID, etc, has changed so reset Thread state.
341 self->InitAfterFork();
342
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700343 EnableDebugFeatures(debug_flags);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700344
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700345 UnsetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700346 runtime->DidForkFromZygote();
347 } else if (pid > 0) {
348 // the parent process
349 }
350 return pid;
351}
352
Elliott Hughes0512f022012-03-15 22:10:52 -0700353static jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
354 jint debug_flags, jobjectArray rlimits) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700355 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, 0, 0);
Brian Carlstroma9f19782011-10-13 00:14:47 -0700356}
357
Elliott Hughes0512f022012-03-15 22:10:52 -0700358static jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
359 jint debug_flags, jobjectArray rlimits,
360 jlong permittedCapabilities, jlong effectiveCapabilities) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700361 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
362 debug_flags, rlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700363 permittedCapabilities, effectiveCapabilities);
364 if (pid > 0) {
365 // The zygote process checks whether the child process has died or not.
366 LOG(INFO) << "System server process " << pid << " has been created";
367 gSystemServerPid = pid;
368 // There is a slight window that the system server process has crashed
369 // but it went unnoticed because we haven't published its pid yet. So
370 // we recheck here just to make sure that all is well.
371 int status;
372 if (waitpid(pid, &status, WNOHANG) == pid) {
373 LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
374 }
375 }
376 return pid;
377}
378
Elliott Hughes01158d72011-09-19 19:47:10 -0700379static JNINativeMethod gMethods[] = {
380 NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
381 //NATIVE_METHOD(Zygote, nativeFork, "()I"),
Brian Carlstroma9f19782011-10-13 00:14:47 -0700382 NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700383 NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
Elliott Hughes01158d72011-09-19 19:47:10 -0700384};
385
Elliott Hughes01158d72011-09-19 19:47:10 -0700386void register_dalvik_system_Zygote(JNIEnv* env) {
387 jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
388}
389
390} // namespace art