blob: 49556bf4da1e9c549a286f2d0be17d9128bbf4e7 [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/prctl.h>
22#include <sys/types.h>
23#include <sys/wait.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070024#include <unistd.h>
25
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 Hughes01158d72011-09-19 19:47:10 -070035namespace art {
36
37namespace {
38
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070039static pid_t gSystemServerPid = 0;
40
Elliott Hughes01158d72011-09-19 19:47:10 -070041void Zygote_nativeExecShell(JNIEnv* env, jclass, jstring javaCommand) {
42 ScopedUtfChars command(env, javaCommand);
43 if (command.c_str() == NULL) {
44 return;
45 }
Elliott Hughesc1f143d2011-12-01 17:31:10 -080046 const char* argp[] = {_PATH_BSHELL, "-c", command.c_str(), NULL};
Elliott Hughes01158d72011-09-19 19:47:10 -070047 LOG(INFO) << "Exec: " << argp[0] << ' ' << argp[1] << ' ' << argp[2];
48
49 execv(_PATH_BSHELL, (char**)argp);
50 exit(127);
51}
52
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070053
54// This signal handler is for zygote mode, since the zygote must reap its children
Elliott Hughes4ffd3132011-10-24 12:06:42 -070055void SigChldHandler(int s) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070056 pid_t pid;
57 int status;
58
59 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
60 // Log process-death status that we care about. In general it is
61 // not safe to call LOG(...) from a signal handler because of
62 // possible reentrancy. However, we know a priori that the
63 // current implementation of LOG() is safe to call from a SIGCHLD
64 // handler in the zygote process. If the LOG() implementation
65 // changes its locking strategy or its use of syscalls within the
66 // lazy-init critical section, its use here may become unsafe.
67 if (WIFEXITED(status)) {
68 if (WEXITSTATUS(status)) {
69 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
70 } else if (false) {
71 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
72 }
73 } else if (WIFSIGNALED(status)) {
74 if (WTERMSIG(status) != SIGKILL) {
75 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
76 } else if (false) {
77 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
78 }
79#ifdef WCOREDUMP
80 if (WCOREDUMP(status)) {
81 LOG(INFO) << "Process " << pid << " dumped core";
82 }
83#endif /* ifdef WCOREDUMP */
84 }
85
86 // If the just-crashed process is the system_server, bring down zygote
87 // so that it is restarted by init and system server will be restarted
88 // from there.
89 if (pid == gSystemServerPid) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -070090 LOG(ERROR) << "Exit zygote because system server (" << pid << ") has terminated";
91 kill(getpid(), SIGKILL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070092 }
93 }
94
95 if (pid < 0) {
96 PLOG(WARNING) << "Zygote SIGCHLD error in waitpid";
97 }
98}
99
100// configure sigchld handler for the zygote process This is configured
101// very late, because earlier in the runtime we may fork() and exec()
102// other processes, and we want to waitpid() for those rather than
103// have them be harvested immediately.
104//
105// This ends up being called repeatedly before each fork(), but there's
106// no real harm in that.
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700107void SetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700108 struct sigaction sa;
109 memset(&sa, 0, sizeof(sa));
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700110 sa.sa_handler = SigChldHandler;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700111
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700112 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700113 if (err < 0) {
114 PLOG(WARNING) << "Error setting SIGCHLD handler";
115 }
116}
117
118// Set the SIGCHLD handler back to default behavior in zygote children
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700119void UnsetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700120 struct sigaction sa;
121 memset(&sa, 0, sizeof(sa));
122 sa.sa_handler = SIG_DFL;
123
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700124 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700125 if (err < 0) {
126 PLOG(WARNING) << "Error unsetting SIGCHLD handler";
127 }
128}
129
130// Calls POSIX setgroups() using the int[] object as an argument.
131// A NULL argument is tolerated.
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700132int SetGids(JNIEnv* env, jintArray javaGids) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700133 if (javaGids == NULL) {
134 return 0;
135 }
136
137 COMPILE_ASSERT(sizeof(gid_t) == sizeof(jint), sizeof_gid_and_jint_are_differerent);
138 ScopedIntArrayRO gids(env, javaGids);
139 if (gids.get() == NULL) {
140 return -1;
141 }
142 return setgroups(gids.size(), (const gid_t *) &gids[0]);
143}
144
145// Sets the resource limits via setrlimit(2) for the values in the
146// two-dimensional array of integers that's passed in. The second dimension
147// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
148// treated as an empty array.
149//
150// -1 is returned on error.
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700151int SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700152 if (javaRlimits == NULL) {
153 return 0;
154 }
155
156 struct rlimit rlim;
157 memset(&rlim, 0, sizeof(rlim));
158
159 for (int i = 0; i < env->GetArrayLength(javaRlimits); i++) {
160 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
161 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
162 if (javaRlimit.size() != 3) {
163 LOG(ERROR) << "rlimits array must have a second dimension of size 3";
164 return -1;
165 }
166
167 rlim.rlim_cur = javaRlimit[1];
168 rlim.rlim_max = javaRlimit[2];
169
170 int err = setrlimit(javaRlimit[0], &rlim);
171 if (err < 0) {
172 return -1;
173 }
174 }
175 return 0;
176}
177
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800178void SetCapabilities(int64_t permitted, int64_t effective) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700179#ifdef HAVE_ANDROID_OS
180 struct __user_cap_header_struct capheader;
181 struct __user_cap_data_struct capdata;
182
183 memset(&capheader, 0, sizeof(capheader));
184 memset(&capdata, 0, sizeof(capdata));
185
186 capheader.version = _LINUX_CAPABILITY_VERSION;
187 capheader.pid = 0;
188
189 capdata.effective = effective;
190 capdata.permitted = permitted;
191
192 if (capset(&capheader, &capdata) != 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800193 PLOG(FATAL) << "capset(" << permitted << ", " << effective << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700194 }
195#endif /*HAVE_ANDROID_OS*/
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700196}
197
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700198void EnableDebugFeatures(uint32_t debug_flags) {
199 // Must match values in dalvik.system.Zygote.
200 enum {
201 DEBUG_ENABLE_DEBUGGER = 1,
202 DEBUG_ENABLE_CHECKJNI = 1 << 1,
203 DEBUG_ENABLE_ASSERT = 1 << 2,
204 DEBUG_ENABLE_SAFEMODE = 1 << 3,
205 DEBUG_ENABLE_JNI_LOGGING = 1 << 4,
206 };
207
208 if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
209 Runtime* runtime = Runtime::Current();
210 JavaVMExt* vm = runtime->GetJavaVM();
211 if (!vm->check_jni) {
212 LOG(DEBUG) << "Late-enabling -Xcheck:jni";
213 vm->EnableCheckJni();
214 // There's only one thread running at this point, so only one JNIEnv to fix up.
215 Thread::Current()->GetJniEnv()->EnableCheckJni();
216 } else {
217 LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
218 }
219 debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
220 }
221
222 if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800223 gLogVerbosity.third_party_jni = true;
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700224 debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
225 }
226
227 Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
228#ifdef HAVE_ANDROID_OS
229 if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
230 /* To let a non-privileged gdbserver attach to this
231 * process, we must set its dumpable bit flag. However
232 * we are not interested in generating a coredump in
233 * case of a crash, so also set the coredump size to 0
234 * to disable that
235 */
236 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
237 PLOG(ERROR) << "could not set dumpable bit flag for pid " << getpid();
238 } else {
239 struct rlimit rl;
240 rl.rlim_cur = 0;
241 rl.rlim_max = RLIM_INFINITY;
242 if (setrlimit(RLIMIT_CORE, &rl) < 0) {
243 PLOG(ERROR) << "could not disable core file generation for pid " << getpid();
244 }
245 }
246 }
247#endif
248 debug_flags &= ~DEBUG_ENABLE_DEBUGGER;
249
250 // These two are for backwards compatibility with Dalvik.
251 debug_flags &= ~DEBUG_ENABLE_ASSERT;
252 debug_flags &= ~DEBUG_ENABLE_SAFEMODE;
253
254 if (debug_flags != 0) {
255 LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
256 }
257}
258
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700259#ifdef HAVE_ANDROID_OS
260extern "C" int gMallocLeakZygoteChild;
261#endif
262
263// Utility routine to fork zygote and specialize the child process.
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700264pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
265 jint debug_flags, jobjectArray javaRlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700266 jlong permittedCapabilities, jlong effectiveCapabilities)
267{
268 Runtime* runtime = Runtime::Current();
269 CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
270 if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
271 LOG(FATAL) << "pre-fork heap failed";
272 }
273
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700274 SetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700275
276 // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
277 Thread* self = Thread::Current();
278
279 // dvmDumpLoaderStats("zygote"); // TODO: ?
280 pid_t pid = fork();
281
282 if (pid == 0) {
283 // The child process
284
285#ifdef HAVE_ANDROID_OS
286 gMallocLeakZygoteChild = 1;
287
288 // keep caps across UID change, unless we're staying root */
289 if (uid != 0) {
290 int err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
291 if (err < 0) {
292 PLOG(FATAL) << "cannot PR_SET_KEEPCAPS";
293 }
294 }
295#endif // HAVE_ANDROID_OS
296
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700297 int err = SetGids(env, javaGids);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700298 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800299 PLOG(FATAL) << "setgroups failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700300 }
301
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700302 err = SetRLimits(env, javaRlimits);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700303 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800304 PLOG(FATAL) << "setrlimit failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700305 }
306
307 err = setgid(gid);
308 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800309 PLOG(FATAL) << "setgid(" << gid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700310 }
311
312 err = setuid(uid);
313 if (err < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800314 PLOG(FATAL) << "setuid(" << uid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700315 }
316
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800317 SetCapabilities(permittedCapabilities, effectiveCapabilities);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700318
319 // Our system thread ID, etc, has changed so reset Thread state.
320 self->InitAfterFork();
321
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700322 EnableDebugFeatures(debug_flags);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700323
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700324 UnsetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700325 runtime->DidForkFromZygote();
326 } else if (pid > 0) {
327 // the parent process
328 }
329 return pid;
330}
331
Brian Carlstroma9f19782011-10-13 00:14:47 -0700332jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700333 jint debug_flags, jobjectArray rlimits) {
334 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, 0, 0);
Brian Carlstroma9f19782011-10-13 00:14:47 -0700335}
336
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700337jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700338 jint debug_flags, jobjectArray rlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700339 jlong permittedCapabilities, jlong effectiveCapabilities) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700340 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
341 debug_flags, rlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700342 permittedCapabilities, effectiveCapabilities);
343 if (pid > 0) {
344 // The zygote process checks whether the child process has died or not.
345 LOG(INFO) << "System server process " << pid << " has been created";
346 gSystemServerPid = pid;
347 // There is a slight window that the system server process has crashed
348 // but it went unnoticed because we haven't published its pid yet. So
349 // we recheck here just to make sure that all is well.
350 int status;
351 if (waitpid(pid, &status, WNOHANG) == pid) {
352 LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
353 }
354 }
355 return pid;
356}
357
Elliott Hughes01158d72011-09-19 19:47:10 -0700358static JNINativeMethod gMethods[] = {
359 NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
360 //NATIVE_METHOD(Zygote, nativeFork, "()I"),
Brian Carlstroma9f19782011-10-13 00:14:47 -0700361 NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700362 NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
Elliott Hughes01158d72011-09-19 19:47:10 -0700363};
364
365} // namespace
366
367void register_dalvik_system_Zygote(JNIEnv* env) {
368 jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
369}
370
371} // namespace art