blob: ff4591fb7f453dcb870c2fe43b4d9323ab8b5e2d [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
Orion Hodson2b71ad02018-12-07 16:44:33 +0000280 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
281 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
282 // Set the soft limit on core dump size to 0 without changing the hard limit.
283 rlimit rl;
284 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
285 ALOGE("getrlimit(RLIMIT_CORE) failed");
286 } else {
287 rl.rlim_cur = 0;
288 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
289 ALOGE("setrlimit(RLIMIT_CORE) failed");
290 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000291 }
292 }
293}
294
Narayan Kamath973b4662014-03-31 13:41:26 +0100295// The debug malloc library needs to know whether it's the zygote or a child.
296extern "C" int gMallocLeakZygoteChild;
297
Christopher Ferris76de39e2017-06-20 16:13:40 -0700298static void PreApplicationInit() {
299 // The child process sets this to indicate it's not the zygote.
300 gMallocLeakZygoteChild = 1;
301
302 // Set the jemalloc decay time to 1.
303 mallopt(M_DECAY_TIME, 1);
304}
305
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800306static void SetUpSeccompFilter(uid_t uid) {
307 if (!g_is_security_enforced) {
308 ALOGI("seccomp disabled by setenforce 0");
309 return;
310 }
311
312 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700313 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800314 set_app_seccomp_filter();
315 } else {
316 set_system_seccomp_filter();
317 }
318}
319
Andreas Gamped5758f62018-03-12 12:08:55 -0700320static bool EnableKeepCapabilities(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100321 int rc = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
322 if (rc == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700323 *error_msg = CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno));
324 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100325 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700326 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100327}
328
Andreas Gamped5758f62018-03-12 12:08:55 -0700329static bool DropCapabilitiesBoundingSet(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100330 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
331 int rc = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
332 if (rc == -1) {
333 if (errno == EINVAL) {
334 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
335 "your kernel is compiled with file capabilities support");
336 } else {
Andreas Gamped5758f62018-03-12 12:08:55 -0700337 *error_msg = CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno));
338 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100339 }
340 }
341 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700342 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100343}
344
Andreas Gamped5758f62018-03-12 12:08:55 -0700345static bool SetInheritable(uint64_t inheritable, std::string* error_msg) {
Josh Gao45dab782017-02-01 14:56:09 -0800346 __user_cap_header_struct capheader;
347 memset(&capheader, 0, sizeof(capheader));
348 capheader.version = _LINUX_CAPABILITY_VERSION_3;
349 capheader.pid = 0;
350
351 __user_cap_data_struct capdata[2];
352 if (capget(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700353 *error_msg = CREATE_ERROR("capget failed: %s", strerror(errno));
354 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800355 }
356
357 capdata[0].inheritable = inheritable;
358 capdata[1].inheritable = inheritable >> 32;
359
360 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700361 *error_msg = CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno));
362 return false;
Josh Gao45dab782017-02-01 14:56:09 -0800363 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700364
365 return true;
Josh Gao45dab782017-02-01 14:56:09 -0800366}
367
Andreas Gamped5758f62018-03-12 12:08:55 -0700368static bool SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
369 std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100370 __user_cap_header_struct capheader;
371 memset(&capheader, 0, sizeof(capheader));
372 capheader.version = _LINUX_CAPABILITY_VERSION_3;
373 capheader.pid = 0;
374
375 __user_cap_data_struct capdata[2];
376 memset(&capdata, 0, sizeof(capdata));
377 capdata[0].effective = effective;
378 capdata[1].effective = effective >> 32;
379 capdata[0].permitted = permitted;
380 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800381 capdata[0].inheritable = inheritable;
382 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100383
384 if (capset(&capheader, &capdata[0]) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700385 *error_msg = CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
386 "failed: %s", permitted, effective, inheritable, strerror(errno));
387 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100388 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700389 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100390}
391
Andreas Gamped5758f62018-03-12 12:08:55 -0700392static bool SetSchedulerPolicy(std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100393 errno = -set_sched_policy(0, SP_DEFAULT);
394 if (errno != 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700395 *error_msg = CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno));
396 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100397 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700398 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100399}
400
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700401static int UnmountTree(const char* path) {
402 size_t path_len = strlen(path);
403
404 FILE* fp = setmntent("/proc/mounts", "r");
405 if (fp == NULL) {
406 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
407 return -errno;
408 }
409
410 // Some volumes can be stacked on each other, so force unmount in
411 // reverse order to give us the best chance of success.
412 std::list<std::string> toUnmount;
413 mntent* mentry;
414 while ((mentry = getmntent(fp)) != NULL) {
415 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
416 toUnmount.push_front(std::string(mentry->mnt_dir));
417 }
418 }
419 endmntent(fp);
420
Chih-Hung Hsieha1b644e2018-12-11 11:09:20 -0800421 for (const auto& path : toUnmount) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700422 if (umount2(path.c_str(), MNT_DETACH)) {
423 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
424 }
425 }
426 return 0;
427}
428
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700429static bool createPkgSandbox(uid_t uid, const std::string& package_name, std::string* error_msg) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700430 // Create /mnt/user/0/package/<package-name>
431 userid_t user_id = multiuser_get_user_id(uid);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700432 std::string pkg_sandbox_dir = StringPrintf("/mnt/user/%d", user_id);
Sudheer Shanka8d8223e2018-08-03 18:18:21 -0700433 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700434 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
435 return false;
436 }
437 StringAppendF(&pkg_sandbox_dir, "/package");
438 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
439 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
440 return false;
441 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700442 StringAppendF(&pkg_sandbox_dir, "/%s", package_name.c_str());
Sudheer Shanka663b1042018-07-30 17:34:21 -0700443 if (fs_prepare_dir(pkg_sandbox_dir.c_str(), 0755, uid, uid) != 0) {
444 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", pkg_sandbox_dir.c_str());
445 return false;
446 }
447 return true;
448}
449
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800450static bool bindMount(const std::string& sourceDir, const std::string& targetDir,
451 std::string* error_msg) {
452 if (TEMP_FAILURE_RETRY(mount(sourceDir.c_str(), targetDir.c_str(),
453 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
454 *error_msg = CREATE_ERROR("Failed to mount %s to %s: %s",
455 sourceDir.c_str(), targetDir.c_str(), strerror(errno));
456 return false;
457 }
458 if (TEMP_FAILURE_RETRY(mount(nullptr, targetDir.c_str(),
459 nullptr, MS_SLAVE | MS_REC, nullptr)) == -1) {
460 *error_msg = CREATE_ERROR("Failed to set MS_SLAVE for %s", targetDir.c_str());
461 return false;
462 }
463 return true;
464}
465
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700466static bool mountPkgSpecificDir(const std::string& mntSourceRoot,
467 const std::string& mntTargetRoot, const std::string& packageName,
468 const char* dirName, std::string* error_msg) {
469 std::string mntSourceDir = StringPrintf("%s/Android/%s/%s",
470 mntSourceRoot.c_str(), dirName, packageName.c_str());
471 std::string mntTargetDir = StringPrintf("%s/Android/%s/%s",
472 mntTargetRoot.c_str(), dirName, packageName.c_str());
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800473 return bindMount(mntSourceDir, mntTargetDir, error_msg);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700474}
475
476static bool preparePkgSpecificDirs(const std::vector<std::string>& packageNames,
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800477 const std::vector<std::string>& volumeLabels, bool mountAllObbs,
478 userid_t userId, std::string* error_msg) {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700479 for (auto& label : volumeLabels) {
480 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", label.c_str());
481 std::string mntTarget = StringPrintf("/storage/%s", label.c_str());
482 if (label == "emulated") {
483 StringAppendF(&mntSource, "/%d", userId);
484 StringAppendF(&mntTarget, "/%d", userId);
485 }
486 for (auto& package : packageNames) {
487 mountPkgSpecificDir(mntSource, mntTarget, package, "data", error_msg);
488 mountPkgSpecificDir(mntSource, mntTarget, package, "media", error_msg);
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800489 if (!mountAllObbs) {
490 mountPkgSpecificDir(mntSource, mntTarget, package, "obb", error_msg);
491 }
492 }
493 if (mountAllObbs) {
494 StringAppendF(&mntSource, "/Android/obb");
495 StringAppendF(&mntTarget, "/Android/obb");
496 bindMount(mntSource, mntTarget, error_msg);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700497 }
498 }
499 return true;
500}
501
Narayan Kamath973b4662014-03-31 13:41:26 +0100502// Create a private mount namespace and bind mount appropriate emulated
503// storage for the given user.
Jeff Sharkey9527b222015-06-24 15:24:48 -0700504static bool MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700505 bool force_mount_namespace, std::string* error_msg, const std::string& package_name,
506 const std::vector<std::string>& packages_for_uid,
507 const std::vector<std::string>& visible_vol_ids) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700508 // See storage config details at http://source.android.com/tech/storage/
509
Jeff Sharkey9527b222015-06-24 15:24:48 -0700510 String8 storageSource;
511 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700512 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700513 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700514 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700515 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700516 storageSource = "/mnt/runtime/write";
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800517 } else if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700518 // Sane default of no storage visible
519 return true;
520 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400521
522 // Create a second private mount namespace for our process
523 if (unshare(CLONE_NEWNS) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700524 *error_msg = CREATE_ERROR("Failed to unshare(): %s", strerror(errno));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400525 return false;
526 }
527
Robert Sesek06f39302017-03-20 17:30:05 -0400528 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
529 if (mount_mode == MOUNT_EXTERNAL_NONE) {
530 return true;
531 }
532
Sudheer Shanka663b1042018-07-30 17:34:21 -0700533 if (GetBoolProperty(kIsolatedStorage, false)) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700534 if (mount_mode == MOUNT_EXTERNAL_FULL) {
535 storageSource = "/mnt/runtime/write";
536 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
537 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
538 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
539 storageSource.string(),
540 strerror(errno));
541 return false;
542 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700543
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700544 // Mount user-specific symlink helper into place
545 userid_t user_id = multiuser_get_user_id(uid);
546 const String8 userSource(String8::format("/mnt/user/%d", user_id));
547 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
548 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
549 return false;
550 }
551 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
552 NULL, MS_BIND, NULL)) == -1) {
553 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
554 userSource.string(),
555 strerror(errno));
556 return false;
557 }
558 } else {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700559 if (package_name.empty()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700560 return true;
561 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700562 userid_t user_id = multiuser_get_user_id(uid);
563 std::string pkgSandboxDir = StringPrintf("/mnt/user/%d/package/%s",
564 user_id, package_name.c_str());
565 struct stat sb;
566 bool sandboxAlreadyCreated = true;
567 if (TEMP_FAILURE_RETRY(lstat(pkgSandboxDir.c_str(), &sb)) == -1) {
568 if (errno == ENOENT) {
569 ALOGD("Sandbox not yet created for %s", pkgSandboxDir.c_str());
570 sandboxAlreadyCreated = false;
571 if (!createPkgSandbox(uid, package_name, error_msg)) {
572 return false;
573 }
574 } else {
575 ALOGE("Failed to lstat %s", pkgSandboxDir.c_str());
576 return false;
577 }
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700578 }
579 if (TEMP_FAILURE_RETRY(mount(pkgSandboxDir.c_str(), "/storage",
580 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
581 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
582 pkgSandboxDir.c_str(), strerror(errno));
583 return false;
584 }
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800585 if (access("/storage/obb_mount", F_OK) == 0) {
586 if (mount_mode != MOUNT_EXTERNAL_INSTALLER) {
587 remove("/storage/obb_mount");
588 }
589 } else {
590 if (mount_mode == MOUNT_EXTERNAL_INSTALLER) {
591 int fd = TEMP_FAILURE_RETRY(open("/storage/obb_mount",
592 O_RDWR | O_CREAT, 0660));
593 if (fd == -1) {
594 *error_msg = CREATE_ERROR("Couldn't create /storage/obb_mount: %s",
595 strerror(errno));
596 return false;
597 }
598 close(fd);
599 }
600 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700601 // If the sandbox was already created by vold, only then set up the bind mounts for
602 // pkg specific directories. Otherwise, leave as is and bind mounts will be taken
603 // care of by vold later.
604 if (sandboxAlreadyCreated) {
605 if (!preparePkgSpecificDirs(packages_for_uid, visible_vol_ids,
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800606 mount_mode == MOUNT_EXTERNAL_INSTALLER, user_id, error_msg)) {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700607 return false;
608 }
609 }
Sudheer Shanka663b1042018-07-30 17:34:21 -0700610 }
611 } else {
612 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
613 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
614 *error_msg = CREATE_ERROR("Failed to mount %s to /storage: %s",
615 storageSource.string(),
616 strerror(errno));
617 return false;
618 }
619
620 // Mount user-specific symlink helper into place
621 userid_t user_id = multiuser_get_user_id(uid);
622 const String8 userSource(String8::format("/mnt/user/%d", user_id));
623 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
624 *error_msg = CREATE_ERROR("fs_prepare_dir failed on %s", userSource.string());
625 return false;
626 }
627 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
628 NULL, MS_BIND, NULL)) == -1) {
629 *error_msg = CREATE_ERROR("Failed to mount %s to /storage/self: %s",
630 userSource.string(),
631 strerror(errno));
632 return false;
633 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700634 }
635
Narayan Kamath973b4662014-03-31 13:41:26 +0100636 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100637}
638
Narayan Kamath973b4662014-03-31 13:41:26 +0100639static bool NeedsNoRandomizeWorkaround() {
640#if !defined(__arm__)
641 return false;
642#else
643 int major;
644 int minor;
645 struct utsname uts;
646 if (uname(&uts) == -1) {
647 return false;
648 }
649
650 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
651 return false;
652 }
653
654 // Kernels before 3.4.* need the workaround.
655 return (major < 3) || ((major == 3) && (minor < 4));
656#endif
657}
Narayan Kamath973b4662014-03-31 13:41:26 +0100658
659// Utility to close down the Zygote socket file descriptors while
660// the child is still running as root with Zygote's privileges. Each
661// descriptor (if any) is closed via dup2(), replacing it with a valid
662// (open) descriptor to /dev/null.
663
Andreas Gamped5758f62018-03-12 12:08:55 -0700664static bool DetachDescriptors(JNIEnv* env, jintArray fdsToClose, std::string* error_msg) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100665 if (!fdsToClose) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700666 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100667 }
668 jsize count = env->GetArrayLength(fdsToClose);
Mykola Kondratenko1ca062f2015-07-31 17:22:26 +0200669 ScopedIntArrayRO ar(env, fdsToClose);
670 if (ar.get() == NULL) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700671 *error_msg = "Bad fd array";
672 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100673 }
674 jsize i;
675 int devnull;
676 for (i = 0; i < count; i++) {
677 devnull = open("/dev/null", O_RDWR);
678 if (devnull < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700679 *error_msg = std::string("Failed to open /dev/null: ").append(strerror(errno));
680 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100681 }
Elliott Hughes960e8312014-09-30 08:49:01 -0700682 ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100683 if (dup2(devnull, ar[i]) < 0) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700684 *error_msg = StringPrintf("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
685 return false;
Narayan Kamath973b4662014-03-31 13:41:26 +0100686 }
687 close(devnull);
688 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700689 return true;
Narayan Kamath973b4662014-03-31 13:41:26 +0100690}
691
692void SetThreadName(const char* thread_name) {
693 bool hasAt = false;
694 bool hasDot = false;
695 const char* s = thread_name;
696 while (*s) {
697 if (*s == '.') {
698 hasDot = true;
699 } else if (*s == '@') {
700 hasAt = true;
701 }
702 s++;
703 }
704 const int len = s - thread_name;
705 if (len < 15 || hasAt || !hasDot) {
706 s = thread_name;
707 } else {
708 s = thread_name + len - 15;
709 }
710 // pthread_setname_np fails rather than truncating long strings.
711 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
712 strlcpy(buf, s, sizeof(buf)-1);
713 errno = pthread_setname_np(pthread_self(), buf);
714 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700715 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100716 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800717 // Update base::logging default tag.
718 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100719}
720
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100721// The list of open zygote file descriptors.
722static FileDescriptorTable* gOpenFdTable = NULL;
723
Andreas Gamped5758f62018-03-12 12:08:55 -0700724static bool FillFileDescriptorVector(JNIEnv* env,
Chris Wailesaf594fc2018-11-02 11:00:07 -0700725 jintArray managed_fds,
Andreas Gamped5758f62018-03-12 12:08:55 -0700726 std::vector<int>* fds,
727 std::string* error_msg) {
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800728 CHECK(fds != nullptr);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700729 if (managed_fds != nullptr) {
730 ScopedIntArrayRO ar(env, managed_fds);
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800731 if (ar.get() == nullptr) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700732 *error_msg = "Bad fd array";
733 return false;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800734 }
735 fds->reserve(ar.size());
736 for (size_t i = 0; i < ar.size(); ++i) {
737 fds->push_back(ar[i]);
738 }
739 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700740 return true;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800741}
742
Chris Wailesaf594fc2018-11-02 11:00:07 -0700743[[noreturn]]
744static void ZygoteFailure(JNIEnv* env,
745 const char* process_name,
746 jstring managed_process_name,
747 const std::string& msg) {
748 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
749 if (managed_process_name != nullptr) {
750 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
751 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
752 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -0700753 }
754 }
755
Chris Wailesaf594fc2018-11-02 11:00:07 -0700756 const std::string& error_msg =
757 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700758
Chris Wailesaf594fc2018-11-02 11:00:07 -0700759 env->FatalError(error_msg.c_str());
760 __builtin_unreachable();
761}
David Sehrde8d0bd2018-06-22 10:45:36 -0700762
Chris Wailesaf594fc2018-11-02 11:00:07 -0700763static std::optional<std::string> ExtractJString(JNIEnv* env,
764 const char* process_name,
765 jstring managed_process_name,
766 jstring managed_string) {
767 if (managed_string == nullptr) {
768 return std::optional<std::string>();
769 } else {
770 ScopedUtfChars scoped_string_chars(env, managed_string);
771
772 if (scoped_string_chars.c_str() != nullptr) {
773 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700774 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -0700775 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700776 }
777 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700778}
779
Chris Wailesaf594fc2018-11-02 11:00:07 -0700780// Utility routine to fork a zygote.
781static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
782 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore) {
yuanhao435e84b2018-01-15 15:37:02 +0800783 SetSignalHandlers();
Narayan Kamath973b4662014-03-31 13:41:26 +0100784
David Sehrde8d0bd2018-06-22 10:45:36 -0700785 // Block SIGCHLD prior to fork.
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000786 sigset_t sigchld;
787 sigemptyset(&sigchld);
788 sigaddset(&sigchld, SIGCHLD);
789
Chris Wailesaf594fc2018-11-02 11:00:07 -0700790 // Curry a failure function.
791 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
792 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -0700793
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000794 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
795 // log, which would result in the logging FDs we close being reopened.
796 // This would cause failures because the FDs are not whitelisted.
797 //
798 // Note that the zygote process is single threaded at this point.
799 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700800 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000801 }
802
Narayan Kamath3764a262016-08-30 15:36:19 +0100803 // Close any logging related FDs before we start evaluating the list of
804 // file descriptors.
805 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -0700806 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +0100807
Chris Wailesaf594fc2018-11-02 11:00:07 -0700808 // If this is the first fork for this zygote, create the open FD table. If
809 // it isn't, we just need to check whether the list of open files has changed
810 // (and it shouldn't in the normal case).
Andreas Gamped5758f62018-03-12 12:08:55 -0700811 std::string error_msg;
Andreas Gampe8dfa1782017-01-05 12:45:58 -0800812 std::vector<int> fds_to_ignore;
Chris Wailesaf594fc2018-11-02 11:00:07 -0700813 if (!FillFileDescriptorVector(env, managed_fds_to_ignore, &fds_to_ignore, &error_msg)) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700814 fail_fn(error_msg);
815 }
Chris Wailesaf594fc2018-11-02 11:00:07 -0700816
817 if (gOpenFdTable == nullptr) {
Andreas Gampec362a442018-03-12 14:53:34 -0700818 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, &error_msg);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700819 if (gOpenFdTable == nullptr) {
Andreas Gampec362a442018-03-12 14:53:34 -0700820 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100821 }
Andreas Gampec362a442018-03-12 14:53:34 -0700822 } else if (!gOpenFdTable->Restat(fds_to_ignore, &error_msg)) {
823 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100824 }
825
Josh Gaod7951102018-06-26 16:05:12 -0700826 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
827
Narayan Kamath973b4662014-03-31 13:41:26 +0100828 pid_t pid = fork();
829
830 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700831 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700832 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700833
Narayan Kamath973b4662014-03-31 13:41:26 +0100834 // Clean up any descriptors which must be closed immediately
Chris Wailesaf594fc2018-11-02 11:00:07 -0700835 if (!DetachDescriptors(env, managed_fds_to_close, &error_msg)) {
Andreas Gamped5758f62018-03-12 12:08:55 -0700836 fail_fn(error_msg);
837 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100838
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100839 // Re-open all remaining open file descriptors so that they aren't shared
840 // with the zygote across a fork.
Andreas Gampec362a442018-03-12 14:53:34 -0700841 if (!gOpenFdTable->ReopenOrDetach(&error_msg)) {
842 fail_fn(error_msg);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100843 }
Josh Gaod7951102018-06-26 16:05:12 -0700844
845 // Turn fdsan back on.
846 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -0700847 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100848
David Sehrde8d0bd2018-06-22 10:45:36 -0700849 // We blocked SIGCHLD prior to a fork, we unblock it here.
850 if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
851 fail_fn(CREATE_ERROR("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100852 }
Chris Wailesaf594fc2018-11-02 11:00:07 -0700853
Narayan Kamath973b4662014-03-31 13:41:26 +0100854 return pid;
855}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700856
Chris Wailesaf594fc2018-11-02 11:00:07 -0700857// Utility routine to specialize a zygote child process.
858static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
859 jint runtime_flags, jobjectArray rlimits,
860 jlong permitted_capabilities, jlong effective_capabilities,
861 jint mount_external, jstring managed_se_info,
862 jstring managed_nice_name, bool is_system_server,
863 bool is_child_zygote, jstring managed_instruction_set,
864 jstring managed_app_data_dir, jstring managed_package_name,
865 jobjectArray managed_pacakges_for_uid,
866 jobjectArray managed_visible_vol_ids) {
867 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
868 managed_nice_name, _1);
869 auto extract_fn = std::bind(ExtractJString, env, is_system_server ? "system_server" : "zygote",
870 managed_nice_name, _1);
871
872 auto se_info = extract_fn(managed_se_info);
873 auto nice_name = extract_fn(managed_nice_name);
874 auto instruction_set = extract_fn(managed_instruction_set);
875 auto app_data_dir = extract_fn(managed_app_data_dir);
876 auto package_name = extract_fn(managed_package_name);
877
878 std::string error_msg;
879
880 // Keep capabilities across UID change, unless we're staying root.
881 if (uid != 0) {
882 if (!EnableKeepCapabilities(&error_msg)) {
883 fail_fn(error_msg);
884 }
885 }
886
887 if (!SetInheritable(permitted_capabilities, &error_msg)) {
888 fail_fn(error_msg);
889 }
890
891 if (!DropCapabilitiesBoundingSet(&error_msg)) {
892 fail_fn(error_msg);
893 }
894
895 bool use_native_bridge = !is_system_server &&
896 instruction_set.has_value() &&
897 android::NativeBridgeAvailable() &&
898 android::NeedsNativeBridge(instruction_set.value().c_str());
899
900 if (use_native_bridge && !app_data_dir.has_value()) {
901 // The app_data_dir variable should never be empty if we need to use a
902 // native bridge. In general, app_data_dir will never be empty for normal
903 // applications. It can only happen in special cases (for isolated
904 // processes which are not associated with any app). These are launched by
905 // the framework and should not be emulated anyway.
906 use_native_bridge = false;
907 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
908 }
909
910 if (!package_name.has_value()) {
911 if (is_system_server) {
912 package_name.emplace("android");
913 } else {
914 package_name.emplace("");
915 }
916 }
917
918 std::vector<std::string> packages_for_uid;
919 if (managed_pacakges_for_uid != nullptr) {
920 jsize count = env->GetArrayLength(managed_pacakges_for_uid);
921 for (jsize package_index = 0; package_index < count; ++package_index) {
922 jstring managed_package_for_uid =
923 (jstring) env->GetObjectArrayElement(managed_pacakges_for_uid, package_index);
924
925 auto package_for_uid = extract_fn(managed_package_for_uid);
926 if (LIKELY(package_for_uid.has_value())) {
927 packages_for_uid.emplace_back(std::move(package_for_uid.value()));
928 } else {
929 fail_fn("Null string found in managed packages_for_uid.");
930 }
931 }
932 }
933
934 std::vector<std::string> visible_vol_ids;
935 if (managed_visible_vol_ids != nullptr) {
936 jsize count = env->GetArrayLength(managed_visible_vol_ids);
937 for (jsize vol_id_index = 0; vol_id_index < count; ++vol_id_index) {
938 jstring managed_visible_vol_id =
939 (jstring) env->GetObjectArrayElement(managed_visible_vol_ids, vol_id_index);
940
941 auto visible_vol_id = extract_fn(managed_visible_vol_id);
942 if (LIKELY(visible_vol_id.has_value())) {
943 visible_vol_ids.emplace_back(std::move(visible_vol_id.value()));
944 } else {
945 fail_fn("Null string found in managed visible_vol_ids.");
946 }
947 }
948 }
949
950 if (!MountEmulatedStorage(uid, mount_external, use_native_bridge, &error_msg,
951 package_name.value(), packages_for_uid, visible_vol_ids)) {
952 ALOGW("Failed to mount emulated storage: %s (%s)", error_msg.c_str(), strerror(errno));
953 if (errno == ENOTCONN || errno == EROFS) {
954 // When device is actively encrypting, we get ENOTCONN here
955 // since FUSE was mounted before the framework restarted.
956 // When encrypted device is booting, we get EROFS since
957 // FUSE hasn't been created yet by init.
958 // In either case, continue without external storage.
959 } else {
960 fail_fn(error_msg);
961 }
962 }
963
964 // If this zygote isn't root, it won't be able to create a process group,
965 // since the directory is owned by root.
966 if (!is_system_server && getuid() == 0) {
967 int rc = createProcessGroup(uid, getpid());
968 if (rc == -EROFS) {
969 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
970 } else if (rc != 0) {
971 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
972 }
973 }
974
975 if (!SetGids(env, gids, &error_msg)) {
976 fail_fn(error_msg);
977 }
978
979 if (!SetRLimits(env, rlimits, &error_msg)) {
980 fail_fn(error_msg);
981 }
982
983 if (use_native_bridge) {
984 // Due to the logic behind use_native_bridge we know that both app_data_dir
985 // and instruction_set contain values.
986 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
987 instruction_set.value().c_str());
988 }
989
990 if (setresgid(gid, gid, gid) == -1) {
991 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
992 }
993
994 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
995 // before changing uid from 0, which clears capabilities. The other
996 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
997 // breaks SELinux domain transition (see b/71859146). As the result,
998 // privileged syscalls used below still need to be accessible in app process.
999 SetUpSeccompFilter(uid);
1000
1001 if (setresuid(uid, uid, uid) == -1) {
1002 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1003 }
1004
1005 // The "dumpable" flag of a process, which controls core dump generation, is
1006 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1007 // user or group ID changes. See proc(5) for possible values. In most cases,
1008 // the value is 0, so core dumps are disabled for zygote children. However,
1009 // when running in a Chrome OS container, the value is already set to 2,
1010 // which allows the external crash reporter to collect all core dumps. Since
1011 // only system crashes are interested, core dump is disabled for app
1012 // processes. This also ensures compliance with CTS.
1013 int dumpable = prctl(PR_GET_DUMPABLE);
1014 if (dumpable == -1) {
1015 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1016 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1017 }
1018
1019 if (dumpable == 2 && uid >= AID_APP) {
1020 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1021 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1022 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1023 }
1024 }
1025
Orion Hodson8d005a62018-12-05 12:28:53 +00001026 // Set process properties to enable debugging if required.
1027 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1028 EnableDebugger();
1029 }
1030
Chris Wailesaf594fc2018-11-02 11:00:07 -07001031 if (NeedsNoRandomizeWorkaround()) {
1032 // Work around ARM kernel ASLR lossage (http://b/5817320).
1033 int old_personality = personality(0xffffffff);
1034 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1035 if (new_personality == -1) {
1036 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1037 }
1038 }
1039
1040 if (!SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities,
1041 &error_msg)) {
1042 fail_fn(error_msg);
1043 }
1044
1045 if (!SetSchedulerPolicy(&error_msg)) {
1046 fail_fn(error_msg);
1047 }
1048
1049 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1050 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1051
1052 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1053 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1054 uid, is_system_server, se_info_ptr, nice_name_ptr));
1055 }
1056
1057 // Make it easier to debug audit logs by setting the main thread's name to the
1058 // nice name rather than "app_process".
1059 if (nice_name.has_value()) {
1060 SetThreadName(nice_name.value().c_str());
1061 } else if (is_system_server) {
1062 SetThreadName("system_server");
1063 }
1064
1065 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1066 UnsetChldSignalHandler();
1067
1068 if (is_system_server) {
1069 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1070 if (env->ExceptionCheck()) {
1071 fail_fn("Error calling post fork system server hooks.");
1072 }
1073 // TODO(oth): Remove hardcoded label here (b/117874058).
1074 static const char* kSystemServerLabel = "u:r:system_server:s0";
1075 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1076 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1077 }
1078 }
1079
1080 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1081 is_system_server, is_child_zygote, managed_instruction_set);
1082
1083 if (env->ExceptionCheck()) {
1084 fail_fn("Error calling post fork hooks.");
1085 }
1086}
1087
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001088static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1089 __user_cap_header_struct capheader;
1090 memset(&capheader, 0, sizeof(capheader));
1091 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1092 capheader.pid = 0;
1093
1094 __user_cap_data_struct capdata[2];
1095 if (capget(&capheader, &capdata[0]) == -1) {
1096 ALOGE("capget failed: %s", strerror(errno));
1097 RuntimeAbort(env, __LINE__, "capget failed");
1098 }
1099
Chris Wailesaf594fc2018-11-02 11:00:07 -07001100 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1101}
1102
1103static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1104 bool is_child_zygote) {
1105 jlong capabilities = 0;
1106
1107 /*
1108 * Grant the following capabilities to the Bluetooth user:
1109 * - CAP_WAKE_ALARM
1110 * - CAP_NET_RAW
1111 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1112 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1113 */
1114
1115 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1116 capabilities |= (1LL << CAP_WAKE_ALARM);
1117 capabilities |= (1LL << CAP_NET_RAW);
1118 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1119 capabilities |= (1LL << CAP_SYS_NICE);
1120 }
1121
1122 /*
1123 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1124 */
1125
1126 bool gid_wakelock_found = false;
1127 if (gid == AID_WAKELOCK) {
1128 gid_wakelock_found = true;
1129 } else if (gids != nullptr) {
1130 jsize gids_num = env->GetArrayLength(gids);
1131 ScopedIntArrayRO native_gid_proxy(env, gids);
1132
1133 if (native_gid_proxy.get() == nullptr) {
1134 RuntimeAbort(env, __LINE__, "Bad gids array");
1135 }
1136
1137 for (int gid_index = gids_num; --gids_num >= 0;) {
1138 if (native_gid_proxy[gid_index] == AID_WAKELOCK) {
1139 gid_wakelock_found = true;
1140 break;
1141 }
1142 }
1143 }
1144
1145 if (gid_wakelock_found) {
1146 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1147 }
1148
1149 /*
1150 * Grant child Zygote processes the following capabilities:
1151 * - CAP_SETUID (change UID of child processes)
1152 * - CAP_SETGID (change GID of child processes)
1153 * - CAP_SETPCAP (change capabilities of child processes)
1154 */
1155
1156 if (is_child_zygote) {
1157 capabilities |= (1LL << CAP_SETUID);
1158 capabilities |= (1LL << CAP_SETGID);
1159 capabilities |= (1LL << CAP_SETPCAP);
1160 }
1161
1162 /*
1163 * Containers run without some capabilities, so drop any caps that are not
1164 * available.
1165 */
1166
1167 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001168}
Narayan Kamath973b4662014-03-31 13:41:26 +01001169} // anonymous namespace
1170
1171namespace android {
1172
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001173static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001174 // security_getenforce is not allowed on app process. Initialize and cache
1175 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001176 g_is_security_enforced = security_getenforce();
1177}
1178
Christopher Ferris76de39e2017-06-20 16:13:40 -07001179static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1180 PreApplicationInit();
1181}
1182
Narayan Kamath973b4662014-03-31 13:41:26 +01001183static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1184 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001185 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001186 jint mount_external, jstring se_info, jstring nice_name,
1187 jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote,
1188 jstring instruction_set, jstring app_data_dir, jstring package_name,
1189 jobjectArray packages_for_uid, jobjectArray visible_vol_ids) {
1190 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001191
Chris Wailesaf594fc2018-11-02 11:00:07 -07001192 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001193 if (pid == 0) {
1194 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1195 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001196 mount_external, se_info, nice_name, false,
1197 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
1198 package_name, packages_for_uid, visible_vol_ids);
David Sehrde8d0bd2018-06-22 10:45:36 -07001199 }
1200 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001201}
1202
1203static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1204 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001205 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1206 jlong effective_capabilities) {
1207 pid_t pid = ForkCommon(env, true,
1208 /* managed_fds_to_close= */ nullptr,
1209 /* managed_fds_to_ignore= */ nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001210 if (pid == 0) {
1211 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001212 permitted_capabilities, effective_capabilities,
1213 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1214 false, nullptr, nullptr, nullptr, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001215 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001216 // The zygote process checks whether the child process has died or not.
1217 ALOGI("System server process %d has been created", pid);
1218 gSystemServerPid = pid;
1219 // There is a slight window that the system server process has crashed
1220 // but it went unnoticed because we haven't published its pid yet. So
1221 // we recheck here just to make sure that all is well.
1222 int status;
1223 if (waitpid(pid, &status, WNOHANG) == pid) {
1224 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001225 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001226 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001227
Minchan Kim5fa8af22018-06-27 11:32:40 +09001228 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
1229 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
1230 if (per_app_memcg) {
1231 // Assign system_server to the correct memory cgroup.
1232 // Not all devices mount /dev/memcg so check for the file first
1233 // to avoid unnecessarily printing errors and denials in the logs.
1234 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -08001235 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001236 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
1237 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001238 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001239 }
1240 return pid;
1241}
1242
Robert Sesek54e387d2016-12-02 17:27:50 -05001243static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1244 JNIEnv* env, jclass, jstring path) {
1245 ScopedUtfChars path_native(env, path);
1246 const char* path_cstr = path_native.c_str();
1247 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001248 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001249 }
1250 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1251}
1252
doheon1.lee885b7422016-01-20 13:07:27 +09001253static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1254 // Zygote process unmount root storage space initially before every child processes are forked.
1255 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001256 // and no need unmount storage operation in MountEmulatedStorage method.
1257 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1258
1259 // See storage config details at http://source.android.com/tech/storage/
1260 // Create private mount namespace shared by all children
1261 if (unshare(CLONE_NEWNS) == -1) {
1262 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1263 return;
1264 }
1265
1266 // Mark rootfs as being a slave so that changes from default
1267 // namespace only flow into our children.
1268 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1269 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1270 return;
1271 }
1272
1273 // Create a staging tmpfs that is shared by our children; they will
1274 // bind mount storage into their respective private namespaces, which
1275 // are isolated from each other.
1276 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1277 if (target_base != nullptr) {
1278#define STRINGIFY_UID(x) __STRING(x)
1279 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1280 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1281 ALOGE("Failed to mount tmpfs to %s", target_base);
1282 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1283 return;
1284 }
1285#undef STRINGIFY_UID
1286 }
doheon1.lee885b7422016-01-20 13:07:27 +09001287
1288 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001289}
1290
Daniel Micay76f6a862015-09-19 17:31:01 -04001291static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001292 { "nativeSecurityInit", "()V",
1293 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001294 { "nativeForkAndSpecialize",
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001295 "(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 +01001296 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1297 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001298 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001299 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1300 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001301 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001302 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1303 { "nativePreApplicationInit", "()V",
1304 (void *) com_android_internal_os_Zygote_nativePreApplicationInit }
Narayan Kamath973b4662014-03-31 13:41:26 +01001305};
1306
1307int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001308 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001309 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1310 "callPostForkSystemServerHooks",
1311 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001312 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001313 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001314
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001315 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001316}
1317} // namespace android