blob: 7c0b6a630c2f4a7a08128a78999d7ec14cfb49da [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) {
90 LOG(FATAL) << "Exit zygote because system server (" << pid << ") has terminated";
91 }
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.
106void setSigchldHandler() {
107 struct sigaction sa;
108 memset(&sa, 0, sizeof(sa));
109 sa.sa_handler = sigchldHandler;
110
111 int err = sigaction (SIGCHLD, &sa, NULL);
112 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
118void unsetSigchldHandler() {
119 struct sigaction sa;
120 memset(&sa, 0, sizeof(sa));
121 sa.sa_handler = SIG_DFL;
122
123 int err = sigaction (SIGCHLD, &sa, NULL);
124 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.
131int setGids(JNIEnv* env, jintArray javaGids) {
132 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.
150int setRlimits(JNIEnv* env, jobjectArray javaRlimits) {
151 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.
180int setCapabilities(int64_t permitted, int64_t effective) {
181#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
202#ifdef HAVE_ANDROID_OS
203extern "C" int gMallocLeakZygoteChild;
204#endif
205
206// Utility routine to fork zygote and specialize the child process.
207pid_t forkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
208 jint debugFlags, jobjectArray javaRlimits,
209 jlong permittedCapabilities, jlong effectiveCapabilities)
210{
211 Runtime* runtime = Runtime::Current();
212 CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
213 if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
214 LOG(FATAL) << "pre-fork heap failed";
215 }
216
217 setSigchldHandler();
218
219 // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
220 Thread* self = Thread::Current();
221
222 // dvmDumpLoaderStats("zygote"); // TODO: ?
223 pid_t pid = fork();
224
225 if (pid == 0) {
226 // The child process
227
228#ifdef HAVE_ANDROID_OS
229 gMallocLeakZygoteChild = 1;
230
231 // keep caps across UID change, unless we're staying root */
232 if (uid != 0) {
233 int err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
234 if (err < 0) {
235 PLOG(FATAL) << "cannot PR_SET_KEEPCAPS";
236 }
237 }
238#endif // HAVE_ANDROID_OS
239
240 int err = setGids(env, javaGids);
241 if (err < 0) {
242 PLOG(FATAL) << "cannot setgroups()";
243 }
244
245 err = setRlimits(env, javaRlimits);
246 if (err < 0) {
247 PLOG(FATAL) << "cannot setrlimit()";
248 }
249
250 err = setgid(gid);
251 if (err < 0) {
252 PLOG(FATAL) << "cannot setgid(" << gid << ")";
253 }
254
255 err = setuid(uid);
256 if (err < 0) {
257 PLOG(FATAL) << "cannot setuid(" << uid << ")";
258 }
259
260 err = setCapabilities(permittedCapabilities, effectiveCapabilities);
261 if (err != 0) {
262 PLOG(FATAL) << "cannot set capabilities ("
263 << permittedCapabilities << "," << effectiveCapabilities << ")";
264 }
265
266 // Our system thread ID, etc, has changed so reset Thread state.
267 self->InitAfterFork();
268
269 // configure additional debug options
270 // enableDebugFeatures(debugFlags); // TODO: debugger
271
272 unsetSigchldHandler();
273 runtime->DidForkFromZygote();
274 } else if (pid > 0) {
275 // the parent process
276 }
277 return pid;
278}
279
Brian Carlstroma9f19782011-10-13 00:14:47 -0700280jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
281 jint debugFlags, jobjectArray rlimits) {
282 return forkAndSpecializeCommon(env, uid, gid, gids, debugFlags, rlimits, 0, 0);
283}
284
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700285jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
286 jint debugFlags, jobjectArray rlimits,
287 jlong permittedCapabilities, jlong effectiveCapabilities) {
288 pid_t pid = forkAndSpecializeCommon(env, uid, gid, gids,
289 debugFlags, rlimits,
290 permittedCapabilities, effectiveCapabilities);
291 if (pid > 0) {
292 // The zygote process checks whether the child process has died or not.
293 LOG(INFO) << "System server process " << pid << " has been created";
294 gSystemServerPid = pid;
295 // There is a slight window that the system server process has crashed
296 // but it went unnoticed because we haven't published its pid yet. So
297 // we recheck here just to make sure that all is well.
298 int status;
299 if (waitpid(pid, &status, WNOHANG) == pid) {
300 LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
301 }
302 }
303 return pid;
304}
305
Elliott Hughes01158d72011-09-19 19:47:10 -0700306static JNINativeMethod gMethods[] = {
307 NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
308 //NATIVE_METHOD(Zygote, nativeFork, "()I"),
Brian Carlstroma9f19782011-10-13 00:14:47 -0700309 NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700310 NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
Elliott Hughes01158d72011-09-19 19:47:10 -0700311};
312
313} // namespace
314
315void register_dalvik_system_Zygote(JNIEnv* env) {
316 jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
317}
318
319} // namespace art