blob: 00a011cbbd161ebbd77c20cd2ad3c261c6294934 [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>
19#include <stdlib.h>
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070020#include <sys/prctl.h>
21#include <sys/types.h>
22#include <sys/wait.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070023#include <unistd.h>
24
Elliott Hughes4ffd3132011-10-24 12:06:42 -070025#include "debugger.h"
26#include "jni_internal.h"
27#include "JniConstants.h"
28#include "JNIHelp.h"
29#include "ScopedLocalRef.h"
30#include "ScopedPrimitiveArray.h"
31#include "ScopedUtfChars.h"
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070032#include "thread.h"
33
Elliott Hughes01158d72011-09-19 19:47:10 -070034namespace art {
35
36namespace {
37
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070038static pid_t gSystemServerPid = 0;
39
Elliott Hughes01158d72011-09-19 19:47:10 -070040void Zygote_nativeExecShell(JNIEnv* env, jclass, jstring javaCommand) {
41 ScopedUtfChars command(env, javaCommand);
42 if (command.c_str() == NULL) {
43 return;
44 }
45 const char *argp[] = {_PATH_BSHELL, "-c", command.c_str(), NULL};
46 LOG(INFO) << "Exec: " << argp[0] << ' ' << argp[1] << ' ' << argp[2];
47
48 execv(_PATH_BSHELL, (char**)argp);
49 exit(127);
50}
51
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070052
53// This signal handler is for zygote mode, since the zygote must reap its children
Elliott Hughes4ffd3132011-10-24 12:06:42 -070054void SigChldHandler(int s) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070055 pid_t pid;
56 int status;
57
58 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
59 // Log process-death status that we care about. In general it is
60 // not safe to call LOG(...) from a signal handler because of
61 // possible reentrancy. However, we know a priori that the
62 // current implementation of LOG() is safe to call from a SIGCHLD
63 // handler in the zygote process. If the LOG() implementation
64 // changes its locking strategy or its use of syscalls within the
65 // lazy-init critical section, its use here may become unsafe.
66 if (WIFEXITED(status)) {
67 if (WEXITSTATUS(status)) {
68 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
69 } else if (false) {
70 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
71 }
72 } else if (WIFSIGNALED(status)) {
73 if (WTERMSIG(status) != SIGKILL) {
74 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
75 } else if (false) {
76 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
77 }
78#ifdef WCOREDUMP
79 if (WCOREDUMP(status)) {
80 LOG(INFO) << "Process " << pid << " dumped core";
81 }
82#endif /* ifdef WCOREDUMP */
83 }
84
85 // If the just-crashed process is the system_server, bring down zygote
86 // so that it is restarted by init and system server will be restarted
87 // from there.
88 if (pid == gSystemServerPid) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -070089 LOG(ERROR) << "Exit zygote because system server (" << pid << ") has terminated";
90 kill(getpid(), SIGKILL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070091 }
92 }
93
94 if (pid < 0) {
95 PLOG(WARNING) << "Zygote SIGCHLD error in waitpid";
96 }
97}
98
99// configure sigchld handler for the zygote process This is configured
100// very late, because earlier in the runtime we may fork() and exec()
101// other processes, and we want to waitpid() for those rather than
102// have them be harvested immediately.
103//
104// This ends up being called repeatedly before each fork(), but there's
105// no real harm in that.
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700106void SetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700107 struct sigaction sa;
108 memset(&sa, 0, sizeof(sa));
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700109 sa.sa_handler = SigChldHandler;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700110
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700111 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700112 if (err < 0) {
113 PLOG(WARNING) << "Error setting SIGCHLD handler";
114 }
115}
116
117// Set the SIGCHLD handler back to default behavior in zygote children
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700118void UnsetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700119 struct sigaction sa;
120 memset(&sa, 0, sizeof(sa));
121 sa.sa_handler = SIG_DFL;
122
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700123 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700124 if (err < 0) {
125 PLOG(WARNING) << "Error unsetting SIGCHLD handler";
126 }
127}
128
129// Calls POSIX setgroups() using the int[] object as an argument.
130// A NULL argument is tolerated.
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700131int SetGids(JNIEnv* env, jintArray javaGids) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700132 if (javaGids == NULL) {
133 return 0;
134 }
135
136 COMPILE_ASSERT(sizeof(gid_t) == sizeof(jint), sizeof_gid_and_jint_are_differerent);
137 ScopedIntArrayRO gids(env, javaGids);
138 if (gids.get() == NULL) {
139 return -1;
140 }
141 return setgroups(gids.size(), (const gid_t *) &gids[0]);
142}
143
144// Sets the resource limits via setrlimit(2) for the values in the
145// two-dimensional array of integers that's passed in. The second dimension
146// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
147// treated as an empty array.
148//
149// -1 is returned on error.
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700150int SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700151 if (javaRlimits == NULL) {
152 return 0;
153 }
154
155 struct rlimit rlim;
156 memset(&rlim, 0, sizeof(rlim));
157
158 for (int i = 0; i < env->GetArrayLength(javaRlimits); i++) {
159 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
160 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
161 if (javaRlimit.size() != 3) {
162 LOG(ERROR) << "rlimits array must have a second dimension of size 3";
163 return -1;
164 }
165
166 rlim.rlim_cur = javaRlimit[1];
167 rlim.rlim_max = javaRlimit[2];
168
169 int err = setrlimit(javaRlimit[0], &rlim);
170 if (err < 0) {
171 return -1;
172 }
173 }
174 return 0;
175}
176
177// Set Linux capability flags.
178//
179// Returns 0 on success, errno on failure.
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700180int SetCapabilities(int64_t permitted, int64_t effective) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700181#ifdef HAVE_ANDROID_OS
182 struct __user_cap_header_struct capheader;
183 struct __user_cap_data_struct capdata;
184
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) {
195 return errno;
196 }
197#endif /*HAVE_ANDROID_OS*/
198
199 return 0;
200}
201
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700202void EnableDebugFeatures(uint32_t debug_flags) {
203 // 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";
217 vm->EnableCheckJni();
218 // There's only one thread running at this point, so only one JNIEnv to fix up.
219 Thread::Current()->GetJniEnv()->EnableCheckJni();
220 } 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) {
227 Runtime::Current()->GetJavaVM()->log_third_party_jni = true;
228 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 {
243 struct rlimit rl;
244 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 Hughes4ffd3132011-10-24 12:06:42 -0700268pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
269 jint debug_flags, jobjectArray javaRlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700270 jlong permittedCapabilities, jlong effectiveCapabilities)
271{
272 Runtime* runtime = Runtime::Current();
273 CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
274 if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
275 LOG(FATAL) << "pre-fork heap failed";
276 }
277
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700278 SetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700279
280 // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
281 Thread* self = Thread::Current();
282
283 // dvmDumpLoaderStats("zygote"); // TODO: ?
284 pid_t pid = fork();
285
286 if (pid == 0) {
287 // The child process
288
289#ifdef HAVE_ANDROID_OS
290 gMallocLeakZygoteChild = 1;
291
292 // keep caps across UID change, unless we're staying root */
293 if (uid != 0) {
294 int err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
295 if (err < 0) {
296 PLOG(FATAL) << "cannot PR_SET_KEEPCAPS";
297 }
298 }
299#endif // HAVE_ANDROID_OS
300
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700301 int err = SetGids(env, javaGids);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700302 if (err < 0) {
303 PLOG(FATAL) << "cannot setgroups()";
304 }
305
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700306 err = SetRLimits(env, javaRlimits);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700307 if (err < 0) {
308 PLOG(FATAL) << "cannot setrlimit()";
309 }
310
311 err = setgid(gid);
312 if (err < 0) {
313 PLOG(FATAL) << "cannot setgid(" << gid << ")";
314 }
315
316 err = setuid(uid);
317 if (err < 0) {
318 PLOG(FATAL) << "cannot setuid(" << uid << ")";
319 }
320
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700321 err = SetCapabilities(permittedCapabilities, effectiveCapabilities);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700322 if (err != 0) {
323 PLOG(FATAL) << "cannot set capabilities ("
324 << permittedCapabilities << "," << effectiveCapabilities << ")";
325 }
326
327 // Our system thread ID, etc, has changed so reset Thread state.
328 self->InitAfterFork();
329
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700330 EnableDebugFeatures(debug_flags);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700331
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700332 UnsetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700333 runtime->DidForkFromZygote();
334 } else if (pid > 0) {
335 // the parent process
336 }
337 return pid;
338}
339
Brian Carlstroma9f19782011-10-13 00:14:47 -0700340jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700341 jint debug_flags, jobjectArray rlimits) {
342 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, 0, 0);
Brian Carlstroma9f19782011-10-13 00:14:47 -0700343}
344
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700345jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700346 jint debug_flags, jobjectArray rlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700347 jlong permittedCapabilities, jlong effectiveCapabilities) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700348 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
349 debug_flags, rlimits,
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700350 permittedCapabilities, effectiveCapabilities);
351 if (pid > 0) {
352 // The zygote process checks whether the child process has died or not.
353 LOG(INFO) << "System server process " << pid << " has been created";
354 gSystemServerPid = pid;
355 // There is a slight window that the system server process has crashed
356 // but it went unnoticed because we haven't published its pid yet. So
357 // we recheck here just to make sure that all is well.
358 int status;
359 if (waitpid(pid, &status, WNOHANG) == pid) {
360 LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
361 }
362 }
363 return pid;
364}
365
Elliott Hughes01158d72011-09-19 19:47:10 -0700366static JNINativeMethod gMethods[] = {
367 NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
368 //NATIVE_METHOD(Zygote, nativeFork, "()I"),
Brian Carlstroma9f19782011-10-13 00:14:47 -0700369 NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700370 NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
Elliott Hughes01158d72011-09-19 19:47:10 -0700371};
372
373} // namespace
374
375void register_dalvik_system_Zygote(JNIEnv* env) {
376 jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
377}
378
379} // namespace art