blob: cdc4c29252cff66cb87884e567f0a113d9abcd88 [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>
Elliott Hughes51e53862012-05-02 17:17:28 -070021#include <sys/personality.h>
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070022#include <sys/types.h>
23#include <sys/wait.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070024#include <unistd.h>
25
Elliott Hughesb6636b82012-04-24 10:41:16 -070026#include "cutils/sched_policy.h"
Elliott Hughes4ffd3132011-10-24 12:06:42 -070027#include "debugger.h"
28#include "jni_internal.h"
29#include "JniConstants.h"
30#include "JNIHelp.h"
31#include "ScopedLocalRef.h"
32#include "ScopedPrimitiveArray.h"
33#include "ScopedUtfChars.h"
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070034#include "thread.h"
35
Elliott Hughesb4807ec2012-01-17 18:33:04 -080036#if defined(HAVE_PRCTL)
37#include <sys/prctl.h>
38#endif
39
Elliott Hughes01158d72011-09-19 19:47:10 -070040namespace art {
41
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070042static pid_t gSystemServerPid = 0;
43
Elliott Hughes0512f022012-03-15 22:10:52 -070044static void Zygote_nativeExecShell(JNIEnv* env, jclass, jstring javaCommand) {
Elliott Hughes01158d72011-09-19 19:47:10 -070045 ScopedUtfChars command(env, javaCommand);
46 if (command.c_str() == NULL) {
47 return;
48 }
Elliott Hughesc1f143d2011-12-01 17:31:10 -080049 const char* argp[] = {_PATH_BSHELL, "-c", command.c_str(), NULL};
Elliott Hughes01158d72011-09-19 19:47:10 -070050 LOG(INFO) << "Exec: " << argp[0] << ' ' << argp[1] << ' ' << argp[2];
51
Elliott Hughesba8eee12012-01-24 20:25:24 -080052 execv(_PATH_BSHELL, const_cast<char**>(argp));
Elliott Hughes01158d72011-09-19 19:47:10 -070053 exit(127);
54}
55
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070056// This signal handler is for zygote mode, since the zygote must reap its children
Elliott Hughes1bac54f2012-03-16 12:48:31 -070057static void SigChldHandler(int /*signal_number*/) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070058 pid_t pid;
59 int status;
60
61 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
62 // Log process-death status that we care about. In general it is
63 // not safe to call LOG(...) from a signal handler because of
64 // possible reentrancy. However, we know a priori that the
65 // current implementation of LOG() is safe to call from a SIGCHLD
66 // handler in the zygote process. If the LOG() implementation
67 // changes its locking strategy or its use of syscalls within the
68 // lazy-init critical section, its use here may become unsafe.
69 if (WIFEXITED(status)) {
70 if (WEXITSTATUS(status)) {
71 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
72 } else if (false) {
73 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
74 }
75 } else if (WIFSIGNALED(status)) {
76 if (WTERMSIG(status) != SIGKILL) {
77 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
78 } else if (false) {
79 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
80 }
81#ifdef WCOREDUMP
82 if (WCOREDUMP(status)) {
83 LOG(INFO) << "Process " << pid << " dumped core";
84 }
85#endif /* ifdef WCOREDUMP */
86 }
87
88 // If the just-crashed process is the system_server, bring down zygote
89 // so that it is restarted by init and system server will be restarted
90 // from there.
91 if (pid == gSystemServerPid) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -070092 LOG(ERROR) << "Exit zygote because system server (" << pid << ") has terminated";
93 kill(getpid(), SIGKILL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070094 }
95 }
96
97 if (pid < 0) {
98 PLOG(WARNING) << "Zygote SIGCHLD error in waitpid";
99 }
100}
101
Elliott Hughes0512f022012-03-15 22:10:52 -0700102// Configures the SIGCHLD handler for the zygote process. This is configured
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700103// very late, because earlier in the runtime we may fork() and exec()
104// other processes, and we want to waitpid() for those rather than
105// have them be harvested immediately.
106//
107// This ends up being called repeatedly before each fork(), but there's
108// no real harm in that.
Elliott Hughes0512f022012-03-15 22:10:52 -0700109static void SetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700110 struct sigaction sa;
111 memset(&sa, 0, sizeof(sa));
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700112 sa.sa_handler = SigChldHandler;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700113
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700114 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700115 if (err < 0) {
116 PLOG(WARNING) << "Error setting SIGCHLD handler";
117 }
118}
119
Elliott Hughes0512f022012-03-15 22:10:52 -0700120// Sets the SIGCHLD handler back to default behavior in zygote children.
121static void UnsetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700122 struct sigaction sa;
123 memset(&sa, 0, sizeof(sa));
124 sa.sa_handler = SIG_DFL;
125
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700126 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700127 if (err < 0) {
128 PLOG(WARNING) << "Error unsetting SIGCHLD handler";
129 }
130}
131
132// Calls POSIX setgroups() using the int[] object as an argument.
133// A NULL argument is tolerated.
Elliott Hughes0512f022012-03-15 22:10:52 -0700134static int SetGids(JNIEnv* env, jintArray javaGids) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700135 if (javaGids == NULL) {
136 return 0;
137 }
138
139 COMPILE_ASSERT(sizeof(gid_t) == sizeof(jint), sizeof_gid_and_jint_are_differerent);
140 ScopedIntArrayRO gids(env, javaGids);
141 if (gids.get() == NULL) {
142 return -1;
143 }
144 return setgroups(gids.size(), (const gid_t *) &gids[0]);
145}
146
147// Sets the resource limits via setrlimit(2) for the values in the
148// two-dimensional array of integers that's passed in. The second dimension
149// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
150// treated as an empty array.
151//
152// -1 is returned on error.
Elliott Hughes0512f022012-03-15 22:10:52 -0700153static int SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700154 if (javaRlimits == NULL) {
155 return 0;
156 }
157
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700158 rlimit rlim;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700159 memset(&rlim, 0, sizeof(rlim));
160
161 for (int i = 0; i < env->GetArrayLength(javaRlimits); i++) {
162 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
163 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
164 if (javaRlimit.size() != 3) {
165 LOG(ERROR) << "rlimits array must have a second dimension of size 3";
166 return -1;
167 }
168
169 rlim.rlim_cur = javaRlimit[1];
170 rlim.rlim_max = javaRlimit[2];
171
172 int err = setrlimit(javaRlimit[0], &rlim);
173 if (err < 0) {
174 return -1;
175 }
176 }
177 return 0;
178}
179
Elliott Hughes76e36942012-03-16 13:44:56 -0700180#if defined(HAVE_ANDROID_OS)
181static void SetCapabilities(int64_t permitted, int64_t effective) {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700182 __user_cap_header_struct capheader;
183 __user_cap_data_struct capdata;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700184
185 memset(&capheader, 0, sizeof(capheader));
186 memset(&capdata, 0, sizeof(capdata));
187
188 capheader.version = _LINUX_CAPABILITY_VERSION;
189 capheader.pid = 0;
190
191 capdata.effective = effective;
192 capdata.permitted = permitted;
193
194 if (capset(&capheader, &capdata) != 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800195 PLOG(FATAL) << "capset(" << permitted << ", " << effective << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700196 }
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700197}
Elliott Hughes76e36942012-03-16 13:44:56 -0700198#else
199static void SetCapabilities(int64_t, int64_t) {}
200#endif
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700201
Elliott Hughes0512f022012-03-15 22:10:52 -0700202static void EnableDebugFeatures(uint32_t debug_flags) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700203 // Must match values in dalvik.system.Zygote.
204 enum {
205 DEBUG_ENABLE_DEBUGGER = 1,
206 DEBUG_ENABLE_CHECKJNI = 1 << 1,
207 DEBUG_ENABLE_ASSERT = 1 << 2,
208 DEBUG_ENABLE_SAFEMODE = 1 << 3,
209 DEBUG_ENABLE_JNI_LOGGING = 1 << 4,
210 };
211
212 if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
213 Runtime* runtime = Runtime::Current();
214 JavaVMExt* vm = runtime->GetJavaVM();
215 if (!vm->check_jni) {
216 LOG(DEBUG) << "Late-enabling -Xcheck:jni";
Elliott Hughes88c5c352012-03-15 18:49:48 -0700217 vm->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700218 // There's only one thread running at this point, so only one JNIEnv to fix up.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700219 Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700220 } else {
221 LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
222 }
223 debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
224 }
225
226 if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800227 gLogVerbosity.third_party_jni = true;
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700228 debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
229 }
230
231 Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
232#ifdef HAVE_ANDROID_OS
233 if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
234 /* To let a non-privileged gdbserver attach to this
235 * process, we must set its dumpable bit flag. However
236 * we are not interested in generating a coredump in
237 * case of a crash, so also set the coredump size to 0
238 * to disable that
239 */
240 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
241 PLOG(ERROR) << "could not set dumpable bit flag for pid " << getpid();
242 } else {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700243 rlimit rl;
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700244 rl.rlim_cur = 0;
245 rl.rlim_max = RLIM_INFINITY;
246 if (setrlimit(RLIMIT_CORE, &rl) < 0) {
247 PLOG(ERROR) << "could not disable core file generation for pid " << getpid();
248 }
249 }
250 }
251#endif
252 debug_flags &= ~DEBUG_ENABLE_DEBUGGER;
253
254 // These two are for backwards compatibility with Dalvik.
255 debug_flags &= ~DEBUG_ENABLE_ASSERT;
256 debug_flags &= ~DEBUG_ENABLE_SAFEMODE;
257
258 if (debug_flags != 0) {
259 LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
260 }
261}
262
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700263#ifdef HAVE_ANDROID_OS
264extern "C" int gMallocLeakZygoteChild;
265#endif
266
267// Utility routine to fork zygote and specialize the child process.
Elliott Hughes0512f022012-03-15 22:10:52 -0700268static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
269 jint debug_flags, jobjectArray javaRlimits,
270 jlong permittedCapabilities, jlong effectiveCapabilities) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700271 Runtime* runtime = Runtime::Current();
272 CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
273 if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
274 LOG(FATAL) << "pre-fork heap failed";
275 }
276
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700277 SetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700278
279 // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
280 Thread* self = Thread::Current();
281
282 // dvmDumpLoaderStats("zygote"); // TODO: ?
283 pid_t pid = fork();
284
285 if (pid == 0) {
286 // The child process
287
288#ifdef HAVE_ANDROID_OS
289 gMallocLeakZygoteChild = 1;
290
291 // keep caps across UID change, unless we're staying root */
292 if (uid != 0) {
293 int err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
294 if (err < 0) {
295 PLOG(FATAL) << "cannot PR_SET_KEEPCAPS";
296 }
297 }
298#endif // HAVE_ANDROID_OS
299
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700300 int err = SetGids(env, javaGids);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700301 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800302 PLOG(FATAL) << "setgroups failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700303 }
304
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700305 err = SetRLimits(env, javaRlimits);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700306 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800307 PLOG(FATAL) << "setrlimit failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700308 }
309
310 err = setgid(gid);
311 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800312 PLOG(FATAL) << "setgid(" << gid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700313 }
314
315 err = setuid(uid);
316 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800317 PLOG(FATAL) << "setuid(" << uid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700318 }
319
Elliott Hughes51e53862012-05-02 17:17:28 -0700320 // Work around ARM kernel ASLR lossage (http://b/5817320).
321 int old_personality = personality(0xffffffff);
322 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
323 if (new_personality == -1) {
324 PLOG(WARNING) << "personality(" << new_personality << ") failed";
325 }
326
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800327 SetCapabilities(permittedCapabilities, effectiveCapabilities);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700328
Elliott Hughesb6636b82012-04-24 10:41:16 -0700329#if 1
330 UNIMPLEMENTED(WARNING) << "enable this code when cutils/sched_policy.h has SP_DEFAULT";
331#else
332 err = set_sched_policy(0, SP_DEFAULT);
333 if (err < 0) {
334 errno = -err;
335 PLOG(FATAL) << "set_sched_policy(0, SP_DEFAULT) failed";
336 }
337#endif
338
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700339 // Our system thread ID, etc, has changed so reset Thread state.
340 self->InitAfterFork();
341
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700342 EnableDebugFeatures(debug_flags);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700343
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700344 UnsetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700345 runtime->DidForkFromZygote();
346 } else if (pid > 0) {
347 // the parent process
348 }
349 return pid;
350}
351
Elliott Hughes0512f022012-03-15 22:10:52 -0700352static jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
353 jint debug_flags, jobjectArray rlimits) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700354 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, 0, 0);
Brian Carlstroma9f19782011-10-13 00:14:47 -0700355}
356
Elliott Hughes0512f022012-03-15 22:10:52 -0700357static jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
358 jint debug_flags, jobjectArray rlimits,
359 jlong permittedCapabilities, jlong effectiveCapabilities) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700360 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
361 debug_flags, rlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700362 permittedCapabilities, effectiveCapabilities);
363 if (pid > 0) {
364 // The zygote process checks whether the child process has died or not.
365 LOG(INFO) << "System server process " << pid << " has been created";
366 gSystemServerPid = pid;
367 // There is a slight window that the system server process has crashed
368 // but it went unnoticed because we haven't published its pid yet. So
369 // we recheck here just to make sure that all is well.
370 int status;
371 if (waitpid(pid, &status, WNOHANG) == pid) {
372 LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
373 }
374 }
375 return pid;
376}
377
Elliott Hughes01158d72011-09-19 19:47:10 -0700378static JNINativeMethod gMethods[] = {
379 NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
380 //NATIVE_METHOD(Zygote, nativeFork, "()I"),
Brian Carlstroma9f19782011-10-13 00:14:47 -0700381 NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700382 NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
Elliott Hughes01158d72011-09-19 19:47:10 -0700383};
384
Elliott Hughes01158d72011-09-19 19:47:10 -0700385void register_dalvik_system_Zygote(JNIEnv* env) {
386 jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
387}
388
389} // namespace art