blob: 827d13f3deb9929e215202dd4b73a22bb5d389c2 [file] [log] [blame]
Narayan Kamath973b4662014-03-31 13:41:26 +01001/*
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
Chris Wailes30f16ca2019-01-17 14:57:10 -080017/*
18 * Disable optimization of this file if we are compiling with the address
19 * sanitizer. This is a mitigation for b/122921367 and can be removed once the
20 * bug is fixed.
21 */
22#if __has_feature(address_sanitizer)
23#pragma clang optimize off
24#endif
25
Colin Cross18cd9f52014-06-13 12:58:55 -070026#define LOG_TAG "Zygote"
Narayan Kamath973b4662014-03-31 13:41:26 +010027
28// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
29#include <sys/mount.h>
30#include <linux/fs.h>
31
Chris Wailesefc65b22018-10-26 12:41:54 -070032#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070033#include <list>
Chris Wailesefc65b22018-10-26 12:41:54 -070034#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080035#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070036#include <string>
37
Josh Gaod7951102018-06-26 16:05:12 -070038#include <android/fdsan.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070039#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080040#include <grp.h>
41#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070042#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070043#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010044#include <paths.h>
45#include <signal.h>
46#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070047#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040048#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070049#include <sys/personality.h>
50#include <sys/prctl.h>
51#include <sys/resource.h>
52#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070053#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070054#include <sys/types.h>
55#include <sys/utsname.h>
56#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080057#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070058
Andreas Gampe8dfa1782017-01-05 12:45:58 -080059#include "android-base/logging.h"
Minchan Kim696873e2018-06-27 11:32:40 +090060#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080061#include <android-base/file.h>
62#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070063#include <cutils/fs.h>
64#include <cutils/multiuser.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070065#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070066#include <utils/String8.h>
67#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080068#include <seccomp_policy.h>
Howard Ro65e48ec2018-10-02 12:08:28 -070069#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070070#include <processgroup/processgroup.h>
Suren Baghdasaryan09a29e12019-01-04 12:16:57 -080071#include <processgroup/sched_policy.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070072
Andreas Gampeed6b9df2014-11-20 22:02:20 -080073#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070074#include <nativehelper/JNIHelp.h>
75#include <nativehelper/ScopedLocalRef.h>
76#include <nativehelper/ScopedPrimitiveArray.h>
77#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050078#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010079
jgu212eacd062014-09-10 06:55:07 -040080#include "nativebridge/native_bridge.h"
81
Narayan Kamath973b4662014-03-31 13:41:26 +010082namespace {
83
Chris Wailesefc65b22018-10-26 12:41:54 -070084using namespace std::placeholders;
85
Narayan Kamath973b4662014-03-31 13:41:26 +010086using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080087using android::base::StringPrintf;
88using android::base::WriteStringToFile;
Minchan Kim696873e2018-06-27 11:32:40 +090089using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010090
Andreas Gamped5758f62018-03-12 12:08:55 -070091#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
92 append(StringPrintf(__VA_ARGS__))
93
Narayan Kamath973b4662014-03-31 13:41:26 +010094static pid_t gSystemServerPid = 0;
95
96static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
97static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +010098static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +010099static jmethodID gCallPostForkChildHooks;
100
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800101static bool g_is_security_enforced = true;
102
Narayan Kamath973b4662014-03-31 13:41:26 +0100103// Must match values in com.android.internal.os.Zygote.
104enum MountExternalKind {
105 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700106 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700107 MOUNT_EXTERNAL_READ = 2,
108 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +0100109};
110
Orion Hodson8d005a62018-12-05 12:28:53 +0000111// Must match values in com.android.internal.os.Zygote.
112enum RuntimeFlags : uint32_t {
113 DEBUG_ENABLE_JDWP = 1,
114};
115
Andreas Gampeb053cce2015-11-17 16:38:59 -0800116static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
117 std::ostringstream oss;
118 oss << __FILE__ << ":" << line << ": " << msg;
119 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100120}
121
122// This signal handler is for zygote mode, since the zygote must reap its children
123static void SigChldHandler(int /*signal_number*/) {
124 pid_t pid;
125 int status;
126
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700127 // It's necessary to save and restore the errno during this function.
128 // Since errno is stored per thread, changing it here modifies the errno
129 // on the thread on which this signal handler executes. If a signal occurs
130 // between a call and an errno check, it's possible to get the errno set
131 // here.
132 // See b/23572286 for extra information.
133 int saved_errno = errno;
134
Narayan Kamath973b4662014-03-31 13:41:26 +0100135 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
136 // Log process-death status that we care about. In general it is
137 // not safe to call LOG(...) from a signal handler because of
138 // possible reentrancy. However, we know a priori that the
139 // current implementation of LOG() is safe to call from a SIGCHLD
140 // handler in the zygote process. If the LOG() implementation
141 // changes its locking strategy or its use of syscalls within the
142 // lazy-init critical section, its use here may become unsafe.
143 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700144 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100145 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700146 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100147 if (WCOREDUMP(status)) {
148 ALOGI("Process %d dumped core.", pid);
149 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100150 }
151
152 // If the just-crashed process is the system_server, bring down zygote
153 // so that it is restarted by init and system server will be restarted
154 // from there.
155 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800156 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100157 kill(getpid(), SIGKILL);
158 }
159 }
160
Narayan Kamath160992d2014-04-14 14:46:07 +0100161 // Note that we shouldn't consider ECHILD an error because
162 // the secondary zygote might have no children left to wait for.
163 if (pid < 0 && errno != ECHILD) {
164 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100165 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700166
167 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100168}
169
yuanhao435e84b2018-01-15 15:37:02 +0800170// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
171// configured very late, because earlier in the runtime we may fork() and
172// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100173// have them be harvested immediately.
174//
yuanhao435e84b2018-01-15 15:37:02 +0800175// Ignore SIGHUP because all processes forked by the zygote are in the same
176// process group as the zygote and we don't want to be notified if we become
177// an orphaned group and have one or more stopped processes. This is not a
178// theoretical concern :
179// - we can become an orphaned group if one of our direct descendants forks
180// and is subsequently killed before its children.
181// - crash_dump routinely STOPs the process it's tracing.
182//
183// See issues b/71965619 and b/25567761 for further details.
184//
Narayan Kamath973b4662014-03-31 13:41:26 +0100185// This ends up being called repeatedly before each fork(), but there's
186// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800187static void SetSignalHandlers() {
188 struct sigaction sig_chld = {};
189 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100190
yuanhao435e84b2018-01-15 15:37:02 +0800191 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700192 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100193 }
yuanhao435e84b2018-01-15 15:37:02 +0800194
195 struct sigaction sig_hup = {};
196 sig_hup.sa_handler = SIG_IGN;
197 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
198 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
199 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100200}
201
202// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800203static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100204 struct sigaction sa;
205 memset(&sa, 0, sizeof(sa));
206 sa.sa_handler = SIG_DFL;
207
yuanhao435e84b2018-01-15 15:37:02 +0800208 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700209 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100210 }
211}
212
213// Calls POSIX setgroups() using the int[] object as an argument.
214// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700215static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100216 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700217 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100218 }
219
220 ScopedIntArrayRO gids(env, javaGids);
221 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700222 *error_msg = CREATE_ERROR("Getting gids int array failed");
223 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100224 }
225 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
226 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700227 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
228 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100229 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700230
231 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100232}
233
234// Sets the resource limits via setrlimit(2) for the values in the
235// two-dimensional array of integers that's passed in. The second dimension
236// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
237// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700238static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100239 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700240 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100241 }
242
243 rlimit rlim;
244 memset(&rlim, 0, sizeof(rlim));
245
246 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
247 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
248 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
249 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700250 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
251 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100252 }
253
254 rlim.rlim_cur = javaRlimit[1];
255 rlim.rlim_max = javaRlimit[2];
256
257 int rc = setrlimit(javaRlimit[0], &rlim);
258 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700259 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800260 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700261 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100262 }
263 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700264
265 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100266}
267
Orion Hodson8d005a62018-12-05 12:28:53 +0000268static void EnableDebugger() {
269 // To let a non-privileged gdbserver attach to this
270 // process, we must set our dumpable flag.
271 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
272 ALOGE("prctl(PR_SET_DUMPABLE) failed");
273 }
274
275 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
276 // is enabled (see kernel/Documentation/security/Yama.txt).
277 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
278 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
279 // case since it's expected behaviour.
280 if (errno != EINVAL) {
281 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
282 }
283 }
284
Orion Hodson2b71ad02018-12-07 16:44:33 +0000285 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
286 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
287 // Set the soft limit on core dump size to 0 without changing the hard limit.
288 rlimit rl;
289 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
290 ALOGE("getrlimit(RLIMIT_CORE) failed");
291 } else {
292 rl.rlim_cur = 0;
293 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
294 ALOGE("setrlimit(RLIMIT_CORE) failed");
295 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000296 }
297 }
298}
299
Narayan Kamath973b4662014-03-31 13:41:26 +0100300// The debug malloc library needs to know whether it's the zygote or a child.
301extern "C" int gMallocLeakZygoteChild;
302
Christopher Ferris76de39e2017-06-20 16:13:40 -0700303static void PreApplicationInit() {
304 // The child process sets this to indicate it's not the zygote.
305 gMallocLeakZygoteChild = 1;
306
307 // Set the jemalloc decay time to 1.
308 mallopt(M_DECAY_TIME, 1);
309}
310
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800311static void SetUpSeccompFilter(uid_t uid) {
312 if (!g_is_security_enforced) {
313 ALOGI("seccomp disabled by setenforce 0");
314 return;
315 }
316
317 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700318 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800319 set_app_seccomp_filter();
320 } else {
321 set_system_seccomp_filter();
322 }
323}
324
Andreas Gamped5758f62018-03-12 12:08:55 -0700325static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100326 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
327 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700328 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
329 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100330 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700331 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100332}
333
Andreas Gamped5758f62018-03-12 12:08:55 -0700334static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100335 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
336 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
337 if (rc == -1) {
338 if (errno == EINVAL) {
339 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
340 "your kernel is compiled with file capabilities support");
341 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700342 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
343 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100344 }
345 }
346 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700347 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100348}
349
Andreas Gamped5758f62018-03-12 12:08:55 -0700350static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800351 __user_cap_header_struct capheader;
352 memset(&capheader, 0, sizeof(capheader));
353 capheader.version = _LINUX_CAPABILITY_VERSION_3;
354 capheader.pid = 0;
355
356 __user_cap_data_struct capdata[2];
357 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700358 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
359 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800360 }
361
362 capdata[0].inheritable = inheritable;
363 capdata[1].inheritable = inheritable >> 32;
364
365 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700366 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
367 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800368 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700369
370 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800371}
372
Andreas Gamped5758f62018-03-12 12:08:55 -0700373static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
374 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100375 __user_cap_header_struct capheader;
376 memset(&capheader, 0, sizeof(capheader));
377 capheader.version = _LINUX_CAPABILITY_VERSION_3;
378 capheader.pid = 0;
379
380 __user_cap_data_struct capdata[2];
381 memset(&capdata, 0, sizeof(capdata));
382 capdata[0].effective = effective;
383 capdata[1].effective = effective >> 32;
384 capdata[0].permitted = permitted;
385 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800386 capdata[0].inheritable = inheritable;
387 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100388
389 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700390 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
391 "failed: %s", permitted, effective, inheritable, strerror(errno));
392 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100393 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700394 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100395}
396
Andreas Gamped5758f62018-03-12 12:08:55 -0700397static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100398 errno = -set_sched_policy(0, SP_DEFAULT);
399 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700400 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
401 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100402 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700403 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100404}
405
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700406static int UnmountTree(const char* path) {
407 size_t path_len = strlen(path);
408
409 FILE* fp = setmntent("/proc/mounts", "r");
410 if (fp == NULL) {
411 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
412 return -errno;
413 }
414
415 // Some volumes can be stacked on each other, so force unmount in
416 // reverse order to give us the best chance of success.
417 std::list<std::string> toUnmount;
418 mntent* mentry;
419 while ((mentry = getmntent(fp)) != NULL) {
420 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
421 toUnmount.push_front(std::string(mentry->mnt_dir));
422 }
423 }
424 endmntent(fp);
425
Chih-Hung Hsieha1b644e2018-12-11 11:09:20 -0800426 for (const auto& path : toUnmount) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700427 if (umount2(path.c_str(), MNT_DETACH)) {
428 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
429 }
430 }
431 return 0;
432}
433
Narayan Kamath973b4662014-03-31 13:41:26 +0100434// Create a private mount namespace and bind mount appropriate emulated
435// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700436static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Andreas Gamped5758f62018-03-12 12:08:55 -0700437 bool force_mount_namespace, std::string* error_msg) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700438 // See storage config details at http://source.android.com/tech/storage/
439
Jeff Sharkey9527b222015-06-24 15:24:48 -0700440 String8 storageSource;
441 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700442 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700443 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700444 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700445 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700446 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500447 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700448 // Sane default of no storage visible
449 return true;
450 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400451
452 // Create a second private mount namespace for our process
453 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700454 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400455 return false;
456 }
457
Robert Sesek06f39302017-03-20 17:30:05 -0400458 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
459 if (mount_mode == MOUNT_EXTERNAL_NONE) {
460 return true;
461 }
462
Jeff Sharkey9527b222015-06-24 15:24:48 -0700463 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
464 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700465 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
466 storageSource.string(),
467 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700468 return false;
469 }
470
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700471 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700472 userid_t user_id = multiuser_get_user_id(uid);
473 const String8 userSource(String8::format("/mnt/user/%d", user_id));
474 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700475 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
Jeff Sharkey9527b222015-06-24 15:24:48 -0700476 return false;
477 }
478 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
479 NULL, MS_BIND, NULL)) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700480 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
481 userSource.string(),
482 strerror(errno));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700483 return false;
484 }
485
Narayan Kamath973b4662014-03-31 13:41:26 +0100486 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100487}
488
Narayan Kamath973b4662014-03-31 13:41:26 +0100489static bool NeedsNoRandomizeWorkaround() {
490#if !defined(__arm__)
491 return false;
492#else
493 int major;
494 int minor;
495 struct utsname uts;
496 if (uname(&uts) == -1) {
497 return false;
498 }
499
500 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
501 return false;
502 }
503
504 // Kernels before 3.4.* need the workaround.
505 return (major < 3) || ((major == 3) && (minor < 4));
506#endif
507}
Narayan Kamath973b4662014-03-31 13:41:26 +0100508
509// Utility to close down the Zygote socket file descriptors while
510// the child is still running as root with Zygote's privileges. Each
511// descriptor (if any) is closed via dup2(), replacing it with a valid
512// (open) descriptor to /dev/null.
513
Andreas Gamped5758f62018-03-12 12:08:55 -0700514static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100515 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700516 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100517 }
518 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200519 ScopedIntArrayRO ar(env, fdsToClose);
520 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700521 *error_msg = "Bad fd array";
522 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100523 }
524 jsize i;
525 int devnull;
526 for (i = 0; i < count; i++) {
527 devnull = open("/dev/null", O_RDWR);
528 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700529 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
530 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100531 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700532 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100533 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700534 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
535 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100536 }
537 close(devnull);
538 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700539 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100540}
541
542void SetThreadName(const char* thread_name) {
543 bool hasAt = false;
544 bool hasDot = false;
545 const char* s = thread_name;
546 while (*s) {
547 if (*s == '.') {
548 hasDot = true;
549 } else if (*s == '@') {
550 hasAt = true;
551 }
552 s++;
553 }
554 const int len = s - thread_name;
555 if (len < 15 || hasAt || !hasDot) {
556 s = thread_name;
557 } else {
558 s = thread_name + len - 15;
559 }
560 // pthread_setname_np fails rather than truncating long strings.
561 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
562 strlcpy(buf, s, sizeof(buf)-1);
563 errno = pthread_setname_np(pthread_self(), buf);
564 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700565 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100566 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800567 // Update base::logging default tag.
568 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100569}
570
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100571// The list of open zygote file descriptors.
572static FileDescriptorTable* gOpenFdTable = NULL;
573
Andreas Gamped5758f62018-03-12 12:08:55 -0700574static bool FillFileDescriptorVector(JNIEnv* env,
Chris Wailesefc65b22018-10-26 12:41:54 -0700575 jintArray managed_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700576 std::vector<int>* fds,
577 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800578 CHECK(fds != nullptr);
Chris Wailesefc65b22018-10-26 12:41:54 -0700579 if (managed_fds != nullptr) {
580 ScopedIntArrayRO ar(env, managed_fds);
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800581 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700582 *error_msg = "Bad fd array";
583 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800584 }
585 fds->reserve(ar.size());
586 for (size_t i = 0; i < ar.size(); ++i) {
587 fds->push_back(ar[i]);
588 }
589 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700590 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800591}
592
Chris Wailesefc65b22018-10-26 12:41:54 -0700593[[noreturn]]
594static void ZygoteFailure(JNIEnv* env,
595 const char* process_name,
596 jstring managed_process_name,
597 const std::string& msg) {
598 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
599 if (managed_process_name != nullptr) {
600 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
601 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
602 process_name = scoped_managed_process_name_ptr->c_str();
603 }
604 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700605
Chris Wailesefc65b22018-10-26 12:41:54 -0700606 const std::string& error_msg =
607 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
608
609 env->FatalError(error_msg.c_str());
610 __builtin_unreachable();
611}
612
613static std::optional<std::string> ExtractJString(JNIEnv* env,
614 const char* process_name,
615 jstring managed_process_name,
616 jstring managed_string) {
617 if (managed_string == nullptr) {
618 return std::optional<std::string>();
619 } else {
620 ScopedUtfChars scoped_string_chars(env, managed_string);
621
622 if (scoped_string_chars.c_str() != nullptr) {
623 return std::optional<std::string>(scoped_string_chars.c_str());
624 } else {
625 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700626 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700627 }
628}
629
630// Utility routine to fork a zygote.
631static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
632 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore) {
633 SetSignalHandlers();
634
635 // Block SIGCHLD prior to fork.
636 sigset_t sigchld;
637 sigemptyset(&sigchld);
638 sigaddset(&sigchld, SIGCHLD);
639
640 // Curry a failure function.
641 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
642 nullptr, _1);
643
644 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
645 // log, which would result in the logging FDs we close being reopened.
646 // This would cause failures because the FDs are not whitelisted.
647 //
648 // Note that the zygote process is single threaded at this point.
649 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
650 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
651 }
652
653 // Close any logging related FDs before we start evaluating the list of
654 // file descriptors.
655 __android_log_close();
656 stats_log_close();
657
658 // If this is the first fork for this zygote, create the open FD table. If
659 // it isn't, we just need to check whether the list of open files has changed
660 // (and it shouldn't in the normal case).
661 std::string error_msg;
662 std::vector<int> fds_to_ignore;
663 if (!FillFileDescriptorVector(env, managed_fds_to_ignore, &fds_to_ignore, &error_msg)) {
664 fail_fn(error_msg);
665 }
666
667 if (gOpenFdTable == nullptr) {
668 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
669 if (gOpenFdTable == nullptr) {
670 fail_fn(error_msg);
David Sehrde8d0bd2018-06-22 10:45:36 -0700671 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700672 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
673 fail_fn(error_msg);
674 }
675
676 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
677
678 pid_t pid = fork();
679
680 if (pid == 0) {
681 // The child process.
682 PreApplicationInit();
683
684 // Clean up any descriptors which must be closed immediately
685 if (!DetachDescriptors(env, managed_fds_to_close, &error_msg)) {
686 fail_fn(error_msg);
687 }
688
689 // Re-open all remaining open file descriptors so that they aren't shared
690 // with the zygote across a fork.
691 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
692 fail_fn(error_msg);
693 }
694
695 // Turn fdsan back on.
696 android_fdsan_set_error_level(fdsan_error_level);
697 }
698
699 // We blocked SIGCHLD prior to a fork, we unblock it here.
700 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
701 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
702 }
703 return pid;
704}
705
706// Utility routine to specialize a zygote child process.
707static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
708 jint runtime_flags, jobjectArray rlimits,
709 jlong permitted_capabilities, jlong effective_capabilities,
710 jint mount_external, jstring managed_se_info,
711 jstring managed_nice_name, bool is_system_server,
712 bool is_child_zygote, jstring managed_instruction_set,
713 jstring managed_app_data_dir) {
714 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
715 managed_nice_name, _1);
716 auto extract_fn = std::bind(ExtractJString, env, is_system_server ? "system_server" : "zygote",
717 managed_nice_name, _1);
718
719 auto se_info = extract_fn(managed_se_info);
720 auto nice_name = extract_fn(managed_nice_name);
721 auto instruction_set = extract_fn(managed_instruction_set);
722 auto app_data_dir = extract_fn(managed_app_data_dir);
723
724 std::string error_msg;
David Sehrde8d0bd2018-06-22 10:45:36 -0700725
726 // Keep capabilities across UID change, unless we're staying root.
727 if (uid != 0) {
728 if (!EnableKeepCapabilities(&error_msg)) {
729 fail_fn(error_msg);
730 }
731 }
732
Chris Wailesefc65b22018-10-26 12:41:54 -0700733 if (!SetInheritable(permitted_capabilities, &error_msg)) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700734 fail_fn(error_msg);
735 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700736
David Sehrde8d0bd2018-06-22 10:45:36 -0700737 if (!DropCapabilitiesBoundingSet(&error_msg)) {
738 fail_fn(error_msg);
739 }
740
Chris Wailesefc65b22018-10-26 12:41:54 -0700741 bool use_native_bridge = !is_system_server &&
742 instruction_set.has_value() &&
743 android::NativeBridgeAvailable() &&
744 android::NeedsNativeBridge(instruction_set.value().c_str());
745
746 if (use_native_bridge && !app_data_dir.has_value()) {
747 // The app_data_dir variable should never be empty if we need to use a
748 // native bridge. In general, app_data_dir will never be empty for normal
749 // applications. It can only happen in special cases (for isolated
750 // processes which are not associated with any app). These are launched by
751 // the framework and should not be emulated anyway.
David Sehrde8d0bd2018-06-22 10:45:36 -0700752 use_native_bridge = false;
Chris Wailesefc65b22018-10-26 12:41:54 -0700753 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700754 }
755
756 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg)) {
757 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
758 if (errno == ENOTCONN || errno == EROFS) {
759 // When device is actively encrypting, we get ENOTCONN here
760 // since FUSE was mounted before the framework restarted.
761 // When encrypted device is booting, we get EROFS since
762 // FUSE hasn't been created yet by init.
763 // In either case, continue without external storage.
764 } else {
765 fail_fn(error_msg);
766 }
767 }
768
769 // If this zygote isn't root, it won't be able to create a process group,
770 // since the directory is owned by root.
771 if (!is_system_server && getuid() == 0) {
772 int rc = createProcessGroup(uid, getpid());
773 if (rc != 0) {
774 if (rc == -EROFS) {
775 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
776 } else {
777 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
778 }
779 }
780 }
781
Chris Wailesefc65b22018-10-26 12:41:54 -0700782 if (!SetGids(env, gids, &error_msg)) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700783 fail_fn(error_msg);
784 }
785
Chris Wailesefc65b22018-10-26 12:41:54 -0700786 if (!SetRLimits(env, rlimits, &error_msg)) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700787 fail_fn(error_msg);
788 }
789
790 if (use_native_bridge) {
Chris Wailesefc65b22018-10-26 12:41:54 -0700791 // Due to the logic behind use_native_bridge we know that both app_data_dir
792 // and instruction_set contain values.
793 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
794 instruction_set.value().c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700795 }
796
Chris Wailesefc65b22018-10-26 12:41:54 -0700797 if (setresgid(gid, gid, gid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700798 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
799 }
800
Chris Wailesefc65b22018-10-26 12:41:54 -0700801 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
802 // before changing uid from 0, which clears capabilities. The other
803 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
804 // breaks SELinux domain transition (see b/71859146). As the result,
805 // privileged syscalls used below still need to be accessible in app process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700806 SetUpSeccompFilter(uid);
807
Chris Wailesefc65b22018-10-26 12:41:54 -0700808 if (setresuid(uid, uid, uid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700809 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
810 }
811
812 // The "dumpable" flag of a process, which controls core dump generation, is
813 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
814 // user or group ID changes. See proc(5) for possible values. In most cases,
815 // the value is 0, so core dumps are disabled for zygote children. However,
816 // when running in a Chrome OS container, the value is already set to 2,
817 // which allows the external crash reporter to collect all core dumps. Since
818 // only system crashes are interested, core dump is disabled for app
819 // processes. This also ensures compliance with CTS.
820 int dumpable = prctl(PR_GET_DUMPABLE);
821 if (dumpable == -1) {
822 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
823 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
824 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700825
David Sehrde8d0bd2018-06-22 10:45:36 -0700826 if (dumpable == 2 && uid >= AID_APP) {
827 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
828 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
829 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
830 }
831 }
832
Orion Hodson8d005a62018-12-05 12:28:53 +0000833 // Set process properties to enable debugging if required.
834 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
835 EnableDebugger();
836 }
837
David Sehrde8d0bd2018-06-22 10:45:36 -0700838 if (NeedsNoRandomizeWorkaround()) {
839 // Work around ARM kernel ASLR lossage (http://b/5817320).
840 int old_personality = personality(0xffffffff);
841 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
842 if (new_personality == -1) {
843 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
844 }
845 }
846
Chris Wailesefc65b22018-10-26 12:41:54 -0700847 if (!SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities,
David Sehrde8d0bd2018-06-22 10:45:36 -0700848 &error_msg)) {
849 fail_fn(error_msg);
850 }
851
852 if (!SetSchedulerPolicy(&error_msg)) {
853 fail_fn(error_msg);
854 }
855
Chris Wailesefc65b22018-10-26 12:41:54 -0700856 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
857 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
858
859 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
860 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
861 uid, is_system_server, se_info_ptr, nice_name_ptr));
David Sehrde8d0bd2018-06-22 10:45:36 -0700862 }
863
864 // Make it easier to debug audit logs by setting the main thread's name to the
865 // nice name rather than "app_process".
Chris Wailesefc65b22018-10-26 12:41:54 -0700866 if (nice_name.has_value()) {
867 SetThreadName(nice_name.value().c_str());
868 } else if (is_system_server) {
869 SetThreadName("system_server");
David Sehrde8d0bd2018-06-22 10:45:36 -0700870 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700871
872 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
873 UnsetChldSignalHandler();
874
Orion Hodson46724e72018-10-19 13:05:33 +0100875 if (is_system_server) {
876 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
877 if (env->ExceptionCheck()) {
878 fail_fn("Error calling post fork system server hooks.");
879 }
880 // TODO(oth): Remove hardcoded label here (b/117874058).
881 static const char* kSystemServerLabel = "u:r:system_server:s0";
882 if (selinux_android_setcon(kSystemServerLabel) != 0) {
883 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
884 }
885 }
886
David Sehrde8d0bd2018-06-22 10:45:36 -0700887 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
Chris Wailesefc65b22018-10-26 12:41:54 -0700888 is_system_server, is_child_zygote, managed_instruction_set);
889
David Sehrde8d0bd2018-06-22 10:45:36 -0700890 if (env->ExceptionCheck()) {
891 fail_fn("Error calling post fork hooks.");
892 }
893}
894
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700895static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
896 __user_cap_header_struct capheader;
897 memset(&capheader, 0, sizeof(capheader));
898 capheader.version = _LINUX_CAPABILITY_VERSION_3;
899 capheader.pid = 0;
900
901 __user_cap_data_struct capdata[2];
902 if (capget(&capheader, &capdata[0]) == -1) {
903 ALOGE("capget failed: %s", strerror(errno));
904 RuntimeAbort(env, __LINE__, "capget failed");
905 }
906
Chris Wailesefc65b22018-10-26 12:41:54 -0700907 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
908}
909
910static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
911 bool is_child_zygote) {
912 jlong capabilities = 0;
913
914 /*
915 * Grant the following capabilities to the Bluetooth user:
916 * - CAP_WAKE_ALARM
917 * - CAP_NET_RAW
918 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
919 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
920 */
921
922 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
923 capabilities |= (1LL << CAP_WAKE_ALARM);
924 capabilities |= (1LL << CAP_NET_RAW);
925 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
926 capabilities |= (1LL << CAP_SYS_NICE);
927 }
928
Remi NGUYEN VANc094a542018-12-07 16:52:24 +0900929 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
930 capabilities |= (1LL << CAP_NET_ADMIN);
931 capabilities |= (1LL << CAP_NET_BROADCAST);
932 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
933 capabilities |= (1LL << CAP_NET_RAW);
934 }
935
Chris Wailesefc65b22018-10-26 12:41:54 -0700936 /*
937 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
938 */
939
940 bool gid_wakelock_found = false;
941 if (gid == AID_WAKELOCK) {
942 gid_wakelock_found = true;
943 } else if (gids != nullptr) {
944 jsize gids_num = env->GetArrayLength(gids);
945 ScopedIntArrayRO native_gid_proxy(env, gids);
946
947 if (native_gid_proxy.get() == nullptr) {
948 RuntimeAbort(env, __LINE__, "Bad gids array");
949 }
950
951 for (int gid_index = gids_num; --gids_num >= 0;) {
952 if (native_gid_proxy[gid_index] == AID_WAKELOCK) {
953 gid_wakelock_found = true;
954 break;
955 }
956 }
957 }
958
959 if (gid_wakelock_found) {
960 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
961 }
962
963 /*
964 * Grant child Zygote processes the following capabilities:
965 * - CAP_SETUID (change UID of child processes)
966 * - CAP_SETGID (change GID of child processes)
967 * - CAP_SETPCAP (change capabilities of child processes)
968 */
969
970 if (is_child_zygote) {
971 capabilities |= (1LL << CAP_SETUID);
972 capabilities |= (1LL << CAP_SETGID);
973 capabilities |= (1LL << CAP_SETPCAP);
974 }
975
976 /*
977 * Containers run without some capabilities, so drop any caps that are not
978 * available.
979 */
980
981 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700982}
Narayan Kamath973b4662014-03-31 13:41:26 +0100983} // anonymous namespace
984
985namespace android {
986
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800987static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesefc65b22018-10-26 12:41:54 -0700988 // security_getenforce is not allowed on app process. Initialize and cache
989 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800990 g_is_security_enforced = security_getenforce();
991}
992
Christopher Ferris76de39e2017-06-20 16:13:40 -0700993static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
994 PreApplicationInit();
995}
996
Narayan Kamath973b4662014-03-31 13:41:26 +0100997static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
998 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100999 jint runtime_flags, jobjectArray rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -07001000 jint mount_external, jstring se_info, jstring nice_name,
1001 jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote,
1002 jstring instruction_set, jstring app_data_dir) {
1003 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001004
Chris Wailesefc65b22018-10-26 12:41:54 -07001005 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001006 if (pid == 0) {
1007 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1008 capabilities, capabilities,
Chris Wailesefc65b22018-10-26 12:41:54 -07001009 mount_external, se_info, nice_name, false,
1010 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
David Sehrde8d0bd2018-06-22 10:45:36 -07001011 }
1012 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001013}
1014
1015static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1016 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesefc65b22018-10-26 12:41:54 -07001017 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1018 jlong effective_capabilities) {
1019 pid_t pid = ForkCommon(env, true,
1020 /* managed_fds_to_close= */ nullptr,
1021 /* managed_fds_to_ignore= */ nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001022 if (pid == 0) {
1023 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -07001024 permitted_capabilities, effective_capabilities,
1025 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1026 false, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001027 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001028 // The zygote process checks whether the child process has died or not.
1029 ALOGI("System server process %d has been created", pid);
1030 gSystemServerPid = pid;
1031 // There is a slight window that the system server process has crashed
1032 // but it went unnoticed because we haven't published its pid yet. So
1033 // we recheck here just to make sure that all is well.
1034 int status;
1035 if (waitpid(pid, &status, WNOHANG) == pid) {
1036 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001037 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001038 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001039
Minchan Kim696873e2018-06-27 11:32:40 +09001040 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
1041 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
1042 if (per_app_memcg) {
1043 // Assign system_server to the correct memory cgroup.
1044 // Not all devices mount /dev/memcg so check for the file first
1045 // to avoid unnecessarily printing errors and denials in the logs.
1046 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -08001047 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim696873e2018-06-27 11:32:40 +09001048 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
1049 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001050 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001051 }
1052 return pid;
1053}
1054
Robert Sesek54e387d2016-12-02 17:27:50 -05001055static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1056 JNIEnv* env, jclass, jstring path) {
1057 ScopedUtfChars path_native(env, path);
1058 const char* path_cstr = path_native.c_str();
1059 if (!path_cstr) {
Chris Wailesefc65b22018-10-26 12:41:54 -07001060 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001061 }
1062 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1063}
1064
doheon1.lee885b7422016-01-20 13:07:27 +09001065static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1066 // Zygote process unmount root storage space initially before every child processes are forked.
1067 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001068 // and no need unmount storage operation in MountEmulatedStorage method.
1069 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1070
1071 // See storage config details at http://source.android.com/tech/storage/
1072 // Create private mount namespace shared by all children
1073 if (unshare(CLONE_NEWNS) == -1) {
1074 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1075 return;
1076 }
1077
1078 // Mark rootfs as being a slave so that changes from default
1079 // namespace only flow into our children.
1080 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1081 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1082 return;
1083 }
1084
1085 // Create a staging tmpfs that is shared by our children; they will
1086 // bind mount storage into their respective private namespaces, which
1087 // are isolated from each other.
1088 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1089 if (target_base != nullptr) {
1090#define STRINGIFY_UID(x) __STRING(x)
1091 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1092 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1093 ALOGE("Failed to mount tmpfs to %s", target_base);
1094 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1095 return;
1096 }
1097#undef STRINGIFY_UID
1098 }
doheon1.lee885b7422016-01-20 13:07:27 +09001099
1100 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001101}
1102
Daniel Micay76f6a862015-09-19 17:31:01 -04001103static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001104 { "nativeSecurityInit", "()V",
1105 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001106 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001107 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001108 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1109 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001110 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001111 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1112 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001113 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001114 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1115 { "nativePreApplicationInit", "()V",
1116 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001117};
1118
1119int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001120 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001121 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1122 "callPostForkSystemServerHooks",
1123 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001124 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001125 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001126
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001127 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001128}
1129} // namespace android