blob: 59aab463c1684b68828fe32b7f01ede529feb3ba [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
Colin Cross18cd9f52014-06-13 12:58:55 -070017#define LOG_TAG "Zygote"
Narayan Kamath973b4662014-03-31 13:41:26 +010018
19// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
20#include <sys/mount.h>
21#include <linux/fs.h>
22
Chris Wailesaf594fc2018-11-02 11:00:07 -070023#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070024#include <list>
Chris Wailesaf594fc2018-11-02 11:00:07 -070025#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080026#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070027#include <string>
28
Josh Gaod7951102018-06-26 16:05:12 -070029#include <android/fdsan.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070030#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080031#include <grp.h>
32#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070033#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070034#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010035#include <paths.h>
36#include <signal.h>
37#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070038#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040039#include <sys/cdefs.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070040#include <sys/personality.h>
41#include <sys/prctl.h>
42#include <sys/resource.h>
43#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070044#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070045#include <sys/types.h>
46#include <sys/utsname.h>
47#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080048#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070049
Andreas Gampe8dfa1782017-01-05 12:45:58 -080050#include "android-base/logging.h"
Minchan Kim5fa8af22018-06-27 11:32:40 +090051#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080052#include <android-base/file.h>
53#include <android-base/stringprintf.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070054#include <cutils/fs.h>
55#include <cutils/multiuser.h>
56#include <cutils/sched_policy.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070057#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070058#include <utils/String8.h>
59#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080060#include <seccomp_policy.h>
Howard Ro27330412018-10-02 12:08:28 -070061#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070062#include <processgroup/processgroup.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070063
Andreas Gampeed6b9df2014-11-20 22:02:20 -080064#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070065#include <nativehelper/JNIHelp.h>
66#include <nativehelper/ScopedLocalRef.h>
67#include <nativehelper/ScopedPrimitiveArray.h>
68#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050069#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010070
jgu212eacd062014-09-10 06:55:07 -040071#include "nativebridge/native_bridge.h"
72
Narayan Kamath973b4662014-03-31 13:41:26 +010073namespace {
74
Chris Wailesaf594fc2018-11-02 11:00:07 -070075using namespace std::placeholders;
76
Narayan Kamath973b4662014-03-31 13:41:26 +010077using android::String8;
Sudheer Shanka663b1042018-07-30 17:34:21 -070078using android::base::StringAppendF;
Carmen Jacksondd401252017-02-23 15:21:10 -080079using android::base::StringPrintf;
80using android::base::WriteStringToFile;
Minchan Kim5fa8af22018-06-27 11:32:40 +090081using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +010082
Andreas Gamped5758f62018-03-12 12:08:55 -070083#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
84 append(StringPrintf(__VA_ARGS__))
85
Narayan Kamath973b4662014-03-31 13:41:26 +010086static pid_t gSystemServerPid = 0;
87
Sudheer Shanka663b1042018-07-30 17:34:21 -070088static const char kIsolatedStorage[] = "persist.sys.isolated_storage";
Sudheer Shankaa3801582019-01-17 17:19:11 -080089static const char kIsolatedStorageSnapshot[] = "sys.isolated_storage_snapshot";
Narayan Kamath973b4662014-03-31 13:41:26 +010090static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
91static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +010092static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +010093static jmethodID gCallPostForkChildHooks;
94
Victor Hsiehc8176ef2018-01-08 12:43:00 -080095static bool g_is_security_enforced = true;
96
Narayan Kamath973b4662014-03-31 13:41:26 +010097// Must match values in com.android.internal.os.Zygote.
98enum MountExternalKind {
99 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700100 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700101 MOUNT_EXTERNAL_READ = 2,
102 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800103 MOUNT_EXTERNAL_INSTALLER = 4,
104 MOUNT_EXTERNAL_FULL = 5,
Narayan Kamath973b4662014-03-31 13:41:26 +0100105};
106
Orion Hodson8d005a62018-12-05 12:28:53 +0000107// Must match values in com.android.internal.os.Zygote.
108enum RuntimeFlags : uint32_t {
109 DEBUG_ENABLE_JDWP = 1,
110};
111
Andreas Gampeb053cce2015-11-17 16:38:59 -0800112static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
113 std::ostringstream oss;
114 oss << __FILE__ << ":" << line << ": " << msg;
115 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100116}
117
118// This signal handler is for zygote mode, since the zygote must reap its children
119static void SigChldHandler(int /*signal_number*/) {
120 pid_t pid;
121 int status;
122
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700123 // It's necessary to save and restore the errno during this function.
124 // Since errno is stored per thread, changing it here modifies the errno
125 // on the thread on which this signal handler executes. If a signal occurs
126 // between a call and an errno check, it's possible to get the errno set
127 // here.
128 // See b/23572286 for extra information.
129 int saved_errno = errno;
130
Narayan Kamath973b4662014-03-31 13:41:26 +0100131 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
132 // Log process-death status that we care about. In general it is
133 // not safe to call LOG(...) from a signal handler because of
134 // possible reentrancy. However, we know a priori that the
135 // current implementation of LOG() is safe to call from a SIGCHLD
136 // handler in the zygote process. If the LOG() implementation
137 // changes its locking strategy or its use of syscalls within the
138 // lazy-init critical section, its use here may become unsafe.
139 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700140 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100141 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700142 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100143 if (WCOREDUMP(status)) {
144 ALOGI("Process %d dumped core.", pid);
145 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100146 }
147
148 // If the just-crashed process is the system_server, bring down zygote
149 // so that it is restarted by init and system server will be restarted
150 // from there.
151 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800152 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100153 kill(getpid(), SIGKILL);
154 }
155 }
156
Narayan Kamath160992d2014-04-14 14:46:07 +0100157 // Note that we shouldn't consider ECHILD an error because
158 // the secondary zygote might have no children left to wait for.
159 if (pid < 0 && errno != ECHILD) {
160 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100161 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700162
163 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100164}
165
yuanhao435e84b2018-01-15 15:37:02 +0800166// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
167// configured very late, because earlier in the runtime we may fork() and
168// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100169// have them be harvested immediately.
170//
yuanhao435e84b2018-01-15 15:37:02 +0800171// Ignore SIGHUP because all processes forked by the zygote are in the same
172// process group as the zygote and we don't want to be notified if we become
173// an orphaned group and have one or more stopped processes. This is not a
174// theoretical concern :
175// - we can become an orphaned group if one of our direct descendants forks
176// and is subsequently killed before its children.
177// - crash_dump routinely STOPs the process it's tracing.
178//
179// See issues b/71965619 and b/25567761 for further details.
180//
Narayan Kamath973b4662014-03-31 13:41:26 +0100181// This ends up being called repeatedly before each fork(), but there's
182// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800183static void SetSignalHandlers() {
184 struct sigaction sig_chld = {};
185 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100186
yuanhao435e84b2018-01-15 15:37:02 +0800187 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700188 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100189 }
yuanhao435e84b2018-01-15 15:37:02 +0800190
191 struct sigaction sig_hup = {};
192 sig_hup.sa_handler = SIG_IGN;
193 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
194 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
195 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100196}
197
198// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800199static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100200 struct sigaction sa;
201 memset(&sa, 0, sizeof(sa));
202 sa.sa_handler = SIG_DFL;
203
yuanhao435e84b2018-01-15 15:37:02 +0800204 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700205 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100206 }
207}
208
209// Calls POSIX setgroups() using the int[] object as an argument.
210// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700211static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100212 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700213 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100214 }
215
216 ScopedIntArrayRO gids(env, javaGids);
217 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700218 *error_msg = CREATE_ERROR("Getting gids int array failed");
219 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100220 }
221 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
222 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700223 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
224 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100225 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700226
227 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100228}
229
230// Sets the resource limits via setrlimit(2) for the values in the
231// two-dimensional array of integers that's passed in. The second dimension
232// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
233// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700234static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100235 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700236 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100237 }
238
239 rlimit rlim;
240 memset(&rlim, 0, sizeof(rlim));
241
242 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
243 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
244 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
245 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700246 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
247 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100248 }
249
250 rlim.rlim_cur = javaRlimit[1];
251 rlim.rlim_max = javaRlimit[2];
252
253 int rc = setrlimit(javaRlimit[0], &rlim);
254 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700255 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800256 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700257 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100258 }
259 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700260
261 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100262}
263
Orion Hodson8d005a62018-12-05 12:28:53 +0000264static void EnableDebugger() {
265 // To let a non-privileged gdbserver attach to this
266 // process, we must set our dumpable flag.
267 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
268 ALOGE("prctl(PR_SET_DUMPABLE) failed");
269 }
270
271 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
272 // is enabled (see kernel/Documentation/security/Yama.txt).
273 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
274 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
275 // case since it's expected behaviour.
276 if (errno != EINVAL) {
277 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
278 }
279 }
280
Orion Hodson2b71ad02018-12-07 16:44:33 +0000281 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
282 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
283 // Set the soft limit on core dump size to 0 without changing the hard limit.
284 rlimit rl;
285 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
286 ALOGE("getrlimit(RLIMIT_CORE) failed");
287 } else {
288 rl.rlim_cur = 0;
289 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
290 ALOGE("setrlimit(RLIMIT_CORE) failed");
291 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000292 }
293 }
294}
295
Narayan Kamath973b4662014-03-31 13:41:26 +0100296// The debug malloc library needs to know whether it's the zygote or a child.
297extern "C" int gMallocLeakZygoteChild;
298
Christopher Ferris76de39e2017-06-20 16:13:40 -0700299static void PreApplicationInit() {
300 // The child process sets this to indicate it's not the zygote.
301 gMallocLeakZygoteChild = 1;
302
303 // Set the jemalloc decay time to 1.
304 mallopt(M_DECAY_TIME, 1);
305}
306
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800307static void SetUpSeccompFilter(uid_t uid) {
308 if (!g_is_security_enforced) {
309 ALOGI("seccomp disabled by setenforce 0");
310 return;
311 }
312
313 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700314 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800315 set_app_seccomp_filter();
316 } else {
317 set_system_seccomp_filter();
318 }
319}
320
Andreas Gamped5758f62018-03-12 12:08:55 -0700321static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100322 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
323 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700324 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
325 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100326 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700327 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100328}
329
Andreas Gamped5758f62018-03-12 12:08:55 -0700330static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100331 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
332 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
333 if (rc == -1) {
334 if (errno == EINVAL) {
335 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
336 "your kernel is compiled with file capabilities support");
337 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700338 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
339 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100340 }
341 }
342 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700343 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100344}
345
Andreas Gamped5758f62018-03-12 12:08:55 -0700346static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800347 __user_cap_header_struct capheader;
348 memset(&capheader, 0, sizeof(capheader));
349 capheader.version = _LINUX_CAPABILITY_VERSION_3;
350 capheader.pid = 0;
351
352 __user_cap_data_struct capdata[2];
353 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700354 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
355 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800356 }
357
358 capdata[0].inheritable = inheritable;
359 capdata[1].inheritable = inheritable >> 32;
360
361 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700362 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
363 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800364 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700365
366 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800367}
368
Andreas Gamped5758f62018-03-12 12:08:55 -0700369static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
370 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100371 __user_cap_header_struct capheader;
372 memset(&capheader, 0, sizeof(capheader));
373 capheader.version = _LINUX_CAPABILITY_VERSION_3;
374 capheader.pid = 0;
375
376 __user_cap_data_struct capdata[2];
377 memset(&capdata, 0, sizeof(capdata));
378 capdata[0].effective = effective;
379 capdata[1].effective = effective >> 32;
380 capdata[0].permitted = permitted;
381 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800382 capdata[0].inheritable = inheritable;
383 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100384
385 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700386 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
387 "failed: %s", permitted, effective, inheritable, strerror(errno));
388 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100389 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700390 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100391}
392
Andreas Gamped5758f62018-03-12 12:08:55 -0700393static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100394 errno = -set_sched_policy(0, SP_DEFAULT);
395 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700396 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
397 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100398 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700399 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100400}
401
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700402static int UnmountTree(const char* path) {
403 size_t path_len = strlen(path);
404
405 FILE* fp = setmntent("/proc/mounts", "r");
406 if (fp == NULL) {
407 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
408 return -errno;
409 }
410
411 // Some volumes can be stacked on each other, so force unmount in
412 // reverse order to give us the best chance of success.
413 std::list<std::string> toUnmount;
414 mntent* mentry;
415 while ((mentry = getmntent(fp)) != NULL) {
416 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
417 toUnmount.push_front(std::string(mentry->mnt_dir));
418 }
419 }
420 endmntent(fp);
421
Chih-Hung Hsieha1b644e2018-12-11 11:09:20 -0800422 for (const auto& path : toUnmount) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700423 if (umount2(path.c_str(), MNT_DETACH)) {
424 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
425 }
426 }
427 return 0;
428}
429
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700430static bool createPkgSandbox(uid_t uid, const std::string& package_name, std::string* error_msg) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700431 // Create /mnt/user/0/package/<package-name>
432 userid_t user_id = multiuser_get_user_id(uid);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700433 std::string pkg_sandbox_dir = StringPrintf("/mnt/user/%d", user_id);
Sudheer Shanka8d8223e2018-08-03 18:18:21 -0700434 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700435 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
436 return false;
437 }
438 StringAppendF(&pkg_sandbox_dir, "/package");
439 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
440 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
441 return false;
442 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700443 StringAppendF(&pkg_sandbox_dir, "/%s", package_name.c_str());
Sudheer Shanka663b1042018-07-30 17:34:21 -0700444 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0755, uid, uid) != 0) {
445 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
446 return false;
447 }
448 return true;
449}
450
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800451static bool bindMount(const std::string& sourceDir, const std::string& targetDir,
452 std::string* error_msg) {
453 if (TEMP_FAILURE_RETRY(mount(sourceDir.c_str(), targetDir.c_str(),
454 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
455 *error_msg = CREATE_ERROR("Failed to mount %s to %s: %s",
456 sourceDir.c_str(), targetDir.c_str(), strerror(errno));
457 return false;
458 }
459 if (TEMP_FAILURE_RETRY(mount(nullptr, targetDir.c_str(),
460 nullptr, MS_SLAVE | MS_REC, nullptr)) == -1) {
461 *error_msg = CREATE_ERROR("Failed to set MS_SLAVE for %s", targetDir.c_str());
462 return false;
463 }
464 return true;
465}
466
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700467static bool mountPkgSpecificDir(const std::string& mntSourceRoot,
468 const std::string& mntTargetRoot, const std::string& packageName,
469 const char* dirName, std::string* error_msg) {
470 std::string mntSourceDir = StringPrintf("%s/Android/%s/%s",
471 mntSourceRoot.c_str(), dirName, packageName.c_str());
472 std::string mntTargetDir = StringPrintf("%s/Android/%s/%s",
473 mntTargetRoot.c_str(), dirName, packageName.c_str());
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800474 return bindMount(mntSourceDir, mntTargetDir, error_msg);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700475}
476
477static bool preparePkgSpecificDirs(const std::vector<std::string>& packageNames,
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800478 const std::vector<std::string>& volumeLabels, bool mountAllObbs,
479 userid_t userId, std::string* error_msg) {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700480 for (auto& label : volumeLabels) {
481 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", label.c_str());
482 std::string mntTarget = StringPrintf("/storage/%s", label.c_str());
483 if (label == "emulated") {
484 StringAppendF(&mntSource, "/%d", userId);
485 StringAppendF(&mntTarget, "/%d", userId);
486 }
487 for (auto& package : packageNames) {
488 mountPkgSpecificDir(mntSource, mntTarget, package, "data", error_msg);
489 mountPkgSpecificDir(mntSource, mntTarget, package, "media", error_msg);
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800490 if (!mountAllObbs) {
491 mountPkgSpecificDir(mntSource, mntTarget, package, "obb", error_msg);
492 }
493 }
494 if (mountAllObbs) {
495 StringAppendF(&mntSource, "/Android/obb");
496 StringAppendF(&mntTarget, "/Android/obb");
497 bindMount(mntSource, mntTarget, error_msg);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700498 }
499 }
500 return true;
501}
502
Narayan Kamath973b4662014-03-31 13:41:26 +0100503// Create a private mount namespace and bind mount appropriate emulated
504// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700505static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700506 bool force_mount_namespace, std::string* error_msg, const std::string& package_name,
507 const std::vector<std::string>& packages_for_uid,
508 const std::vector<std::string>& visible_vol_ids) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700509 // See storage config details at http://source.android.com/tech/storage/
510
Jeff Sharkey9527b222015-06-24 15:24:48 -0700511 String8 storageSource;
512 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700513 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700514 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700515 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700516 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700517 storageSource = "/mnt/runtime/write";
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800518 } else if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700519 // Sane default of no storage visible
520 return true;
521 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400522
523 // Create a second private mount namespace for our process
524 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700525 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400526 return false;
527 }
528
Robert Sesek06f39302017-03-20 17:30:05 -0400529 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
530 if (mount_mode == MOUNT_EXTERNAL_NONE) {
531 return true;
532 }
533
Sudheer Shankaa3801582019-01-17 17:19:11 -0800534 if (GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, false))) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700535 if (mount_mode == MOUNT_EXTERNAL_FULL) {
536 storageSource = "/mnt/runtime/write";
537 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
538 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
539 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
540 storageSource.string(),
541 strerror(errno));
542 return false;
543 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700544
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700545 // Mount user-specific symlink helper into place
546 userid_t user_id = multiuser_get_user_id(uid);
547 const String8 userSource(String8::format("/mnt/user/%d", user_id));
548 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
549 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
550 return false;
551 }
552 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
553 NULL, MS_BIND, NULL)) == -1) {
554 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
555 userSource.string(),
556 strerror(errno));
557 return false;
558 }
559 } else {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700560 if (package_name.empty()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700561 return true;
562 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700563 userid_t user_id = multiuser_get_user_id(uid);
564 std::string pkgSandboxDir = StringPrintf("/mnt/user/%d/package/%s",
565 user_id, package_name.c_str());
566 struct stat sb;
567 bool sandboxAlreadyCreated = true;
568 if (TEMP_FAILURE_RETRY(lstat(pkgSandboxDir.c_str(), &sb)) == -1) {
569 if (errno == ENOENT) {
570 ALOGD("Sandbox not yet created for %s", pkgSandboxDir.c_str());
571 sandboxAlreadyCreated = false;
572 if (!createPkgSandbox(uid, package_name, error_msg)) {
573 return false;
574 }
575 } else {
576 ALOGE("Failed to lstat %s", pkgSandboxDir.c_str());
577 return false;
578 }
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700579 }
580 if (TEMP_FAILURE_RETRY(mount(pkgSandboxDir.c_str(), "/storage",
581 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
582 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
583 pkgSandboxDir.c_str(), strerror(errno));
584 return false;
585 }
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800586 if (access("/storage/obb_mount", F_OK) == 0) {
587 if (mount_mode != MOUNT_EXTERNAL_INSTALLER) {
588 remove("/storage/obb_mount");
589 }
590 } else {
591 if (mount_mode == MOUNT_EXTERNAL_INSTALLER) {
592 int fd = TEMP_FAILURE_RETRY(open("/storage/obb_mount",
593 O_RDWR | O_CREAT, 0660));
594 if (fd == -1) {
595 *error_msg = CREATE_ERROR("Couldn't create /storage/obb_mount: %s",
596 strerror(errno));
597 return false;
598 }
599 close(fd);
600 }
601 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700602 // If the sandbox was already created by vold, only then set up the bind mounts for
603 // pkg specific directories. Otherwise, leave as is and bind mounts will be taken
604 // care of by vold later.
605 if (sandboxAlreadyCreated) {
606 if (!preparePkgSpecificDirs(packages_for_uid, visible_vol_ids,
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800607 mount_mode == MOUNT_EXTERNAL_INSTALLER, user_id, error_msg)) {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700608 return false;
609 }
610 }
Sudheer Shanka663b1042018-07-30 17:34:21 -0700611 }
612 } else {
613 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
614 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
615 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
616 storageSource.string(),
617 strerror(errno));
618 return false;
619 }
620
621 // Mount user-specific symlink helper into place
622 userid_t user_id = multiuser_get_user_id(uid);
623 const String8 userSource(String8::format("/mnt/user/%d", user_id));
624 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
625 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
626 return false;
627 }
628 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
629 NULL, MS_BIND, NULL)) == -1) {
630 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
631 userSource.string(),
632 strerror(errno));
633 return false;
634 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700635 }
636
Narayan Kamath973b4662014-03-31 13:41:26 +0100637 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100638}
639
Narayan Kamath973b4662014-03-31 13:41:26 +0100640static bool NeedsNoRandomizeWorkaround() {
641#if !defined(__arm__)
642 return false;
643#else
644 int major;
645 int minor;
646 struct utsname uts;
647 if (uname(&uts) == -1) {
648 return false;
649 }
650
651 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
652 return false;
653 }
654
655 // Kernels before 3.4.* need the workaround.
656 return (major < 3) || ((major == 3) && (minor < 4));
657#endif
658}
Narayan Kamath973b4662014-03-31 13:41:26 +0100659
660// Utility to close down the Zygote socket file descriptors while
661// the child is still running as root with Zygote's privileges. Each
662// descriptor (if any) is closed via dup2(), replacing it with a valid
663// (open) descriptor to /dev/null.
664
Andreas Gamped5758f62018-03-12 12:08:55 -0700665static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100666 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700667 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100668 }
669 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200670 ScopedIntArrayRO ar(env, fdsToClose);
671 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700672 *error_msg = "Bad fd array";
673 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100674 }
675 jsize i;
676 int devnull;
677 for (i = 0; i < count; i++) {
678 devnull = open("/dev/null", O_RDWR);
679 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700680 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
681 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100682 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700683 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100684 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700685 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
686 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100687 }
688 close(devnull);
689 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700690 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100691}
692
693void SetThreadName(const char* thread_name) {
694 bool hasAt = false;
695 bool hasDot = false;
696 const char* s = thread_name;
697 while (*s) {
698 if (*s == '.') {
699 hasDot = true;
700 } else if (*s == '@') {
701 hasAt = true;
702 }
703 s++;
704 }
705 const int len = s - thread_name;
706 if (len < 15 || hasAt || !hasDot) {
707 s = thread_name;
708 } else {
709 s = thread_name + len - 15;
710 }
711 // pthread_setname_np fails rather than truncating long strings.
712 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
713 strlcpy(buf, s, sizeof(buf)-1);
714 errno = pthread_setname_np(pthread_self(), buf);
715 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700716 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100717 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800718 // Update base::logging default tag.
719 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100720}
721
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100722// The list of open zygote file descriptors.
723static FileDescriptorTable* gOpenFdTable = NULL;
724
Andreas Gamped5758f62018-03-12 12:08:55 -0700725static bool FillFileDescriptorVector(JNIEnv* env,
Chris Wailesaf594fc2018-11-02 11:00:07 -0700726 jintArray managed_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700727 std::vector<int>* fds,
728 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800729 CHECK(fds != nullptr);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700730 if (managed_fds != nullptr) {
731 ScopedIntArrayRO ar(env, managed_fds);
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800732 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700733 *error_msg = "Bad fd array";
734 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800735 }
736 fds->reserve(ar.size());
737 for (size_t i = 0; i < ar.size(); ++i) {
738 fds->push_back(ar[i]);
739 }
740 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700741 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800742}
743
Chris Wailesaf594fc2018-11-02 11:00:07 -0700744[[noreturn]]
745static void ZygoteFailure(JNIEnv* env,
746 const char* process_name,
747 jstring managed_process_name,
748 const std::string& msg) {
749 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
750 if (managed_process_name != nullptr) {
751 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
752 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
753 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -0700754 }
755 }
756
Chris Wailesaf594fc2018-11-02 11:00:07 -0700757 const std::string& error_msg =
758 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700759
Chris Wailesaf594fc2018-11-02 11:00:07 -0700760 env->FatalError(error_msg.c_str());
761 __builtin_unreachable();
762}
David Sehrde8d0bd2018-06-22 10:45:36 -0700763
Chris Wailesaf594fc2018-11-02 11:00:07 -0700764static std::optional<std::string> ExtractJString(JNIEnv* env,
765 const char* process_name,
766 jstring managed_process_name,
767 jstring managed_string) {
768 if (managed_string == nullptr) {
769 return std::optional<std::string>();
770 } else {
771 ScopedUtfChars scoped_string_chars(env, managed_string);
772
773 if (scoped_string_chars.c_str() != nullptr) {
774 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700775 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -0700776 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700777 }
778 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700779}
780
Chris Wailesaf594fc2018-11-02 11:00:07 -0700781// Utility routine to fork a zygote.
782static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
783 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore) {
yuanhao435e84b2018-01-15 15:37:02 +0800784 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100785
David Sehrde8d0bd2018-06-22 10:45:36 -0700786 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000787 sigset_t sigchld;
788 sigemptyset(&sigchld);
789 sigaddset(&sigchld, SIGCHLD);
790
Chris Wailesaf594fc2018-11-02 11:00:07 -0700791 // Curry a failure function.
792 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
793 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -0700794
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000795 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
796 // log, which would result in the logging FDs we close being reopened.
797 // This would cause failures because the FDs are not whitelisted.
798 //
799 // Note that the zygote process is single threaded at this point.
800 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700801 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000802 }
803
Narayan Kamath3764a262016-08-30 15:36:19 +0100804 // Close any logging related FDs before we start evaluating the list of
805 // file descriptors.
806 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -0700807 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +0100808
Chris Wailesaf594fc2018-11-02 11:00:07 -0700809 // If this is the first fork for this zygote, create the open FD table. If
810 // it isn't, we just need to check whether the list of open files has changed
811 // (and it shouldn't in the normal case).
Andreas Gamped5758f62018-03-12 12:08:55 -0700812 std::string error_msg;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800813 std::vector<int> fds_to_ignore;
Chris Wailesaf594fc2018-11-02 11:00:07 -0700814 if (!FillFileDescriptorVector(env, managed_fds_to_ignore, &fds_to_ignore, &error_msg)) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700815 fail_fn(error_msg);
816 }
Chris Wailesaf594fc2018-11-02 11:00:07 -0700817
818 if (gOpenFdTable == nullptr) {
Andreas Gampec362a442018-03-12 14:53:34 -0700819 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700820 if (gOpenFdTable == nullptr) {
Andreas Gampec362a442018-03-12 14:53:34 -0700821 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100822 }
Andreas Gampec362a442018-03-12 14:53:34 -0700823 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
824 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100825 }
826
Josh Gaod7951102018-06-26 16:05:12 -0700827 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
828
Narayan Kamath973b4662014-03-31 13:41:26 +0100829 pid_t pid = fork();
830
831 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700832 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700833 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700834
Narayan Kamath973b4662014-03-31 13:41:26 +0100835 // Clean up any descriptors which must be closed immediately
Chris Wailesaf594fc2018-11-02 11:00:07 -0700836 if (!DetachDescriptors(env, managed_fds_to_close, &error_msg)) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700837 fail_fn(error_msg);
838 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100839
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100840 // Re-open all remaining open file descriptors so that they aren't shared
841 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700842 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
843 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100844 }
Josh Gaod7951102018-06-26 16:05:12 -0700845
846 // Turn fdsan back on.
847 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -0700848 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100849
David Sehrde8d0bd2018-06-22 10:45:36 -0700850 // We blocked SIGCHLD prior to a fork, we unblock it here.
851 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
852 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100853 }
Chris Wailesaf594fc2018-11-02 11:00:07 -0700854
Narayan Kamath973b4662014-03-31 13:41:26 +0100855 return pid;
856}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700857
Chris Wailesaf594fc2018-11-02 11:00:07 -0700858// Utility routine to specialize a zygote child process.
859static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
860 jint runtime_flags, jobjectArray rlimits,
861 jlong permitted_capabilities, jlong effective_capabilities,
862 jint mount_external, jstring managed_se_info,
863 jstring managed_nice_name, bool is_system_server,
864 bool is_child_zygote, jstring managed_instruction_set,
865 jstring managed_app_data_dir, jstring managed_package_name,
866 jobjectArray managed_pacakges_for_uid,
867 jobjectArray managed_visible_vol_ids) {
868 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
869 managed_nice_name, _1);
870 auto extract_fn = std::bind(ExtractJString, env, is_system_server ? "system_server" : "zygote",
871 managed_nice_name, _1);
872
873 auto se_info = extract_fn(managed_se_info);
874 auto nice_name = extract_fn(managed_nice_name);
875 auto instruction_set = extract_fn(managed_instruction_set);
876 auto app_data_dir = extract_fn(managed_app_data_dir);
877 auto package_name = extract_fn(managed_package_name);
878
879 std::string error_msg;
880
881 // Keep capabilities across UID change, unless we're staying root.
882 if (uid != 0) {
883 if (!EnableKeepCapabilities(&error_msg)) {
884 fail_fn(error_msg);
885 }
886 }
887
888 if (!SetInheritable(permitted_capabilities, &error_msg)) {
889 fail_fn(error_msg);
890 }
891
892 if (!DropCapabilitiesBoundingSet(&error_msg)) {
893 fail_fn(error_msg);
894 }
895
896 bool use_native_bridge = !is_system_server &&
897 instruction_set.has_value() &&
898 android::NativeBridgeAvailable() &&
899 android::NeedsNativeBridge(instruction_set.value().c_str());
900
901 if (use_native_bridge && !app_data_dir.has_value()) {
902 // The app_data_dir variable should never be empty if we need to use a
903 // native bridge. In general, app_data_dir will never be empty for normal
904 // applications. It can only happen in special cases (for isolated
905 // processes which are not associated with any app). These are launched by
906 // the framework and should not be emulated anyway.
907 use_native_bridge = false;
908 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
909 }
910
911 if (!package_name.has_value()) {
912 if (is_system_server) {
913 package_name.emplace("android");
914 } else {
915 package_name.emplace("");
916 }
917 }
918
919 std::vector<std::string> packages_for_uid;
920 if (managed_pacakges_for_uid != nullptr) {
921 jsize count = env->GetArrayLength(managed_pacakges_for_uid);
922 for (jsize package_index = 0; package_index < count; ++package_index) {
923 jstring managed_package_for_uid =
924 (jstring) env->GetObjectArrayElement(managed_pacakges_for_uid, package_index);
925
926 auto package_for_uid = extract_fn(managed_package_for_uid);
927 if (LIKELY(package_for_uid.has_value())) {
928 packages_for_uid.emplace_back(std::move(package_for_uid.value()));
929 } else {
930 fail_fn("Null string found in managed packages_for_uid.");
931 }
932 }
933 }
934
935 std::vector<std::string> visible_vol_ids;
936 if (managed_visible_vol_ids != nullptr) {
937 jsize count = env->GetArrayLength(managed_visible_vol_ids);
938 for (jsize vol_id_index = 0; vol_id_index < count; ++vol_id_index) {
939 jstring managed_visible_vol_id =
940 (jstring) env->GetObjectArrayElement(managed_visible_vol_ids, vol_id_index);
941
942 auto visible_vol_id = extract_fn(managed_visible_vol_id);
943 if (LIKELY(visible_vol_id.has_value())) {
944 visible_vol_ids.emplace_back(std::move(visible_vol_id.value()));
945 } else {
946 fail_fn("Null string found in managed visible_vol_ids.");
947 }
948 }
949 }
950
951 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg,
952 package_name.value(), packages_for_uid, visible_vol_ids)) {
953 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
954 if (errno == ENOTCONN || errno == EROFS) {
955 // When device is actively encrypting, we get ENOTCONN here
956 // since FUSE was mounted before the framework restarted.
957 // When encrypted device is booting, we get EROFS since
958 // FUSE hasn't been created yet by init.
959 // In either case, continue without external storage.
960 } else {
961 fail_fn(error_msg);
962 }
963 }
964
965 // If this zygote isn't root, it won't be able to create a process group,
966 // since the directory is owned by root.
967 if (!is_system_server && getuid() == 0) {
968 int rc = createProcessGroup(uid, getpid());
969 if (rc == -EROFS) {
970 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
971 } else if (rc != 0) {
972 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
973 }
974 }
975
976 if (!SetGids(env, gids, &error_msg)) {
977 fail_fn(error_msg);
978 }
979
980 if (!SetRLimits(env, rlimits, &error_msg)) {
981 fail_fn(error_msg);
982 }
983
984 if (use_native_bridge) {
985 // Due to the logic behind use_native_bridge we know that both app_data_dir
986 // and instruction_set contain values.
987 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
988 instruction_set.value().c_str());
989 }
990
991 if (setresgid(gid, gid, gid) == -1) {
992 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
993 }
994
995 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
996 // before changing uid from 0, which clears capabilities. The other
997 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
998 // breaks SELinux domain transition (see b/71859146). As the result,
999 // privileged syscalls used below still need to be accessible in app process.
1000 SetUpSeccompFilter(uid);
1001
1002 if (setresuid(uid, uid, uid) == -1) {
1003 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1004 }
1005
1006 // The "dumpable" flag of a process, which controls core dump generation, is
1007 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1008 // user or group ID changes. See proc(5) for possible values. In most cases,
1009 // the value is 0, so core dumps are disabled for zygote children. However,
1010 // when running in a Chrome OS container, the value is already set to 2,
1011 // which allows the external crash reporter to collect all core dumps. Since
1012 // only system crashes are interested, core dump is disabled for app
1013 // processes. This also ensures compliance with CTS.
1014 int dumpable = prctl(PR_GET_DUMPABLE);
1015 if (dumpable == -1) {
1016 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1017 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1018 }
1019
1020 if (dumpable == 2 && uid >= AID_APP) {
1021 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1022 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1023 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1024 }
1025 }
1026
Orion Hodson8d005a62018-12-05 12:28:53 +00001027 // Set process properties to enable debugging if required.
1028 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1029 EnableDebugger();
1030 }
1031
Chris Wailesaf594fc2018-11-02 11:00:07 -07001032 if (NeedsNoRandomizeWorkaround()) {
1033 // Work around ARM kernel ASLR lossage (http://b/5817320).
1034 int old_personality = personality(0xffffffff);
1035 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1036 if (new_personality == -1) {
1037 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1038 }
1039 }
1040
1041 if (!SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities,
1042 &error_msg)) {
1043 fail_fn(error_msg);
1044 }
1045
1046 if (!SetSchedulerPolicy(&error_msg)) {
1047 fail_fn(error_msg);
1048 }
1049
1050 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1051 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1052
1053 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1054 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1055 uid, is_system_server, se_info_ptr, nice_name_ptr));
1056 }
1057
1058 // Make it easier to debug audit logs by setting the main thread's name to the
1059 // nice name rather than "app_process".
1060 if (nice_name.has_value()) {
1061 SetThreadName(nice_name.value().c_str());
1062 } else if (is_system_server) {
1063 SetThreadName("system_server");
1064 }
1065
1066 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1067 UnsetChldSignalHandler();
1068
1069 if (is_system_server) {
1070 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1071 if (env->ExceptionCheck()) {
1072 fail_fn("Error calling post fork system server hooks.");
1073 }
1074 // TODO(oth): Remove hardcoded label here (b/117874058).
1075 static const char* kSystemServerLabel = "u:r:system_server:s0";
1076 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1077 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1078 }
1079 }
1080
1081 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1082 is_system_server, is_child_zygote, managed_instruction_set);
1083
1084 if (env->ExceptionCheck()) {
1085 fail_fn("Error calling post fork hooks.");
1086 }
1087}
1088
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001089static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1090 __user_cap_header_struct capheader;
1091 memset(&capheader, 0, sizeof(capheader));
1092 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1093 capheader.pid = 0;
1094
1095 __user_cap_data_struct capdata[2];
1096 if (capget(&capheader, &capdata[0]) == -1) {
1097 ALOGE("capget failed: %s", strerror(errno));
1098 RuntimeAbort(env, __LINE__, "capget failed");
1099 }
1100
Chris Wailesaf594fc2018-11-02 11:00:07 -07001101 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1102}
1103
1104static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1105 bool is_child_zygote) {
1106 jlong capabilities = 0;
1107
1108 /*
1109 * Grant the following capabilities to the Bluetooth user:
1110 * - CAP_WAKE_ALARM
1111 * - CAP_NET_RAW
1112 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1113 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1114 */
1115
1116 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1117 capabilities |= (1LL << CAP_WAKE_ALARM);
1118 capabilities |= (1LL << CAP_NET_RAW);
1119 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1120 capabilities |= (1LL << CAP_SYS_NICE);
1121 }
1122
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001123 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1124 capabilities |= (1LL << CAP_NET_ADMIN);
1125 capabilities |= (1LL << CAP_NET_BROADCAST);
1126 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1127 capabilities |= (1LL << CAP_NET_RAW);
1128 }
1129
Chris Wailesaf594fc2018-11-02 11:00:07 -07001130 /*
1131 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1132 */
1133
1134 bool gid_wakelock_found = false;
1135 if (gid == AID_WAKELOCK) {
1136 gid_wakelock_found = true;
1137 } else if (gids != nullptr) {
1138 jsize gids_num = env->GetArrayLength(gids);
1139 ScopedIntArrayRO native_gid_proxy(env, gids);
1140
1141 if (native_gid_proxy.get() == nullptr) {
1142 RuntimeAbort(env, __LINE__, "Bad gids array");
1143 }
1144
1145 for (int gid_index = gids_num; --gids_num >= 0;) {
1146 if (native_gid_proxy[gid_index] == AID_WAKELOCK) {
1147 gid_wakelock_found = true;
1148 break;
1149 }
1150 }
1151 }
1152
1153 if (gid_wakelock_found) {
1154 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1155 }
1156
1157 /*
1158 * Grant child Zygote processes the following capabilities:
1159 * - CAP_SETUID (change UID of child processes)
1160 * - CAP_SETGID (change GID of child processes)
1161 * - CAP_SETPCAP (change capabilities of child processes)
1162 */
1163
1164 if (is_child_zygote) {
1165 capabilities |= (1LL << CAP_SETUID);
1166 capabilities |= (1LL << CAP_SETGID);
1167 capabilities |= (1LL << CAP_SETPCAP);
1168 }
1169
1170 /*
1171 * Containers run without some capabilities, so drop any caps that are not
1172 * available.
1173 */
1174
1175 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001176}
Narayan Kamath973b4662014-03-31 13:41:26 +01001177} // anonymous namespace
1178
1179namespace android {
1180
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001181static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001182 // security_getenforce is not allowed on app process. Initialize and cache
1183 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001184 g_is_security_enforced = security_getenforce();
1185}
1186
Christopher Ferris76de39e2017-06-20 16:13:40 -07001187static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1188 PreApplicationInit();
1189}
1190
Narayan Kamath973b4662014-03-31 13:41:26 +01001191static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1192 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001193 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001194 jint mount_external, jstring se_info, jstring nice_name,
1195 jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote,
1196 jstring instruction_set, jstring app_data_dir, jstring package_name,
1197 jobjectArray packages_for_uid, jobjectArray visible_vol_ids) {
1198 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001199
Chris Wailesaf594fc2018-11-02 11:00:07 -07001200 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001201 if (pid == 0) {
1202 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1203 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001204 mount_external, se_info, nice_name, false,
1205 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
1206 package_name, packages_for_uid, visible_vol_ids);
David Sehrde8d0bd2018-06-22 10:45:36 -07001207 }
1208 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001209}
1210
1211static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1212 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001213 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1214 jlong effective_capabilities) {
1215 pid_t pid = ForkCommon(env, true,
1216 /* managed_fds_to_close= */ nullptr,
1217 /* managed_fds_to_ignore= */ nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001218 if (pid == 0) {
1219 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001220 permitted_capabilities, effective_capabilities,
1221 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1222 false, nullptr, nullptr, nullptr, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001223 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001224 // The zygote process checks whether the child process has died or not.
1225 ALOGI("System server process %d has been created", pid);
1226 gSystemServerPid = pid;
1227 // There is a slight window that the system server process has crashed
1228 // but it went unnoticed because we haven't published its pid yet. So
1229 // we recheck here just to make sure that all is well.
1230 int status;
1231 if (waitpid(pid, &status, WNOHANG) == pid) {
1232 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001233 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001234 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001235
Minchan Kim5fa8af22018-06-27 11:32:40 +09001236 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
1237 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
1238 if (per_app_memcg) {
1239 // Assign system_server to the correct memory cgroup.
1240 // Not all devices mount /dev/memcg so check for the file first
1241 // to avoid unnecessarily printing errors and denials in the logs.
1242 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -08001243 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001244 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
1245 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001246 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001247 }
1248 return pid;
1249}
1250
Robert Sesek54e387d2016-12-02 17:27:50 -05001251static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1252 JNIEnv* env, jclass, jstring path) {
1253 ScopedUtfChars path_native(env, path);
1254 const char* path_cstr = path_native.c_str();
1255 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001256 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001257 }
1258 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1259}
1260
doheon1.lee885b7422016-01-20 13:07:27 +09001261static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1262 // Zygote process unmount root storage space initially before every child processes are forked.
1263 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001264 // and no need unmount storage operation in MountEmulatedStorage method.
1265 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1266
1267 // See storage config details at http://source.android.com/tech/storage/
1268 // Create private mount namespace shared by all children
1269 if (unshare(CLONE_NEWNS) == -1) {
1270 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1271 return;
1272 }
1273
1274 // Mark rootfs as being a slave so that changes from default
1275 // namespace only flow into our children.
1276 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1277 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1278 return;
1279 }
1280
1281 // Create a staging tmpfs that is shared by our children; they will
1282 // bind mount storage into their respective private namespaces, which
1283 // are isolated from each other.
1284 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1285 if (target_base != nullptr) {
1286#define STRINGIFY_UID(x) __STRING(x)
1287 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1288 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1289 ALOGE("Failed to mount tmpfs to %s", target_base);
1290 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1291 return;
1292 }
1293#undef STRINGIFY_UID
1294 }
doheon1.lee885b7422016-01-20 13:07:27 +09001295
1296 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001297}
1298
Daniel Micay76f6a862015-09-19 17:31:01 -04001299static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001300 { "nativeSecurityInit", "()V",
1301 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001302 { "nativeForkAndSpecialize",
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001303 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001304 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1305 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001306 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001307 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1308 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001309 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001310 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1311 { "nativePreApplicationInit", "()V",
1312 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001313};
1314
1315int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001316 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001317 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1318 "callPostForkSystemServerHooks",
1319 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001320 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001321 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001322
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001323 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001324}
1325} // namespace android