blob: 335f3204a1fe0037d0931885c15c1a62ceb6050d [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";
Narayan Kamath973b4662014-03-31 13:41:26 +010089static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
90static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +010091static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +010092static jmethodID gCallPostForkChildHooks;
93
Victor Hsiehc8176ef2018-01-08 12:43:00 -080094static bool g_is_security_enforced = true;
95
Narayan Kamath973b4662014-03-31 13:41:26 +010096// Must match values in com.android.internal.os.Zygote.
97enum MountExternalKind {
98 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -070099 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700100 MOUNT_EXTERNAL_READ = 2,
101 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800102 MOUNT_EXTERNAL_INSTALLER = 4,
103 MOUNT_EXTERNAL_FULL = 5,
Narayan Kamath973b4662014-03-31 13:41:26 +0100104};
105
Orion Hodson8d005a62018-12-05 12:28:53 +0000106// Must match values in com.android.internal.os.Zygote.
107enum RuntimeFlags : uint32_t {
108 DEBUG_ENABLE_JDWP = 1,
109};
110
Andreas Gampeb053cce2015-11-17 16:38:59 -0800111static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
112 std::ostringstream oss;
113 oss << __FILE__ << ":" << line << ": " << msg;
114 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100115}
116
117// This signal handler is for zygote mode, since the zygote must reap its children
118static void SigChldHandler(int /*signal_number*/) {
119 pid_t pid;
120 int status;
121
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700122 // It's necessary to save and restore the errno during this function.
123 // Since errno is stored per thread, changing it here modifies the errno
124 // on the thread on which this signal handler executes. If a signal occurs
125 // between a call and an errno check, it's possible to get the errno set
126 // here.
127 // See b/23572286 for extra information.
128 int saved_errno = errno;
129
Narayan Kamath973b4662014-03-31 13:41:26 +0100130 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
131 // Log process-death status that we care about. In general it is
132 // not safe to call LOG(...) from a signal handler because of
133 // possible reentrancy. However, we know a priori that the
134 // current implementation of LOG() is safe to call from a SIGCHLD
135 // handler in the zygote process. If the LOG() implementation
136 // changes its locking strategy or its use of syscalls within the
137 // lazy-init critical section, its use here may become unsafe.
138 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700139 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100140 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700141 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100142 if (WCOREDUMP(status)) {
143 ALOGI("Process %d dumped core.", pid);
144 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100145 }
146
147 // If the just-crashed process is the system_server, bring down zygote
148 // so that it is restarted by init and system server will be restarted
149 // from there.
150 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800151 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100152 kill(getpid(), SIGKILL);
153 }
154 }
155
Narayan Kamath160992d2014-04-14 14:46:07 +0100156 // Note that we shouldn't consider ECHILD an error because
157 // the secondary zygote might have no children left to wait for.
158 if (pid < 0 && errno != ECHILD) {
159 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100160 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700161
162 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100163}
164
yuanhao435e84b2018-01-15 15:37:02 +0800165// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
166// configured very late, because earlier in the runtime we may fork() and
167// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100168// have them be harvested immediately.
169//
yuanhao435e84b2018-01-15 15:37:02 +0800170// Ignore SIGHUP because all processes forked by the zygote are in the same
171// process group as the zygote and we don't want to be notified if we become
172// an orphaned group and have one or more stopped processes. This is not a
173// theoretical concern :
174// - we can become an orphaned group if one of our direct descendants forks
175// and is subsequently killed before its children.
176// - crash_dump routinely STOPs the process it's tracing.
177//
178// See issues b/71965619 and b/25567761 for further details.
179//
Narayan Kamath973b4662014-03-31 13:41:26 +0100180// This ends up being called repeatedly before each fork(), but there's
181// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800182static void SetSignalHandlers() {
183 struct sigaction sig_chld = {};
184 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100185
yuanhao435e84b2018-01-15 15:37:02 +0800186 if (sigaction(SIGCHLD, &sig_chld, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700187 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100188 }
yuanhao435e84b2018-01-15 15:37:02 +0800189
190 struct sigaction sig_hup = {};
191 sig_hup.sa_handler = SIG_IGN;
192 if (sigaction(SIGHUP, &sig_hup, NULL) < 0) {
193 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
194 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100195}
196
197// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800198static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100199 struct sigaction sa;
200 memset(&sa, 0, sizeof(sa));
201 sa.sa_handler = SIG_DFL;
202
yuanhao435e84b2018-01-15 15:37:02 +0800203 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700204 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100205 }
206}
207
208// Calls POSIX setgroups() using the int[] object as an argument.
209// A NULL argument is tolerated.
Andreas Gamped5758f62018-03-12 12:08:55 -0700210static bool SetGids(JNIEnv* env, jintArray javaGids, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100211 if (javaGids == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700212 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100213 }
214
215 ScopedIntArrayRO gids(env, javaGids);
216 if (gids.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700217 *error_msg = CREATE_ERROR("Getting gids int array failed");
218 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100219 }
220 int rc = setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0]));
221 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700222 *error_msg = CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size());
223 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100224 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700225
226 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100227}
228
229// Sets the resource limits via setrlimit(2) for the values in the
230// two-dimensional array of integers that's passed in. The second dimension
231// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
232// treated as an empty array.
Andreas Gamped5758f62018-03-12 12:08:55 -0700233static bool SetRLimits(JNIEnv* env, jobjectArray javaRlimits, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100234 if (javaRlimits == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700235 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100236 }
237
238 rlimit rlim;
239 memset(&rlim, 0, sizeof(rlim));
240
241 for (int i = 0; i < env->GetArrayLength(javaRlimits); ++i) {
242 ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
243 ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
244 if (javaRlimit.size() != 3) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700245 *error_msg = CREATE_ERROR("rlimits array must have a second dimension of size 3");
246 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100247 }
248
249 rlim.rlim_cur = javaRlimit[1];
250 rlim.rlim_max = javaRlimit[2];
251
252 int rc = setrlimit(javaRlimit[0], &rlim);
253 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700254 *error_msg = CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed", javaRlimit[0], rlim.rlim_cur,
Dan Albert46d84442014-11-18 16:07:51 -0800255 rlim.rlim_max);
Andreas Gamped5758f62018-03-12 12:08:55 -0700256 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100257 }
258 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700259
260 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100261}
262
Orion Hodson8d005a62018-12-05 12:28:53 +0000263static void EnableDebugger() {
264 // To let a non-privileged gdbserver attach to this
265 // process, we must set our dumpable flag.
266 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
267 ALOGE("prctl(PR_SET_DUMPABLE) failed");
268 }
269
270 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
271 // is enabled (see kernel/Documentation/security/Yama.txt).
272 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
273 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
274 // case since it's expected behaviour.
275 if (errno != EINVAL) {
276 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
277 }
278 }
279
280 // We don't want core dumps, though, so set the soft limit on core dump size
281 // to 0 without changing the hard limit.
282 rlimit rl;
283 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
284 ALOGE("getrlimit(RLIMIT_CORE) failed");
285 } else {
286 rl.rlim_cur = 0;
287 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
288 ALOGE("setrlimit(RLIMIT_CORE) failed");
289 }
290 }
291}
292
Narayan Kamath973b4662014-03-31 13:41:26 +0100293// The debug malloc library needs to know whether it's the zygote or a child.
294extern "C" int gMallocLeakZygoteChild;
295
Christopher Ferris76de39e2017-06-20 16:13:40 -0700296static void PreApplicationInit() {
297 // The child process sets this to indicate it's not the zygote.
298 gMallocLeakZygoteChild = 1;
299
300 // Set the jemalloc decay time to 1.
301 mallopt(M_DECAY_TIME, 1);
302}
303
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800304static void SetUpSeccompFilter(uid_t uid) {
305 if (!g_is_security_enforced) {
306 ALOGI("seccomp disabled by setenforce 0");
307 return;
308 }
309
310 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700311 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800312 set_app_seccomp_filter();
313 } else {
314 set_system_seccomp_filter();
315 }
316}
317
Andreas Gamped5758f62018-03-12 12:08:55 -0700318static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100319 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
320 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700321 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
322 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100323 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700324 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100325}
326
Andreas Gamped5758f62018-03-12 12:08:55 -0700327static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100328 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
329 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
330 if (rc == -1) {
331 if (errno == EINVAL) {
332 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
333 "your kernel is compiled with file capabilities support");
334 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700335 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
336 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100337 }
338 }
339 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700340 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100341}
342
Andreas Gamped5758f62018-03-12 12:08:55 -0700343static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800344 __user_cap_header_struct capheader;
345 memset(&capheader, 0, sizeof(capheader));
346 capheader.version = _LINUX_CAPABILITY_VERSION_3;
347 capheader.pid = 0;
348
349 __user_cap_data_struct capdata[2];
350 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700351 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
352 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800353 }
354
355 capdata[0].inheritable = inheritable;
356 capdata[1].inheritable = inheritable >> 32;
357
358 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700359 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
360 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800361 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700362
363 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800364}
365
Andreas Gamped5758f62018-03-12 12:08:55 -0700366static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
367 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100368 __user_cap_header_struct capheader;
369 memset(&capheader, 0, sizeof(capheader));
370 capheader.version = _LINUX_CAPABILITY_VERSION_3;
371 capheader.pid = 0;
372
373 __user_cap_data_struct capdata[2];
374 memset(&capdata, 0, sizeof(capdata));
375 capdata[0].effective = effective;
376 capdata[1].effective = effective >> 32;
377 capdata[0].permitted = permitted;
378 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800379 capdata[0].inheritable = inheritable;
380 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100381
382 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700383 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
384 "failed: %s", permitted, effective, inheritable, strerror(errno));
385 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100386 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700387 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100388}
389
Andreas Gamped5758f62018-03-12 12:08:55 -0700390static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100391 errno = -set_sched_policy(0, SP_DEFAULT);
392 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700393 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
394 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100395 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700396 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100397}
398
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700399static int UnmountTree(const char* path) {
400 size_t path_len = strlen(path);
401
402 FILE* fp = setmntent("/proc/mounts", "r");
403 if (fp == NULL) {
404 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
405 return -errno;
406 }
407
408 // Some volumes can be stacked on each other, so force unmount in
409 // reverse order to give us the best chance of success.
410 std::list<std::string> toUnmount;
411 mntent* mentry;
412 while ((mentry = getmntent(fp)) != NULL) {
413 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
414 toUnmount.push_front(std::string(mentry->mnt_dir));
415 }
416 }
417 endmntent(fp);
418
419 for (auto path : toUnmount) {
420 if (umount2(path.c_str(), MNT_DETACH)) {
421 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
422 }
423 }
424 return 0;
425}
426
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700427static bool createPkgSandbox(uid_t uid, const std::string& package_name, std::string* error_msg) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700428 // Create /mnt/user/0/package/<package-name>
429 userid_t user_id = multiuser_get_user_id(uid);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700430 std::string pkg_sandbox_dir = StringPrintf("/mnt/user/%d", user_id);
Sudheer Shanka8d8223e2018-08-03 18:18:21 -0700431 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700432 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
433 return false;
434 }
435 StringAppendF(&pkg_sandbox_dir, "/package");
436 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
437 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
438 return false;
439 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700440 StringAppendF(&pkg_sandbox_dir, "/%s", package_name.c_str());
Sudheer Shanka663b1042018-07-30 17:34:21 -0700441 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0755, uid, uid) != 0) {
442 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
443 return false;
444 }
445 return true;
446}
447
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800448static bool bindMount(const std::string& sourceDir, const std::string& targetDir,
449 std::string* error_msg) {
450 if (TEMP_FAILURE_RETRY(mount(sourceDir.c_str(), targetDir.c_str(),
451 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
452 *error_msg = CREATE_ERROR("Failed to mount %s to %s: %s",
453 sourceDir.c_str(), targetDir.c_str(), strerror(errno));
454 return false;
455 }
456 if (TEMP_FAILURE_RETRY(mount(nullptr, targetDir.c_str(),
457 nullptr, MS_SLAVE | MS_REC, nullptr)) == -1) {
458 *error_msg = CREATE_ERROR("Failed to set MS_SLAVE for %s", targetDir.c_str());
459 return false;
460 }
461 return true;
462}
463
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700464static bool mountPkgSpecificDir(const std::string& mntSourceRoot,
465 const std::string& mntTargetRoot, const std::string& packageName,
466 const char* dirName, std::string* error_msg) {
467 std::string mntSourceDir = StringPrintf("%s/Android/%s/%s",
468 mntSourceRoot.c_str(), dirName, packageName.c_str());
469 std::string mntTargetDir = StringPrintf("%s/Android/%s/%s",
470 mntTargetRoot.c_str(), dirName, packageName.c_str());
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800471 return bindMount(mntSourceDir, mntTargetDir, error_msg);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700472}
473
474static bool preparePkgSpecificDirs(const std::vector<std::string>& packageNames,
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800475 const std::vector<std::string>& volumeLabels, bool mountAllObbs,
476 userid_t userId, std::string* error_msg) {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700477 for (auto& label : volumeLabels) {
478 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", label.c_str());
479 std::string mntTarget = StringPrintf("/storage/%s", label.c_str());
480 if (label == "emulated") {
481 StringAppendF(&mntSource, "/%d", userId);
482 StringAppendF(&mntTarget, "/%d", userId);
483 }
484 for (auto& package : packageNames) {
485 mountPkgSpecificDir(mntSource, mntTarget, package, "data", error_msg);
486 mountPkgSpecificDir(mntSource, mntTarget, package, "media", error_msg);
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800487 if (!mountAllObbs) {
488 mountPkgSpecificDir(mntSource, mntTarget, package, "obb", error_msg);
489 }
490 }
491 if (mountAllObbs) {
492 StringAppendF(&mntSource, "/Android/obb");
493 StringAppendF(&mntTarget, "/Android/obb");
494 bindMount(mntSource, mntTarget, error_msg);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700495 }
496 }
497 return true;
498}
499
Narayan Kamath973b4662014-03-31 13:41:26 +0100500// Create a private mount namespace and bind mount appropriate emulated
501// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700502static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700503 bool force_mount_namespace, std::string* error_msg, const std::string& package_name,
504 const std::vector<std::string>& packages_for_uid,
505 const std::vector<std::string>& visible_vol_ids) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700506 // See storage config details at http://source.android.com/tech/storage/
507
Jeff Sharkey9527b222015-06-24 15:24:48 -0700508 String8 storageSource;
509 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700510 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700511 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700512 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700513 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700514 storageSource = "/mnt/runtime/write";
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800515 } else if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700516 // Sane default of no storage visible
517 return true;
518 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400519
520 // Create a second private mount namespace for our process
521 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700522 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400523 return false;
524 }
525
Robert Sesek06f39302017-03-20 17:30:05 -0400526 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
527 if (mount_mode == MOUNT_EXTERNAL_NONE) {
528 return true;
529 }
530
Sudheer Shanka663b1042018-07-30 17:34:21 -0700531 if (GetBoolProperty(kIsolatedStorage, false)) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700532 if (mount_mode == MOUNT_EXTERNAL_FULL) {
533 storageSource = "/mnt/runtime/write";
534 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
535 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
536 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
537 storageSource.string(),
538 strerror(errno));
539 return false;
540 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700541
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700542 // Mount user-specific symlink helper into place
543 userid_t user_id = multiuser_get_user_id(uid);
544 const String8 userSource(String8::format("/mnt/user/%d", user_id));
545 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
546 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
547 return false;
548 }
549 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
550 NULL, MS_BIND, NULL)) == -1) {
551 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
552 userSource.string(),
553 strerror(errno));
554 return false;
555 }
556 } else {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700557 if (package_name.empty()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700558 return true;
559 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700560 userid_t user_id = multiuser_get_user_id(uid);
561 std::string pkgSandboxDir = StringPrintf("/mnt/user/%d/package/%s",
562 user_id, package_name.c_str());
563 struct stat sb;
564 bool sandboxAlreadyCreated = true;
565 if (TEMP_FAILURE_RETRY(lstat(pkgSandboxDir.c_str(), &sb)) == -1) {
566 if (errno == ENOENT) {
567 ALOGD("Sandbox not yet created for %s", pkgSandboxDir.c_str());
568 sandboxAlreadyCreated = false;
569 if (!createPkgSandbox(uid, package_name, error_msg)) {
570 return false;
571 }
572 } else {
573 ALOGE("Failed to lstat %s", pkgSandboxDir.c_str());
574 return false;
575 }
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700576 }
577 if (TEMP_FAILURE_RETRY(mount(pkgSandboxDir.c_str(), "/storage",
578 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
579 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
580 pkgSandboxDir.c_str(), strerror(errno));
581 return false;
582 }
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800583 if (access("/storage/obb_mount", F_OK) == 0) {
584 if (mount_mode != MOUNT_EXTERNAL_INSTALLER) {
585 remove("/storage/obb_mount");
586 }
587 } else {
588 if (mount_mode == MOUNT_EXTERNAL_INSTALLER) {
589 int fd = TEMP_FAILURE_RETRY(open("/storage/obb_mount",
590 O_RDWR | O_CREAT, 0660));
591 if (fd == -1) {
592 *error_msg = CREATE_ERROR("Couldn't create /storage/obb_mount: %s",
593 strerror(errno));
594 return false;
595 }
596 close(fd);
597 }
598 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700599 // If the sandbox was already created by vold, only then set up the bind mounts for
600 // pkg specific directories. Otherwise, leave as is and bind mounts will be taken
601 // care of by vold later.
602 if (sandboxAlreadyCreated) {
603 if (!preparePkgSpecificDirs(packages_for_uid, visible_vol_ids,
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800604 mount_mode == MOUNT_EXTERNAL_INSTALLER, user_id, error_msg)) {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700605 return false;
606 }
607 }
Sudheer Shanka663b1042018-07-30 17:34:21 -0700608 }
609 } else {
610 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
611 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
612 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
613 storageSource.string(),
614 strerror(errno));
615 return false;
616 }
617
618 // Mount user-specific symlink helper into place
619 userid_t user_id = multiuser_get_user_id(uid);
620 const String8 userSource(String8::format("/mnt/user/%d", user_id));
621 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
622 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
623 return false;
624 }
625 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
626 NULL, MS_BIND, NULL)) == -1) {
627 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
628 userSource.string(),
629 strerror(errno));
630 return false;
631 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700632 }
633
Narayan Kamath973b4662014-03-31 13:41:26 +0100634 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100635}
636
Narayan Kamath973b4662014-03-31 13:41:26 +0100637static bool NeedsNoRandomizeWorkaround() {
638#if !defined(__arm__)
639 return false;
640#else
641 int major;
642 int minor;
643 struct utsname uts;
644 if (uname(&uts) == -1) {
645 return false;
646 }
647
648 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
649 return false;
650 }
651
652 // Kernels before 3.4.* need the workaround.
653 return (major < 3) || ((major == 3) && (minor < 4));
654#endif
655}
Narayan Kamath973b4662014-03-31 13:41:26 +0100656
657// Utility to close down the Zygote socket file descriptors while
658// the child is still running as root with Zygote's privileges. Each
659// descriptor (if any) is closed via dup2(), replacing it with a valid
660// (open) descriptor to /dev/null.
661
Andreas Gamped5758f62018-03-12 12:08:55 -0700662static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100663 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700664 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100665 }
666 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200667 ScopedIntArrayRO ar(env, fdsToClose);
668 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700669 *error_msg = "Bad fd array";
670 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100671 }
672 jsize i;
673 int devnull;
674 for (i = 0; i < count; i++) {
675 devnull = open("/dev/null", O_RDWR);
676 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700677 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
678 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100679 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700680 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100681 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700682 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
683 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100684 }
685 close(devnull);
686 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700687 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100688}
689
690void SetThreadName(const char* thread_name) {
691 bool hasAt = false;
692 bool hasDot = false;
693 const char* s = thread_name;
694 while (*s) {
695 if (*s == '.') {
696 hasDot = true;
697 } else if (*s == '@') {
698 hasAt = true;
699 }
700 s++;
701 }
702 const int len = s - thread_name;
703 if (len < 15 || hasAt || !hasDot) {
704 s = thread_name;
705 } else {
706 s = thread_name + len - 15;
707 }
708 // pthread_setname_np fails rather than truncating long strings.
709 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
710 strlcpy(buf, s, sizeof(buf)-1);
711 errno = pthread_setname_np(pthread_self(), buf);
712 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700713 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100714 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800715 // Update base::logging default tag.
716 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100717}
718
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100719// The list of open zygote file descriptors.
720static FileDescriptorTable* gOpenFdTable = NULL;
721
Andreas Gamped5758f62018-03-12 12:08:55 -0700722static bool FillFileDescriptorVector(JNIEnv* env,
Chris Wailesaf594fc2018-11-02 11:00:07 -0700723 jintArray managed_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700724 std::vector<int>* fds,
725 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800726 CHECK(fds != nullptr);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700727 if (managed_fds != nullptr) {
728 ScopedIntArrayRO ar(env, managed_fds);
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800729 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700730 *error_msg = "Bad fd array";
731 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800732 }
733 fds->reserve(ar.size());
734 for (size_t i = 0; i < ar.size(); ++i) {
735 fds->push_back(ar[i]);
736 }
737 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700738 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800739}
740
Chris Wailesaf594fc2018-11-02 11:00:07 -0700741[[noreturn]]
742static void ZygoteFailure(JNIEnv* env,
743 const char* process_name,
744 jstring managed_process_name,
745 const std::string& msg) {
746 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
747 if (managed_process_name != nullptr) {
748 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
749 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
750 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -0700751 }
752 }
753
Chris Wailesaf594fc2018-11-02 11:00:07 -0700754 const std::string& error_msg =
755 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700756
Chris Wailesaf594fc2018-11-02 11:00:07 -0700757 env->FatalError(error_msg.c_str());
758 __builtin_unreachable();
759}
David Sehrde8d0bd2018-06-22 10:45:36 -0700760
Chris Wailesaf594fc2018-11-02 11:00:07 -0700761static std::optional<std::string> ExtractJString(JNIEnv* env,
762 const char* process_name,
763 jstring managed_process_name,
764 jstring managed_string) {
765 if (managed_string == nullptr) {
766 return std::optional<std::string>();
767 } else {
768 ScopedUtfChars scoped_string_chars(env, managed_string);
769
770 if (scoped_string_chars.c_str() != nullptr) {
771 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700772 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -0700773 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700774 }
775 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700776}
777
Chris Wailesaf594fc2018-11-02 11:00:07 -0700778// Utility routine to fork a zygote.
779static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
780 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore) {
yuanhao435e84b2018-01-15 15:37:02 +0800781 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100782
David Sehrde8d0bd2018-06-22 10:45:36 -0700783 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000784 sigset_t sigchld;
785 sigemptyset(&sigchld);
786 sigaddset(&sigchld, SIGCHLD);
787
Chris Wailesaf594fc2018-11-02 11:00:07 -0700788 // Curry a failure function.
789 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
790 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -0700791
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000792 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
793 // log, which would result in the logging FDs we close being reopened.
794 // This would cause failures because the FDs are not whitelisted.
795 //
796 // Note that the zygote process is single threaded at this point.
797 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700798 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000799 }
800
Narayan Kamath3764a262016-08-30 15:36:19 +0100801 // Close any logging related FDs before we start evaluating the list of
802 // file descriptors.
803 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -0700804 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +0100805
Chris Wailesaf594fc2018-11-02 11:00:07 -0700806 // If this is the first fork for this zygote, create the open FD table. If
807 // it isn't, we just need to check whether the list of open files has changed
808 // (and it shouldn't in the normal case).
Andreas Gamped5758f62018-03-12 12:08:55 -0700809 std::string error_msg;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800810 std::vector<int> fds_to_ignore;
Chris Wailesaf594fc2018-11-02 11:00:07 -0700811 if (!FillFileDescriptorVector(env, managed_fds_to_ignore, &fds_to_ignore, &error_msg)) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700812 fail_fn(error_msg);
813 }
Chris Wailesaf594fc2018-11-02 11:00:07 -0700814
815 if (gOpenFdTable == nullptr) {
Andreas Gampec362a442018-03-12 14:53:34 -0700816 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700817 if (gOpenFdTable == nullptr) {
Andreas Gampec362a442018-03-12 14:53:34 -0700818 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100819 }
Andreas Gampec362a442018-03-12 14:53:34 -0700820 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
821 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100822 }
823
Josh Gaod7951102018-06-26 16:05:12 -0700824 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
825
Narayan Kamath973b4662014-03-31 13:41:26 +0100826 pid_t pid = fork();
827
828 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700829 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700830 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700831
Narayan Kamath973b4662014-03-31 13:41:26 +0100832 // Clean up any descriptors which must be closed immediately
Chris Wailesaf594fc2018-11-02 11:00:07 -0700833 if (!DetachDescriptors(env, managed_fds_to_close, &error_msg)) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700834 fail_fn(error_msg);
835 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100836
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100837 // Re-open all remaining open file descriptors so that they aren't shared
838 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700839 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
840 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100841 }
Josh Gaod7951102018-06-26 16:05:12 -0700842
843 // Turn fdsan back on.
844 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -0700845 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100846
David Sehrde8d0bd2018-06-22 10:45:36 -0700847 // We blocked SIGCHLD prior to a fork, we unblock it here.
848 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
849 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100850 }
Chris Wailesaf594fc2018-11-02 11:00:07 -0700851
Narayan Kamath973b4662014-03-31 13:41:26 +0100852 return pid;
853}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700854
Chris Wailesaf594fc2018-11-02 11:00:07 -0700855// Utility routine to specialize a zygote child process.
856static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
857 jint runtime_flags, jobjectArray rlimits,
858 jlong permitted_capabilities, jlong effective_capabilities,
859 jint mount_external, jstring managed_se_info,
860 jstring managed_nice_name, bool is_system_server,
861 bool is_child_zygote, jstring managed_instruction_set,
862 jstring managed_app_data_dir, jstring managed_package_name,
863 jobjectArray managed_pacakges_for_uid,
864 jobjectArray managed_visible_vol_ids) {
865 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
866 managed_nice_name, _1);
867 auto extract_fn = std::bind(ExtractJString, env, is_system_server ? "system_server" : "zygote",
868 managed_nice_name, _1);
869
870 auto se_info = extract_fn(managed_se_info);
871 auto nice_name = extract_fn(managed_nice_name);
872 auto instruction_set = extract_fn(managed_instruction_set);
873 auto app_data_dir = extract_fn(managed_app_data_dir);
874 auto package_name = extract_fn(managed_package_name);
875
876 std::string error_msg;
877
878 // Keep capabilities across UID change, unless we're staying root.
879 if (uid != 0) {
880 if (!EnableKeepCapabilities(&error_msg)) {
881 fail_fn(error_msg);
882 }
883 }
884
885 if (!SetInheritable(permitted_capabilities, &error_msg)) {
886 fail_fn(error_msg);
887 }
888
889 if (!DropCapabilitiesBoundingSet(&error_msg)) {
890 fail_fn(error_msg);
891 }
892
893 bool use_native_bridge = !is_system_server &&
894 instruction_set.has_value() &&
895 android::NativeBridgeAvailable() &&
896 android::NeedsNativeBridge(instruction_set.value().c_str());
897
898 if (use_native_bridge && !app_data_dir.has_value()) {
899 // The app_data_dir variable should never be empty if we need to use a
900 // native bridge. In general, app_data_dir will never be empty for normal
901 // applications. It can only happen in special cases (for isolated
902 // processes which are not associated with any app). These are launched by
903 // the framework and should not be emulated anyway.
904 use_native_bridge = false;
905 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
906 }
907
908 if (!package_name.has_value()) {
909 if (is_system_server) {
910 package_name.emplace("android");
911 } else {
912 package_name.emplace("");
913 }
914 }
915
916 std::vector<std::string> packages_for_uid;
917 if (managed_pacakges_for_uid != nullptr) {
918 jsize count = env->GetArrayLength(managed_pacakges_for_uid);
919 for (jsize package_index = 0; package_index < count; ++package_index) {
920 jstring managed_package_for_uid =
921 (jstring) env->GetObjectArrayElement(managed_pacakges_for_uid, package_index);
922
923 auto package_for_uid = extract_fn(managed_package_for_uid);
924 if (LIKELY(package_for_uid.has_value())) {
925 packages_for_uid.emplace_back(std::move(package_for_uid.value()));
926 } else {
927 fail_fn("Null string found in managed packages_for_uid.");
928 }
929 }
930 }
931
932 std::vector<std::string> visible_vol_ids;
933 if (managed_visible_vol_ids != nullptr) {
934 jsize count = env->GetArrayLength(managed_visible_vol_ids);
935 for (jsize vol_id_index = 0; vol_id_index < count; ++vol_id_index) {
936 jstring managed_visible_vol_id =
937 (jstring) env->GetObjectArrayElement(managed_visible_vol_ids, vol_id_index);
938
939 auto visible_vol_id = extract_fn(managed_visible_vol_id);
940 if (LIKELY(visible_vol_id.has_value())) {
941 visible_vol_ids.emplace_back(std::move(visible_vol_id.value()));
942 } else {
943 fail_fn("Null string found in managed visible_vol_ids.");
944 }
945 }
946 }
947
948 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg,
949 package_name.value(), packages_for_uid, visible_vol_ids)) {
950 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
951 if (errno == ENOTCONN || errno == EROFS) {
952 // When device is actively encrypting, we get ENOTCONN here
953 // since FUSE was mounted before the framework restarted.
954 // When encrypted device is booting, we get EROFS since
955 // FUSE hasn't been created yet by init.
956 // In either case, continue without external storage.
957 } else {
958 fail_fn(error_msg);
959 }
960 }
961
962 // If this zygote isn't root, it won't be able to create a process group,
963 // since the directory is owned by root.
964 if (!is_system_server && getuid() == 0) {
965 int rc = createProcessGroup(uid, getpid());
966 if (rc == -EROFS) {
967 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
968 } else if (rc != 0) {
969 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
970 }
971 }
972
973 if (!SetGids(env, gids, &error_msg)) {
974 fail_fn(error_msg);
975 }
976
977 if (!SetRLimits(env, rlimits, &error_msg)) {
978 fail_fn(error_msg);
979 }
980
981 if (use_native_bridge) {
982 // Due to the logic behind use_native_bridge we know that both app_data_dir
983 // and instruction_set contain values.
984 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
985 instruction_set.value().c_str());
986 }
987
988 if (setresgid(gid, gid, gid) == -1) {
989 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
990 }
991
992 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
993 // before changing uid from 0, which clears capabilities. The other
994 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
995 // breaks SELinux domain transition (see b/71859146). As the result,
996 // privileged syscalls used below still need to be accessible in app process.
997 SetUpSeccompFilter(uid);
998
999 if (setresuid(uid, uid, uid) == -1) {
1000 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1001 }
1002
1003 // The "dumpable" flag of a process, which controls core dump generation, is
1004 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1005 // user or group ID changes. See proc(5) for possible values. In most cases,
1006 // the value is 0, so core dumps are disabled for zygote children. However,
1007 // when running in a Chrome OS container, the value is already set to 2,
1008 // which allows the external crash reporter to collect all core dumps. Since
1009 // only system crashes are interested, core dump is disabled for app
1010 // processes. This also ensures compliance with CTS.
1011 int dumpable = prctl(PR_GET_DUMPABLE);
1012 if (dumpable == -1) {
1013 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1014 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1015 }
1016
1017 if (dumpable == 2 && uid >= AID_APP) {
1018 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1019 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1020 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1021 }
1022 }
1023
Orion Hodson8d005a62018-12-05 12:28:53 +00001024 // Set process properties to enable debugging if required.
1025 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1026 EnableDebugger();
1027 }
1028
Chris Wailesaf594fc2018-11-02 11:00:07 -07001029 if (NeedsNoRandomizeWorkaround()) {
1030 // Work around ARM kernel ASLR lossage (http://b/5817320).
1031 int old_personality = personality(0xffffffff);
1032 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1033 if (new_personality == -1) {
1034 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1035 }
1036 }
1037
1038 if (!SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities,
1039 &error_msg)) {
1040 fail_fn(error_msg);
1041 }
1042
1043 if (!SetSchedulerPolicy(&error_msg)) {
1044 fail_fn(error_msg);
1045 }
1046
1047 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1048 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1049
1050 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1051 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1052 uid, is_system_server, se_info_ptr, nice_name_ptr));
1053 }
1054
1055 // Make it easier to debug audit logs by setting the main thread's name to the
1056 // nice name rather than "app_process".
1057 if (nice_name.has_value()) {
1058 SetThreadName(nice_name.value().c_str());
1059 } else if (is_system_server) {
1060 SetThreadName("system_server");
1061 }
1062
1063 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1064 UnsetChldSignalHandler();
1065
1066 if (is_system_server) {
1067 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1068 if (env->ExceptionCheck()) {
1069 fail_fn("Error calling post fork system server hooks.");
1070 }
1071 // TODO(oth): Remove hardcoded label here (b/117874058).
1072 static const char* kSystemServerLabel = "u:r:system_server:s0";
1073 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1074 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1075 }
1076 }
1077
1078 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1079 is_system_server, is_child_zygote, managed_instruction_set);
1080
1081 if (env->ExceptionCheck()) {
1082 fail_fn("Error calling post fork hooks.");
1083 }
1084}
1085
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001086static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1087 __user_cap_header_struct capheader;
1088 memset(&capheader, 0, sizeof(capheader));
1089 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1090 capheader.pid = 0;
1091
1092 __user_cap_data_struct capdata[2];
1093 if (capget(&capheader, &capdata[0]) == -1) {
1094 ALOGE("capget failed: %s", strerror(errno));
1095 RuntimeAbort(env, __LINE__, "capget failed");
1096 }
1097
Chris Wailesaf594fc2018-11-02 11:00:07 -07001098 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1099}
1100
1101static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1102 bool is_child_zygote) {
1103 jlong capabilities = 0;
1104
1105 /*
1106 * Grant the following capabilities to the Bluetooth user:
1107 * - CAP_WAKE_ALARM
1108 * - CAP_NET_RAW
1109 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1110 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1111 */
1112
1113 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1114 capabilities |= (1LL << CAP_WAKE_ALARM);
1115 capabilities |= (1LL << CAP_NET_RAW);
1116 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1117 capabilities |= (1LL << CAP_SYS_NICE);
1118 }
1119
1120 /*
1121 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1122 */
1123
1124 bool gid_wakelock_found = false;
1125 if (gid == AID_WAKELOCK) {
1126 gid_wakelock_found = true;
1127 } else if (gids != nullptr) {
1128 jsize gids_num = env->GetArrayLength(gids);
1129 ScopedIntArrayRO native_gid_proxy(env, gids);
1130
1131 if (native_gid_proxy.get() == nullptr) {
1132 RuntimeAbort(env, __LINE__, "Bad gids array");
1133 }
1134
1135 for (int gid_index = gids_num; --gids_num >= 0;) {
1136 if (native_gid_proxy[gid_index] == AID_WAKELOCK) {
1137 gid_wakelock_found = true;
1138 break;
1139 }
1140 }
1141 }
1142
1143 if (gid_wakelock_found) {
1144 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1145 }
1146
1147 /*
1148 * Grant child Zygote processes the following capabilities:
1149 * - CAP_SETUID (change UID of child processes)
1150 * - CAP_SETGID (change GID of child processes)
1151 * - CAP_SETPCAP (change capabilities of child processes)
1152 */
1153
1154 if (is_child_zygote) {
1155 capabilities |= (1LL << CAP_SETUID);
1156 capabilities |= (1LL << CAP_SETGID);
1157 capabilities |= (1LL << CAP_SETPCAP);
1158 }
1159
1160 /*
1161 * Containers run without some capabilities, so drop any caps that are not
1162 * available.
1163 */
1164
1165 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001166}
Narayan Kamath973b4662014-03-31 13:41:26 +01001167} // anonymous namespace
1168
1169namespace android {
1170
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001171static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001172 // security_getenforce is not allowed on app process. Initialize and cache
1173 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001174 g_is_security_enforced = security_getenforce();
1175}
1176
Christopher Ferris76de39e2017-06-20 16:13:40 -07001177static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1178 PreApplicationInit();
1179}
1180
Narayan Kamath973b4662014-03-31 13:41:26 +01001181static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1182 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001183 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001184 jint mount_external, jstring se_info, jstring nice_name,
1185 jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote,
1186 jstring instruction_set, jstring app_data_dir, jstring package_name,
1187 jobjectArray packages_for_uid, jobjectArray visible_vol_ids) {
1188 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001189
Chris Wailesaf594fc2018-11-02 11:00:07 -07001190 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001191 if (pid == 0) {
1192 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1193 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001194 mount_external, se_info, nice_name, false,
1195 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
1196 package_name, packages_for_uid, visible_vol_ids);
David Sehrde8d0bd2018-06-22 10:45:36 -07001197 }
1198 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001199}
1200
1201static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1202 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001203 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1204 jlong effective_capabilities) {
1205 pid_t pid = ForkCommon(env, true,
1206 /* managed_fds_to_close= */ nullptr,
1207 /* managed_fds_to_ignore= */ nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001208 if (pid == 0) {
1209 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001210 permitted_capabilities, effective_capabilities,
1211 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1212 false, nullptr, nullptr, nullptr, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001213 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001214 // The zygote process checks whether the child process has died or not.
1215 ALOGI("System server process %d has been created", pid);
1216 gSystemServerPid = pid;
1217 // There is a slight window that the system server process has crashed
1218 // but it went unnoticed because we haven't published its pid yet. So
1219 // we recheck here just to make sure that all is well.
1220 int status;
1221 if (waitpid(pid, &status, WNOHANG) == pid) {
1222 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001223 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001224 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001225
Minchan Kim5fa8af22018-06-27 11:32:40 +09001226 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
1227 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
1228 if (per_app_memcg) {
1229 // Assign system_server to the correct memory cgroup.
1230 // Not all devices mount /dev/memcg so check for the file first
1231 // to avoid unnecessarily printing errors and denials in the logs.
1232 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -08001233 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001234 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
1235 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001236 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001237 }
1238 return pid;
1239}
1240
Robert Sesek54e387d2016-12-02 17:27:50 -05001241static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1242 JNIEnv* env, jclass, jstring path) {
1243 ScopedUtfChars path_native(env, path);
1244 const char* path_cstr = path_native.c_str();
1245 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001246 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001247 }
1248 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1249}
1250
doheon1.lee885b7422016-01-20 13:07:27 +09001251static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1252 // Zygote process unmount root storage space initially before every child processes are forked.
1253 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001254 // and no need unmount storage operation in MountEmulatedStorage method.
1255 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1256
1257 // See storage config details at http://source.android.com/tech/storage/
1258 // Create private mount namespace shared by all children
1259 if (unshare(CLONE_NEWNS) == -1) {
1260 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1261 return;
1262 }
1263
1264 // Mark rootfs as being a slave so that changes from default
1265 // namespace only flow into our children.
1266 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1267 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1268 return;
1269 }
1270
1271 // Create a staging tmpfs that is shared by our children; they will
1272 // bind mount storage into their respective private namespaces, which
1273 // are isolated from each other.
1274 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1275 if (target_base != nullptr) {
1276#define STRINGIFY_UID(x) __STRING(x)
1277 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1278 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1279 ALOGE("Failed to mount tmpfs to %s", target_base);
1280 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1281 return;
1282 }
1283#undef STRINGIFY_UID
1284 }
doheon1.lee885b7422016-01-20 13:07:27 +09001285
1286 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001287}
1288
Daniel Micay76f6a862015-09-19 17:31:01 -04001289static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001290 { "nativeSecurityInit", "()V",
1291 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001292 { "nativeForkAndSpecialize",
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001293 "(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 +01001294 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1295 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001296 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001297 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1298 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001299 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001300 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1301 { "nativePreApplicationInit", "()V",
1302 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001303};
1304
1305int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001306 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001307 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1308 "callPostForkSystemServerHooks",
1309 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001310 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001311 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001312
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001313 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001314}
1315} // namespace android