blob: 3751e1322ec6bf086185614e094e47dba8f66bee [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
17#include "jni_internal.h"
18#include "JNIHelp.h"
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070019#include "ScopedLocalRef.h"
20#include "ScopedPrimitiveArray.h"
Elliott Hughes01158d72011-09-19 19:47:10 -070021#include "ScopedUtfChars.h"
22
23#include "JniConstants.h" // Last to avoid problems with LOG redefinition.
24
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070025#include <grp.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070026#include <paths.h>
27#include <stdlib.h>
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070028#include <sys/prctl.h>
29#include <sys/types.h>
30#include <sys/wait.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070031#include <unistd.h>
32
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 }
46 const char *argp[] = {_PATH_BSHELL, "-c", command.c_str(), NULL};
47 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
55void sigchldHandler(int s) {
56 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.
107void setSigchldHandler() {
108 struct sigaction sa;
109 memset(&sa, 0, sizeof(sa));
110 sa.sa_handler = sigchldHandler;
111
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
119void unsetSigchldHandler() {
120 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.
132int setGids(JNIEnv* env, jintArray javaGids) {
133 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.
151int setRlimits(JNIEnv* env, jobjectArray javaRlimits) {
152 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
178// Set Linux capability flags.
179//
180// Returns 0 on success, errno on failure.
181int setCapabilities(int64_t permitted, int64_t effective) {
182#ifdef HAVE_ANDROID_OS
183 struct __user_cap_header_struct capheader;
184 struct __user_cap_data_struct capdata;
185
186 memset(&capheader, 0, sizeof(capheader));
187 memset(&capdata, 0, sizeof(capdata));
188
189 capheader.version = _LINUX_CAPABILITY_VERSION;
190 capheader.pid = 0;
191
192 capdata.effective = effective;
193 capdata.permitted = permitted;
194
195 if (capset(&capheader, &capdata) != 0) {
196 return errno;
197 }
198#endif /*HAVE_ANDROID_OS*/
199
200 return 0;
201}
202
203#ifdef HAVE_ANDROID_OS
204extern "C" int gMallocLeakZygoteChild;
205#endif
206
207// Utility routine to fork zygote and specialize the child process.
208pid_t forkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
209 jint debugFlags, jobjectArray javaRlimits,
210 jlong permittedCapabilities, jlong effectiveCapabilities)
211{
212 Runtime* runtime = Runtime::Current();
213 CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
214 if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
215 LOG(FATAL) << "pre-fork heap failed";
216 }
217
218 setSigchldHandler();
219
220 // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
221 Thread* self = Thread::Current();
222
223 // dvmDumpLoaderStats("zygote"); // TODO: ?
224 pid_t pid = fork();
225
226 if (pid == 0) {
227 // The child process
228
229#ifdef HAVE_ANDROID_OS
230 gMallocLeakZygoteChild = 1;
231
232 // keep caps across UID change, unless we're staying root */
233 if (uid != 0) {
234 int err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
235 if (err < 0) {
236 PLOG(FATAL) << "cannot PR_SET_KEEPCAPS";
237 }
238 }
239#endif // HAVE_ANDROID_OS
240
241 int err = setGids(env, javaGids);
242 if (err < 0) {
243 PLOG(FATAL) << "cannot setgroups()";
244 }
245
246 err = setRlimits(env, javaRlimits);
247 if (err < 0) {
248 PLOG(FATAL) << "cannot setrlimit()";
249 }
250
251 err = setgid(gid);
252 if (err < 0) {
253 PLOG(FATAL) << "cannot setgid(" << gid << ")";
254 }
255
256 err = setuid(uid);
257 if (err < 0) {
258 PLOG(FATAL) << "cannot setuid(" << uid << ")";
259 }
260
261 err = setCapabilities(permittedCapabilities, effectiveCapabilities);
262 if (err != 0) {
263 PLOG(FATAL) << "cannot set capabilities ("
264 << permittedCapabilities << "," << effectiveCapabilities << ")";
265 }
266
267 // Our system thread ID, etc, has changed so reset Thread state.
268 self->InitAfterFork();
269
270 // configure additional debug options
271 // enableDebugFeatures(debugFlags); // TODO: debugger
272
273 unsetSigchldHandler();
274 runtime->DidForkFromZygote();
275 } else if (pid > 0) {
276 // the parent process
277 }
278 return pid;
279}
280
Brian Carlstroma9f19782011-10-13 00:14:47 -0700281jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
282 jint debugFlags, jobjectArray rlimits) {
283 return forkAndSpecializeCommon(env, uid, gid, gids, debugFlags, rlimits, 0, 0);
284}
285
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700286jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
287 jint debugFlags, jobjectArray rlimits,
288 jlong permittedCapabilities, jlong effectiveCapabilities) {
289 pid_t pid = forkAndSpecializeCommon(env, uid, gid, gids,
290 debugFlags, rlimits,
291 permittedCapabilities, effectiveCapabilities);
292 if (pid > 0) {
293 // The zygote process checks whether the child process has died or not.
294 LOG(INFO) << "System server process " << pid << " has been created";
295 gSystemServerPid = pid;
296 // There is a slight window that the system server process has crashed
297 // but it went unnoticed because we haven't published its pid yet. So
298 // we recheck here just to make sure that all is well.
299 int status;
300 if (waitpid(pid, &status, WNOHANG) == pid) {
301 LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
302 }
303 }
304 return pid;
305}
306
Elliott Hughes01158d72011-09-19 19:47:10 -0700307static JNINativeMethod gMethods[] = {
308 NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
309 //NATIVE_METHOD(Zygote, nativeFork, "()I"),
Brian Carlstroma9f19782011-10-13 00:14:47 -0700310 NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700311 NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
Elliott Hughes01158d72011-09-19 19:47:10 -0700312};
313
314} // namespace
315
316void register_dalvik_system_Zygote(JNIEnv* env) {
317 jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
318}
319
320} // namespace art