blob: 8ced7e4a75811ec2a38fe549837bc0cf8bfb7fea [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 Hughes2abeb9b2012-05-11 23:42:02 -0700137static void SetGids(JNIEnv* env, jintArray javaGids) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700138 if (javaGids == NULL) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700139 return;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700140 }
141
142 COMPILE_ASSERT(sizeof(gid_t) == sizeof(jint), sizeof_gid_and_jint_are_differerent);
143 ScopedIntArrayRO gids(env, javaGids);
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700144 CHECK(gids.get() != NULL);
145 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
146 if (rc == -1) {
147 PLOG(FATAL) << "setgroups failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700148 }
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700149}
150
151// Sets the resource limits via setrlimit(2) for the values in the
152// two-dimensional array of integers that's passed in. The second dimension
153// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
154// treated as an empty array.
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700155static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700156 if (javaRlimits == NULL) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700157 return;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700158 }
159
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700160 rlimit rlim;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700161 memset(&rlim, 0, sizeof(rlim));
162
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700163 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700164 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
165 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
166 if (javaRlimit.size() != 3) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700167 LOG(FATAL) << "rlimits array must have a second dimension of size 3";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700168 }
169
170 rlim.rlim_cur = javaRlimit[1];
171 rlim.rlim_max = javaRlimit[2];
172
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700173 int rc = setrlimit(javaRlimit[0], &rlim);
174 if (rc == -1) {
175 PLOG(FATAL) << "setrlimit(" << javaRlimit[0] << ", "
176 << "{" << rlim.rlim_cur << ", " << rlim.rlim_max << "}) failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700177 }
178 }
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700179}
180
Elliott Hughes76e36942012-03-16 13:44:56 -0700181#if defined(HAVE_ANDROID_OS)
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700182
183// The debug malloc library needs to know whether it's the zygote or a child.
184extern "C" int gMallocLeakZygoteChild;
185
186static void EnableDebugger() {
187 // To let a non-privileged gdbserver attach to this
188 // process, we must set our dumpable flag.
189 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
190 PLOG(ERROR) << "prctl(PR_SET_DUMPABLE) failed for pid " << getpid();
191 }
192 // We don't want core dumps, though, so set the core dump size to 0.
193 rlimit rl;
194 rl.rlim_cur = 0;
195 rl.rlim_max = RLIM_INFINITY;
196 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
197 PLOG(ERROR) << "setrlimit(RLIMIT_CORE) failed for pid " << getpid();
198 }
199}
200
201static void EnableKeepCapabilities() {
202 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
203 if (rc == -1) {
204 PLOG(FATAL) << "prctl(PR_SET_KEEPCAPS) failed";
205 }
206}
207
Elliott Hughes76e36942012-03-16 13:44:56 -0700208static void SetCapabilities(int64_t permitted, int64_t effective) {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700209 __user_cap_header_struct capheader;
210 __user_cap_data_struct capdata;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700211
212 memset(&capheader, 0, sizeof(capheader));
213 memset(&capdata, 0, sizeof(capdata));
214
215 capheader.version = _LINUX_CAPABILITY_VERSION;
216 capheader.pid = 0;
217
218 capdata.effective = effective;
219 capdata.permitted = permitted;
220
221 if (capset(&capheader, &capdata) != 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800222 PLOG(FATAL) << "capset(" << permitted << ", " << effective << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700223 }
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700224}
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700225
226static void SetSchedulerPolicy() {
227 errno = -set_sched_policy(0, SP_DEFAULT);
228 if (errno != 0) {
229 PLOG(FATAL) << "set_sched_policy(0, SP_DEFAULT) failed";
230 }
231}
232
Elliott Hughes76e36942012-03-16 13:44:56 -0700233#else
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700234
235static int gMallocLeakZygoteChild = 0;
236
237static void EnableDebugger() {}
238static void EnableKeepCapabilities() {}
Elliott Hughes76e36942012-03-16 13:44:56 -0700239static void SetCapabilities(int64_t, int64_t) {}
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700240static void SetSchedulerPolicy() {}
241
Elliott Hughes76e36942012-03-16 13:44:56 -0700242#endif
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700243
Elliott Hughes0512f022012-03-15 22:10:52 -0700244static void EnableDebugFeatures(uint32_t debug_flags) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700245 // Must match values in dalvik.system.Zygote.
246 enum {
247 DEBUG_ENABLE_DEBUGGER = 1,
248 DEBUG_ENABLE_CHECKJNI = 1 << 1,
249 DEBUG_ENABLE_ASSERT = 1 << 2,
250 DEBUG_ENABLE_SAFEMODE = 1 << 3,
251 DEBUG_ENABLE_JNI_LOGGING = 1 << 4,
252 };
253
254 if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
255 Runtime* runtime = Runtime::Current();
256 JavaVMExt* vm = runtime->GetJavaVM();
257 if (!vm->check_jni) {
258 LOG(DEBUG) << "Late-enabling -Xcheck:jni";
Elliott Hughes88c5c352012-03-15 18:49:48 -0700259 vm->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700260 // There's only one thread running at this point, so only one JNIEnv to fix up.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700261 Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700262 } else {
263 LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
264 }
265 debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
266 }
267
268 if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800269 gLogVerbosity.third_party_jni = true;
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700270 debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
271 }
272
273 Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700274 if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700275 EnableDebugger();
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700276 }
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700277 debug_flags &= ~DEBUG_ENABLE_DEBUGGER;
278
279 // These two are for backwards compatibility with Dalvik.
280 debug_flags &= ~DEBUG_ENABLE_ASSERT;
281 debug_flags &= ~DEBUG_ENABLE_SAFEMODE;
282
283 if (debug_flags != 0) {
284 LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
285 }
286}
287
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700288// Utility routine to fork zygote and specialize the child process.
Elliott Hughes0512f022012-03-15 22:10:52 -0700289static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
290 jint debug_flags, jobjectArray javaRlimits,
291 jlong permittedCapabilities, jlong effectiveCapabilities) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700292 Runtime* runtime = Runtime::Current();
293 CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
294 if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
295 LOG(FATAL) << "pre-fork heap failed";
296 }
297
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700298 SetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700299
300 // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
301 Thread* self = Thread::Current();
302
303 // dvmDumpLoaderStats("zygote"); // TODO: ?
304 pid_t pid = fork();
305
306 if (pid == 0) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700307 // The child process.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700308 gMallocLeakZygoteChild = 1;
309
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700310 // Keep capabilities across UID change, unless we're staying root.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700311 if (uid != 0) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700312 EnableKeepCapabilities();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700313 }
314
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700315 SetGids(env, javaGids);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700316
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700317 SetRLimits(env, javaRlimits);
318
319 int rc = setgid(gid);
320 if (rc == -1) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800321 PLOG(FATAL) << "setgid(" << gid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700322 }
323
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700324 rc = setuid(uid);
325 if (rc == -1) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800326 PLOG(FATAL) << "setuid(" << uid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700327 }
328
Brian Carlstrom154cef62012-05-02 22:34:03 -0700329#if defined(__linux__)
Elliott Hughes51e53862012-05-02 17:17:28 -0700330 // Work around ARM kernel ASLR lossage (http://b/5817320).
331 int old_personality = personality(0xffffffff);
332 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
333 if (new_personality == -1) {
334 PLOG(WARNING) << "personality(" << new_personality << ") failed";
335 }
Brian Carlstrom154cef62012-05-02 22:34:03 -0700336#endif
Elliott Hughes51e53862012-05-02 17:17:28 -0700337
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800338 SetCapabilities(permittedCapabilities, effectiveCapabilities);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700339
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700340 SetSchedulerPolicy();
Elliott Hughesb6636b82012-04-24 10:41:16 -0700341
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700342 // Our system thread ID, etc, has changed so reset Thread state.
343 self->InitAfterFork();
344
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700345 EnableDebugFeatures(debug_flags);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700346
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700347 UnsetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700348 runtime->DidForkFromZygote();
349 } else if (pid > 0) {
350 // the parent process
351 }
352 return pid;
353}
354
Elliott Hughes0512f022012-03-15 22:10:52 -0700355static jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
356 jint debug_flags, jobjectArray rlimits) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700357 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, 0, 0);
Brian Carlstroma9f19782011-10-13 00:14:47 -0700358}
359
Elliott Hughes0512f022012-03-15 22:10:52 -0700360static jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
361 jint debug_flags, jobjectArray rlimits,
362 jlong permittedCapabilities, jlong effectiveCapabilities) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700363 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
364 debug_flags, rlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700365 permittedCapabilities, effectiveCapabilities);
366 if (pid > 0) {
367 // The zygote process checks whether the child process has died or not.
368 LOG(INFO) << "System server process " << pid << " has been created";
369 gSystemServerPid = pid;
370 // There is a slight window that the system server process has crashed
371 // but it went unnoticed because we haven't published its pid yet. So
372 // we recheck here just to make sure that all is well.
373 int status;
374 if (waitpid(pid, &status, WNOHANG) == pid) {
375 LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
376 }
377 }
378 return pid;
379}
380
Elliott Hughes01158d72011-09-19 19:47:10 -0700381static JNINativeMethod gMethods[] = {
382 NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
383 //NATIVE_METHOD(Zygote, nativeFork, "()I"),
Brian Carlstroma9f19782011-10-13 00:14:47 -0700384 NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700385 NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
Elliott Hughes01158d72011-09-19 19:47:10 -0700386};
387
Elliott Hughes01158d72011-09-19 19:47:10 -0700388void register_dalvik_system_Zygote(JNIEnv* env) {
389 jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
390}
391
392} // namespace art