blob: 4d009db29ebf155c35ea3e405fe955fffb96b43b [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 Carlstrombd86bcc2013-03-10 20:26:16 -070017// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
18#include <sys/mount.h>
19#include <linux/fs.h>
20
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070021#include <grp.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070022#include <paths.h>
Elliott Hughesada2da92012-01-17 17:58:58 -080023#include <signal.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070024#include <stdlib.h>
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070025#include <sys/types.h>
Dave Platt870901d2014-02-05 17:03:16 -080026#include <sys/stat.h>
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070027#include <sys/wait.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070028#include <unistd.h>
Dave Platt870901d2014-02-05 17:03:16 -080029#include <fcntl.h>
Elliott Hughes01158d72011-09-19 19:47:10 -070030
Brian Carlstrombd86bcc2013-03-10 20:26:16 -070031#include "cutils/fs.h"
32#include "cutils/multiuser.h"
Elliott Hughesb6636b82012-04-24 10:41:16 -070033#include "cutils/sched_policy.h"
Elliott Hughes4ffd3132011-10-24 12:06:42 -070034#include "debugger.h"
35#include "jni_internal.h"
Elliott Hughes4ffd3132011-10-24 12:06:42 -070036#include "JNIHelp.h"
37#include "ScopedLocalRef.h"
38#include "ScopedPrimitiveArray.h"
39#include "ScopedUtfChars.h"
Brian Carlstroma3d27182013-11-05 23:22:27 -080040#include "thread-inl.h"
William Roberts1e7d1d52013-11-11 07:28:37 -080041#include "utils.h"
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070042
Elliott Hughesb4807ec2012-01-17 18:33:04 -080043#if defined(HAVE_PRCTL)
44#include <sys/prctl.h>
45#endif
46
Elliott Hughesc151f902012-06-21 20:33:21 -070047#include <selinux/android.h>
Elliott Hughesc151f902012-06-21 20:33:21 -070048
Brian Carlstrom154cef62012-05-02 22:34:03 -070049#if defined(__linux__)
50#include <sys/personality.h>
Nick Kralevichb7882782012-09-27 12:29:02 -070051#include <sys/utsname.h>
Ian Rogersef7d42f2014-01-06 12:55:46 -080052#if defined(HAVE_ANDROID_OS)
Nick Kralevich2b97c272013-03-01 11:14:38 -080053#include <sys/capability.h>
Brian Carlstrom154cef62012-05-02 22:34:03 -070054#endif
Ian Rogersef7d42f2014-01-06 12:55:46 -080055#endif
Brian Carlstrom154cef62012-05-02 22:34:03 -070056
Elliott Hughes01158d72011-09-19 19:47:10 -070057namespace art {
58
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070059static pid_t gSystemServerPid = 0;
60
Elliott Hughes178cdcc2012-08-16 16:47:31 -070061// Must match values in dalvik.system.Zygote.
62enum MountExternalKind {
63 MOUNT_EXTERNAL_NONE = 0,
64 MOUNT_EXTERNAL_SINGLEUSER = 1,
65 MOUNT_EXTERNAL_MULTIUSER = 2,
Brian Carlstrombd86bcc2013-03-10 20:26:16 -070066 MOUNT_EXTERNAL_MULTIUSER_ALL = 3,
Elliott Hughes178cdcc2012-08-16 16:47:31 -070067};
68
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070069// This signal handler is for zygote mode, since the zygote must reap its children
Elliott Hughes1bac54f2012-03-16 12:48:31 -070070static void SigChldHandler(int /*signal_number*/) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070071 pid_t pid;
72 int status;
73
74 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
75 // Log process-death status that we care about. In general it is
76 // not safe to call LOG(...) from a signal handler because of
77 // possible reentrancy. However, we know a priori that the
78 // current implementation of LOG() is safe to call from a SIGCHLD
79 // handler in the zygote process. If the LOG() implementation
80 // changes its locking strategy or its use of syscalls within the
81 // lazy-init critical section, its use here may become unsafe.
82 if (WIFEXITED(status)) {
83 if (WEXITSTATUS(status)) {
84 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
85 } else if (false) {
86 LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
87 }
88 } else if (WIFSIGNALED(status)) {
89 if (WTERMSIG(status) != SIGKILL) {
90 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
91 } else if (false) {
92 LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
93 }
94#ifdef WCOREDUMP
95 if (WCOREDUMP(status)) {
96 LOG(INFO) << "Process " << pid << " dumped core";
97 }
98#endif /* ifdef WCOREDUMP */
99 }
100
101 // If the just-crashed process is the system_server, bring down zygote
102 // so that it is restarted by init and system server will be restarted
103 // from there.
104 if (pid == gSystemServerPid) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -0700105 LOG(ERROR) << "Exit zygote because system server (" << pid << ") has terminated";
106 kill(getpid(), SIGKILL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700107 }
108 }
109
110 if (pid < 0) {
111 PLOG(WARNING) << "Zygote SIGCHLD error in waitpid";
112 }
113}
114
Elliott Hughes0512f022012-03-15 22:10:52 -0700115// Configures the SIGCHLD handler for the zygote process. This is configured
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700116// very late, because earlier in the runtime we may fork() and exec()
117// other processes, and we want to waitpid() for those rather than
118// have them be harvested immediately.
119//
120// This ends up being called repeatedly before each fork(), but there's
121// no real harm in that.
Elliott Hughes0512f022012-03-15 22:10:52 -0700122static void SetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700123 struct sigaction sa;
124 memset(&sa, 0, sizeof(sa));
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700125 sa.sa_handler = SigChldHandler;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700126
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700127 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700128 if (err < 0) {
129 PLOG(WARNING) << "Error setting SIGCHLD handler";
130 }
131}
132
Elliott Hughes0512f022012-03-15 22:10:52 -0700133// Sets the SIGCHLD handler back to default behavior in zygote children.
134static void UnsetSigChldHandler() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700135 struct sigaction sa;
136 memset(&sa, 0, sizeof(sa));
137 sa.sa_handler = SIG_DFL;
138
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700139 int err = sigaction(SIGCHLD, &sa, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700140 if (err < 0) {
141 PLOG(WARNING) << "Error unsetting SIGCHLD handler";
142 }
143}
144
145// Calls POSIX setgroups() using the int[] object as an argument.
146// A NULL argument is tolerated.
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700147static void SetGids(JNIEnv* env, jintArray javaGids) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700148 if (javaGids == NULL) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700149 return;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700150 }
151
152 COMPILE_ASSERT(sizeof(gid_t) == sizeof(jint), sizeof_gid_and_jint_are_differerent);
153 ScopedIntArrayRO gids(env, javaGids);
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700154 CHECK(gids.get() != NULL);
155 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
156 if (rc == -1) {
157 PLOG(FATAL) << "setgroups failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700158 }
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700159}
160
161// Sets the resource limits via setrlimit(2) for the values in the
162// two-dimensional array of integers that's passed in. The second dimension
163// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
164// treated as an empty array.
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700165static void SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700166 if (javaRlimits == NULL) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700167 return;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700168 }
169
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700170 rlimit rlim;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700171 memset(&rlim, 0, sizeof(rlim));
172
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700173 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700174 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
175 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
176 if (javaRlimit.size() != 3) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700177 LOG(FATAL) << "rlimits array must have a second dimension of size 3";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700178 }
179
180 rlim.rlim_cur = javaRlimit[1];
181 rlim.rlim_max = javaRlimit[2];
182
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700183 int rc = setrlimit(javaRlimit[0], &rlim);
184 if (rc == -1) {
185 PLOG(FATAL) << "setrlimit(" << javaRlimit[0] << ", "
186 << "{" << rlim.rlim_cur << ", " << rlim.rlim_max << "}) failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700187 }
188 }
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700189}
190
Elliott Hughes76e36942012-03-16 13:44:56 -0700191#if defined(HAVE_ANDROID_OS)
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700192
193// The debug malloc library needs to know whether it's the zygote or a child.
194extern "C" int gMallocLeakZygoteChild;
195
196static void EnableDebugger() {
197 // To let a non-privileged gdbserver attach to this
198 // process, we must set our dumpable flag.
199 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
200 PLOG(ERROR) << "prctl(PR_SET_DUMPABLE) failed for pid " << getpid();
201 }
202 // We don't want core dumps, though, so set the core dump size to 0.
203 rlimit rl;
204 rl.rlim_cur = 0;
205 rl.rlim_max = RLIM_INFINITY;
206 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
207 PLOG(ERROR) << "setrlimit(RLIMIT_CORE) failed for pid " << getpid();
208 }
209}
210
211static void EnableKeepCapabilities() {
212 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
213 if (rc == -1) {
214 PLOG(FATAL) << "prctl(PR_SET_KEEPCAPS) failed";
215 }
216}
217
Nick Kralevicha0664be2013-02-13 14:39:17 -0800218static void DropCapabilitiesBoundingSet() {
219 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
Nick Kralevicha0664be2013-02-13 14:39:17 -0800220 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
221 if (rc == -1) {
222 if (errno == EINVAL) {
223 PLOG(ERROR) << "prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
224 << "your kernel is compiled with file capabilities support";
225 } else {
226 PLOG(FATAL) << "prctl(PR_CAPBSET_DROP) failed";
227 }
228 }
229 }
230}
231
Elliott Hughes76e36942012-03-16 13:44:56 -0700232static void SetCapabilities(int64_t permitted, int64_t effective) {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700233 __user_cap_header_struct capheader;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700234 memset(&capheader, 0, sizeof(capheader));
Elliott Hughese1467652013-11-11 11:15:43 -0800235 capheader.version = _LINUX_CAPABILITY_VERSION_3;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700236 capheader.pid = 0;
237
Elliott Hughese1467652013-11-11 11:15:43 -0800238 __user_cap_data_struct capdata[2];
239 memset(&capdata, 0, sizeof(capdata));
240 capdata[0].effective = effective;
241 capdata[1].effective = effective >> 32;
242 capdata[0].permitted = permitted;
243 capdata[1].permitted = permitted >> 32;
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700244
Elliott Hughese1467652013-11-11 11:15:43 -0800245 if (capset(&capheader, &capdata[0]) == -1) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800246 PLOG(FATAL) << "capset(" << permitted << ", " << effective << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700247 }
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700248}
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700249
250static void SetSchedulerPolicy() {
251 errno = -set_sched_policy(0, SP_DEFAULT);
252 if (errno != 0) {
253 PLOG(FATAL) << "set_sched_policy(0, SP_DEFAULT) failed";
254 }
255}
256
Elliott Hughes76e36942012-03-16 13:44:56 -0700257#else
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700258
259static int gMallocLeakZygoteChild = 0;
260
261static void EnableDebugger() {}
262static void EnableKeepCapabilities() {}
Brian Carlstrom9b7085a2013-07-18 15:15:21 -0700263static void DropCapabilitiesBoundingSet() {}
Elliott Hughes76e36942012-03-16 13:44:56 -0700264static void SetCapabilities(int64_t, int64_t) {}
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700265static void SetSchedulerPolicy() {}
266
Elliott Hughes76e36942012-03-16 13:44:56 -0700267#endif
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700268
Elliott Hughes0512f022012-03-15 22:10:52 -0700269static void EnableDebugFeatures(uint32_t debug_flags) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700270 // Must match values in dalvik.system.Zygote.
271 enum {
272 DEBUG_ENABLE_DEBUGGER = 1,
273 DEBUG_ENABLE_CHECKJNI = 1 << 1,
274 DEBUG_ENABLE_ASSERT = 1 << 2,
275 DEBUG_ENABLE_SAFEMODE = 1 << 3,
276 DEBUG_ENABLE_JNI_LOGGING = 1 << 4,
277 };
278
279 if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
280 Runtime* runtime = Runtime::Current();
281 JavaVMExt* vm = runtime->GetJavaVM();
282 if (!vm->check_jni) {
283 LOG(DEBUG) << "Late-enabling -Xcheck:jni";
Elliott Hughes88c5c352012-03-15 18:49:48 -0700284 vm->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700285 // There's only one thread running at this point, so only one JNIEnv to fix up.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700286 Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700287 } else {
288 LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
289 }
290 debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
291 }
292
293 if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800294 gLogVerbosity.third_party_jni = true;
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700295 debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
296 }
297
298 Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700299 if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700300 EnableDebugger();
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700301 }
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700302 debug_flags &= ~DEBUG_ENABLE_DEBUGGER;
303
304 // These two are for backwards compatibility with Dalvik.
305 debug_flags &= ~DEBUG_ENABLE_ASSERT;
306 debug_flags &= ~DEBUG_ENABLE_SAFEMODE;
307
308 if (debug_flags != 0) {
309 LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
310 }
311}
312
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700313// Create a private mount namespace and bind mount appropriate emulated
314// storage for the given user.
315static bool MountEmulatedStorage(uid_t uid, jint mount_mode) {
316 if (mount_mode == MOUNT_EXTERNAL_NONE) {
317 return true;
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700318 }
319
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700320 // See storage config details at http://source.android.com/tech/storage/
321 userid_t user_id = multiuser_get_user_id(uid);
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700322
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700323 // Create a second private mount namespace for our process
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700324 if (unshare(CLONE_NEWNS) == -1) {
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700325 PLOG(WARNING) << "Failed to unshare()";
326 return false;
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700327 }
328
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700329 // Create bind mounts to expose external storage
330 if (mount_mode == MOUNT_EXTERNAL_MULTIUSER || mount_mode == MOUNT_EXTERNAL_MULTIUSER_ALL) {
331 // These paths must already be created by init.rc
332 const char* source = getenv("EMULATED_STORAGE_SOURCE");
333 const char* target = getenv("EMULATED_STORAGE_TARGET");
334 const char* legacy = getenv("EXTERNAL_STORAGE");
335 if (source == NULL || target == NULL || legacy == NULL) {
336 LOG(WARNING) << "Storage environment undefined; unable to provide external storage";
337 return false;
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700338 }
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700339
340 // Prepare source paths
341
342 // /mnt/shell/emulated/0
343 std::string source_user(StringPrintf("%s/%d", source, user_id));
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700344 // /storage/emulated/0
345 std::string target_user(StringPrintf("%s/%d", target, user_id));
346
347 if (fs_prepare_dir(source_user.c_str(), 0000, 0, 0) == -1
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700348 || fs_prepare_dir(target_user.c_str(), 0000, 0, 0) == -1) {
349 return false;
350 }
351
352 if (mount_mode == MOUNT_EXTERNAL_MULTIUSER_ALL) {
353 // Mount entire external storage tree for all users
Brian Carlstrom01add2c2013-12-16 09:50:35 -0800354 if (TEMP_FAILURE_RETRY(mount(source, target, NULL, MS_BIND, NULL)) == -1) {
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700355 PLOG(WARNING) << "Failed to mount " << source << " to " << target;
356 return false;
357 }
358 } else {
359 // Only mount user-specific external storage
Brian Carlstrom01add2c2013-12-16 09:50:35 -0800360 if (TEMP_FAILURE_RETRY(
361 mount(source_user.c_str(), target_user.c_str(), NULL, MS_BIND, NULL)) == -1) {
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700362 PLOG(WARNING) << "Failed to mount " << source_user << " to " << target_user;
363 return false;
364 }
365 }
366
Jeff Sharkeyb8c46fc2013-09-10 18:28:10 -0700367 if (fs_prepare_dir(legacy, 0000, 0, 0) == -1) {
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700368 return false;
369 }
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700370
371 // Finally, mount user-specific path into place for legacy users
Brian Carlstrom01add2c2013-12-16 09:50:35 -0800372 if (TEMP_FAILURE_RETRY(
373 mount(target_user.c_str(), legacy, NULL, MS_BIND | MS_REC, NULL)) == -1) {
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700374 PLOG(WARNING) << "Failed to mount " << target_user << " to " << legacy;
375 return false;
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700376 }
377 } else {
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700378 LOG(WARNING) << "Mount mode " << mount_mode << " unsupported";
379 return false;
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700380 }
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700381
382 return true;
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700383}
384
Nick Kralevichb7882782012-09-27 12:29:02 -0700385#if defined(__linux__)
386static bool NeedsNoRandomizeWorkaround() {
Nick Kralevich50e17442012-10-19 13:02:37 -0700387#if !defined(__arm__)
388 return false;
389#else
Nick Kralevichb7882782012-09-27 12:29:02 -0700390 int major;
391 int minor;
392 struct utsname uts;
393 if (uname(&uts) == -1) {
394 return false;
395 }
396
397 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
398 return false;
399 }
400
401 // Kernels before 3.4.* need the workaround.
402 return (major < 3) || ((major == 3) && (minor < 4));
Nick Kralevich50e17442012-10-19 13:02:37 -0700403#endif
Nick Kralevichb7882782012-09-27 12:29:02 -0700404}
405#endif
406
Dave Platt870901d2014-02-05 17:03:16 -0800407// Utility to close down the Zygote socket file descriptors while
408// the child is still running as root with Zygote's privileges. Each
409// descriptor (if any) is closed via dup2(), replacing it with a valid
410// (open) descriptor to /dev/null.
411
412static void DetachDescriptors(JNIEnv* env, jintArray fdsToClose) {
413 if (!fdsToClose) {
414 return;
415 }
416 jsize count = env->GetArrayLength(fdsToClose);
417 jint *ar = env->GetIntArrayElements(fdsToClose, 0);
418 if (!ar) {
419 PLOG(FATAL) << "Bad fd array";
420 }
421 jsize i;
422 int devnull;
423 for (i = 0; i < count; i++) {
424 devnull = open("/dev/null", O_RDWR);
425 if (devnull < 0) {
426 PLOG(FATAL) << "Failed to open /dev/null";
427 continue;
428 }
429 PLOG(VERBOSE) << "Switching descriptor " << ar[i] << " to /dev/null";
430 if (dup2(devnull, ar[i]) < 0) {
431 PLOG(FATAL) << "Failed dup2() on descriptor " << ar[i];
432 }
433 close(devnull);
434 }
435}
436
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700437// Utility routine to fork zygote and specialize the child process.
Elliott Hughes0512f022012-03-15 22:10:52 -0700438static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
439 jint debug_flags, jobjectArray javaRlimits,
Elliott Hughesc151f902012-06-21 20:33:21 -0700440 jlong permittedCapabilities, jlong effectiveCapabilities,
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700441 jint mount_external,
Brian Carlstrom01add2c2013-12-16 09:50:35 -0800442 jstring java_se_info, jstring java_se_name,
Dave Platt870901d2014-02-05 17:03:16 -0800443 bool is_system_server, jintArray fdsToClose) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700444 Runtime* runtime = Runtime::Current();
445 CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700446 if (!runtime->PreZygoteFork()) {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700447 LOG(FATAL) << "pre-fork heap failed";
448 }
449
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700450 SetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700451
452 // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
453 Thread* self = Thread::Current();
454
455 // dvmDumpLoaderStats("zygote"); // TODO: ?
456 pid_t pid = fork();
457
458 if (pid == 0) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700459 // The child process.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700460 gMallocLeakZygoteChild = 1;
461
Dave Platt870901d2014-02-05 17:03:16 -0800462 // Clean up any descriptors which must be closed immediately
463 DetachDescriptors(env, fdsToClose);
464
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700465 // Keep capabilities across UID change, unless we're staying root.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700466 if (uid != 0) {
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700467 EnableKeepCapabilities();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700468 }
469
Nick Kralevicha0664be2013-02-13 14:39:17 -0800470 DropCapabilitiesBoundingSet();
471
Brian Carlstrombd86bcc2013-03-10 20:26:16 -0700472 if (!MountEmulatedStorage(uid, mount_external)) {
473 PLOG(WARNING) << "Failed to mount emulated storage";
474 if (errno == ENOTCONN || errno == EROFS) {
475 // When device is actively encrypting, we get ENOTCONN here
476 // since FUSE was mounted before the framework restarted.
477 // When encrypted device is booting, we get EROFS since
478 // FUSE hasn't been created yet by init.
479 // In either case, continue without external storage.
480 } else {
481 LOG(FATAL) << "Cannot continue without emulated storage";
482 }
483 }
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700484
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700485 SetGids(env, javaGids);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700486
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700487 SetRLimits(env, javaRlimits);
488
Nick Kralevich7e2364c2013-02-20 14:46:54 -0800489 int rc = setresgid(gid, gid, gid);
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700490 if (rc == -1) {
Nick Kralevich7e2364c2013-02-20 14:46:54 -0800491 PLOG(FATAL) << "setresgid(" << gid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700492 }
493
Nick Kralevich7e2364c2013-02-20 14:46:54 -0800494 rc = setresuid(uid, uid, uid);
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700495 if (rc == -1) {
Nick Kralevich7e2364c2013-02-20 14:46:54 -0800496 PLOG(FATAL) << "setresuid(" << uid << ") failed";
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700497 }
498
Brian Carlstrom154cef62012-05-02 22:34:03 -0700499#if defined(__linux__)
Nick Kralevichb7882782012-09-27 12:29:02 -0700500 if (NeedsNoRandomizeWorkaround()) {
501 // Work around ARM kernel ASLR lossage (http://b/5817320).
502 int old_personality = personality(0xffffffff);
503 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
504 if (new_personality == -1) {
505 PLOG(WARNING) << "personality(" << new_personality << ") failed";
506 }
Elliott Hughes51e53862012-05-02 17:17:28 -0700507 }
Brian Carlstrom154cef62012-05-02 22:34:03 -0700508#endif
Elliott Hughes51e53862012-05-02 17:17:28 -0700509
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800510 SetCapabilities(permittedCapabilities, effectiveCapabilities);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700511
Elliott Hughes2abeb9b2012-05-11 23:42:02 -0700512 SetSchedulerPolicy();
Elliott Hughesb6636b82012-04-24 10:41:16 -0700513
Kenny Rootdc1cd102012-10-17 10:35:32 -0700514#if defined(HAVE_ANDROID_OS)
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700515 { // NOLINT(whitespace/braces)
Brian Carlstrom1a0b4752012-10-17 16:23:18 -0700516 const char* se_info_c_str = NULL;
517 UniquePtr<ScopedUtfChars> se_info;
518 if (java_se_info != NULL) {
519 se_info.reset(new ScopedUtfChars(env, java_se_info));
520 se_info_c_str = se_info->c_str();
521 CHECK(se_info_c_str != NULL);
522 }
523 const char* se_name_c_str = NULL;
524 UniquePtr<ScopedUtfChars> se_name;
525 if (java_se_name != NULL) {
526 se_name.reset(new ScopedUtfChars(env, java_se_name));
527 se_name_c_str = se_name->c_str();
528 CHECK(se_name_c_str != NULL);
529 }
530 rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
Elliott Hughesc151f902012-06-21 20:33:21 -0700531 if (rc == -1) {
532 PLOG(FATAL) << "selinux_android_setcontext(" << uid << ", "
533 << (is_system_server ? "true" : "false") << ", "
Brian Carlstrom1a0b4752012-10-17 16:23:18 -0700534 << "\"" << se_info_c_str << "\", \"" << se_name_c_str << "\") failed";
Elliott Hughesc151f902012-06-21 20:33:21 -0700535 }
William Roberts1e7d1d52013-11-11 07:28:37 -0800536
537 // Make it easier to debug audit logs by setting the main thread's name to the
538 // nice name rather than "app_process".
539 if (se_info_c_str == NULL && is_system_server) {
540 se_name_c_str = "system_server";
541 }
542 if (se_info_c_str != NULL) {
543 SetThreadName(se_name_c_str);
544 }
Elliott Hughesc151f902012-06-21 20:33:21 -0700545 }
546#else
547 UNUSED(is_system_server);
548 UNUSED(java_se_info);
549 UNUSED(java_se_name);
550#endif
551
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700552 // Our system thread ID, etc, has changed so reset Thread state.
553 self->InitAfterFork();
554
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700555 EnableDebugFeatures(debug_flags);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700556
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700557 UnsetSigChldHandler();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700558 runtime->DidForkFromZygote();
559 } else if (pid > 0) {
560 // the parent process
561 }
562 return pid;
563}
564
Dave Platt874d2522014-02-13 13:33:36 -0800565static jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Dave Platt870901d2014-02-05 17:03:16 -0800566 jint debug_flags, jobjectArray rlimits,
567 jint mount_external, jstring se_info, jstring se_name,
568 jintArray fdsToClose) {
569 return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, 0, 0, mount_external,
570 se_info, se_name, false, fdsToClose);
571}
572
Elliott Hughes0512f022012-03-15 22:10:52 -0700573static jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
574 jint debug_flags, jobjectArray rlimits,
Brian Carlstrom01add2c2013-12-16 09:50:35 -0800575 jlong permittedCapabilities,
576 jlong effectiveCapabilities) {
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700577 pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
578 debug_flags, rlimits,
Elliott Hughes178cdcc2012-08-16 16:47:31 -0700579 permittedCapabilities, effectiveCapabilities,
Dave Platt870901d2014-02-05 17:03:16 -0800580 MOUNT_EXTERNAL_NONE, NULL, NULL, true, NULL);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700581 if (pid > 0) {
582 // The zygote process checks whether the child process has died or not.
583 LOG(INFO) << "System server process " << pid << " has been created";
584 gSystemServerPid = pid;
585 // There is a slight window that the system server process has crashed
586 // but it went unnoticed because we haven't published its pid yet. So
587 // we recheck here just to make sure that all is well.
588 int status;
589 if (waitpid(pid, &status, WNOHANG) == pid) {
590 LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
591 }
592 }
593 return pid;
594}
595
Elliott Hughes01158d72011-09-19 19:47:10 -0700596static JNINativeMethod gMethods[] = {
Dave Platt874d2522014-02-13 13:33:36 -0800597 NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[IILjava/lang/String;Ljava/lang/String;[I)I"),
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700598 NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
Elliott Hughes01158d72011-09-19 19:47:10 -0700599};
600
Elliott Hughes01158d72011-09-19 19:47:10 -0700601void register_dalvik_system_Zygote(JNIEnv* env) {
Elliott Hughes7756d542012-05-24 21:56:51 -0700602 REGISTER_NATIVE_METHODS("dalvik/system/Zygote");
Elliott Hughes01158d72011-09-19 19:47:10 -0700603}
604
605} // namespace art