blob: 4649b52627238eed3eb2b2832195da9d728e7048 [file] [log] [blame]
Narayan Kamath973b4662014-03-31 13:41:26 +01001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Chris Waileseac7f4e2019-01-17 14:57:10 -080017/*
18 * Disable optimization of this file if we are compiling with the address
19 * sanitizer. This is a mitigation for b/122921367 and can be removed once the
20 * bug is fixed.
21 */
22#if __has_feature(address_sanitizer)
23#pragma clang optimize off
24#endif
25
Colin Cross18cd9f52014-06-13 12:58:55 -070026#define LOG_TAG "Zygote"
Narayan Kamath973b4662014-03-31 13:41:26 +010027
wangmingming16d0dd1a2018-11-14 10:43:36 +080028#include <async_safe/log.h>
29
Narayan Kamath973b4662014-03-31 13:41:26 +010030// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
31#include <sys/mount.h>
32#include <linux/fs.h>
33
Chris Wailesaa1c9622019-01-10 16:55:32 -080034#include <array>
35#include <atomic>
Chris Wailesaf594fc2018-11-02 11:00:07 -070036#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070037#include <list>
Chris Wailesaf594fc2018-11-02 11:00:07 -070038#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080039#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070040#include <string>
Chris Wailesaa1c9622019-01-10 16:55:32 -080041#include <string_view>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070042
Josh Gaod7951102018-06-26 16:05:12 -070043#include <android/fdsan.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080044#include <arpa/inet.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070045#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080046#include <grp.h>
47#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070048#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070049#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010050#include <paths.h>
51#include <signal.h>
52#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070053#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040054#include <sys/cdefs.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080055#include <sys/eventfd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070056#include <sys/personality.h>
57#include <sys/prctl.h>
58#include <sys/resource.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080059#include <sys/socket.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070060#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070061#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070062#include <sys/types.h>
63#include <sys/utsname.h>
64#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080065#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070066
Chris Wailesaa1c9622019-01-10 16:55:32 -080067#include <android-base/logging.h>
Minchan Kim5fa8af22018-06-27 11:32:40 +090068#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080069#include <android-base/file.h>
70#include <android-base/stringprintf.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080071#include <android-base/unique_fd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070072#include <cutils/fs.h>
73#include <cutils/multiuser.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070074#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070075#include <utils/String8.h>
76#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080077#include <seccomp_policy.h>
Howard Ro27330412018-10-02 12:08:28 -070078#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070079#include <processgroup/processgroup.h>
Suren Baghdasaryane4433262019-01-04 12:16:57 -080080#include <processgroup/sched_policy.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070081
Andreas Gampeed6b9df2014-11-20 22:02:20 -080082#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070083#include <nativehelper/JNIHelp.h>
84#include <nativehelper/ScopedLocalRef.h>
85#include <nativehelper/ScopedPrimitiveArray.h>
86#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050087#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010088
jgu212eacd062014-09-10 06:55:07 -040089#include "nativebridge/native_bridge.h"
90
Narayan Kamath973b4662014-03-31 13:41:26 +010091namespace {
92
Chris Wailesaa1c9622019-01-10 16:55:32 -080093// TODO (chriswailes): Add a function to initialize native Zygote data.
94// TODO (chriswailes): Fix mixed indentation style (2 and 4 spaces).
95
Chris Wailesaf594fc2018-11-02 11:00:07 -070096using namespace std::placeholders;
97
Narayan Kamath973b4662014-03-31 13:41:26 +010098using android::String8;
Sudheer Shanka663b1042018-07-30 17:34:21 -070099using android::base::StringAppendF;
Carmen Jacksondd401252017-02-23 15:21:10 -0800100using android::base::StringPrintf;
101using android::base::WriteStringToFile;
Minchan Kim5fa8af22018-06-27 11:32:40 +0900102using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +0100103
Andreas Gamped5758f62018-03-12 12:08:55 -0700104#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
105 append(StringPrintf(__VA_ARGS__))
106
Chris Wailesaa1c9622019-01-10 16:55:32 -0800107// This type is duplicated in fd_utils.h
108typedef const std::function<void(std::string)>& fail_fn_t;
109
Narayan Kamath973b4662014-03-31 13:41:26 +0100110static pid_t gSystemServerPid = 0;
111
Sudheer Shanka663b1042018-07-30 17:34:21 -0700112static const char kIsolatedStorage[] = "persist.sys.isolated_storage";
Sudheer Shankaa3801582019-01-17 17:19:11 -0800113static const char kIsolatedStorageSnapshot[] = "sys.isolated_storage_snapshot";
Narayan Kamath973b4662014-03-31 13:41:26 +0100114static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
115static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +0100116static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +0100117static jmethodID gCallPostForkChildHooks;
118
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800119static bool g_is_security_enforced = true;
120
Chris Wailesaa1c9622019-01-10 16:55:32 -0800121/**
122 * The maximum number of characters (not including a null terminator) that a
123 * process name may contain.
124 */
125static constexpr size_t MAX_NAME_LENGTH = 15;
126
127/**
128 * The prefix string for environmental variables storing socket FDs created by
129 * init.
130 */
131
132static constexpr std::string_view ANDROID_SOCKET_PREFIX("ANDROID_SOCKET_");
133
134/**
135 * The file descriptor for the Zygote socket opened by init.
136 */
137
138static int gZygoteSocketFD = -1;
139
140/**
141 * The file descriptor for the Blastula pool socket opened by init.
142 */
143
144static int gBlastulaPoolSocketFD = -1;
145
146/**
147 * The number of Blastulas currently in this Zygote's pool.
148 */
149static std::atomic_uint32_t gBlastulaPoolCount = 0;
150
151/**
152 * Event file descriptor used to communicate reaped blastulas to the
153 * ZygoteServer.
154 */
155static int gBlastulaPoolEventFD = -1;
156
157/**
158 * The maximum value that the gBlastulaPoolMax variable may take. This value
159 * is a mirror of Zygote.BLASTULA_POOL_MAX_LIMIT
160 */
161static constexpr int BLASTULA_POOL_MAX_LIMIT = 10;
162
163/**
164 * A helper class containing accounting information for Blastulas.
165 */
166class BlastulaTableEntry {
167 public:
168 struct EntryStorage {
169 int32_t pid;
170 int32_t read_pipe_fd;
171
172 bool operator!=(const EntryStorage& other) {
173 return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
174 }
175 };
176
177 private:
178 static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
179
180 std::atomic<EntryStorage> mStorage;
181 static_assert(decltype(mStorage)::is_always_lock_free);
182
183 public:
184 constexpr BlastulaTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
185
186 /**
187 * If the provided PID matches the one stored in this entry, the entry will
188 * be invalidated and the associated file descriptor will be closed. If the
189 * PIDs don't match nothing will happen.
190 *
191 * @param pid The ID of the process who's entry we want to clear.
192 * @return True if the entry was cleared; false otherwise
193 */
194 bool ClearForPID(int32_t pid) {
195 EntryStorage storage = mStorage.load();
196
197 if (storage.pid == pid) {
198 /*
199 * There are three possible outcomes from this compare-and-exchange:
200 * 1) It succeeds, in which case we close the FD
201 * 2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
202 * the entry has already been cleared.
203 * 3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
204 * case the entry has already been cleared and re-used.
205 *
206 * In all three cases the goal of the caller has been met and we can
207 * return true.
208 */
209 if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
210 close(storage.read_pipe_fd);
211 }
212
213 return true;
214 } else {
215 return false;
216 }
217 }
218
219 /**
220 * @return A copy of the data stored in this entry.
221 */
222 std::optional<EntryStorage> GetValues() {
223 EntryStorage storage = mStorage.load();
224
225 if (storage != INVALID_ENTRY_VALUE) {
226 return storage;
227 } else {
228 return std::nullopt;
229 }
230 }
231
232 /**
233 * Sets the entry to the given values if it is currently invalid.
234 *
235 * @param pid The process ID for the new entry.
236 * @param read_pipe_fd The read end of the blastula control pipe for this
237 * process.
238 * @return True if the entry was set; false otherwise.
239 */
240 bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
241 EntryStorage new_value_storage;
242
243 new_value_storage.pid = pid;
244 new_value_storage.read_pipe_fd = read_pipe_fd;
245
246 EntryStorage expected = INVALID_ENTRY_VALUE;
247
248 return mStorage.compare_exchange_strong(expected, new_value_storage);
249 }
250};
251
252/**
253 * A table containing information about the Blastulas currently in the pool.
254 *
255 * Multiple threads may be attempting to modify the table, either from the
256 * signal handler or from the ZygoteServer poll loop. Atomic loads/stores in
257 * the BlastulaTableEntry class prevent data races during these concurrent
258 * operations.
259 */
260static std::array<BlastulaTableEntry, BLASTULA_POOL_MAX_LIMIT> gBlastulaTable;
261
262/**
263 * The list of open zygote file descriptors.
264 */
265static FileDescriptorTable* gOpenFdTable = nullptr;
266
Narayan Kamath973b4662014-03-31 13:41:26 +0100267// Must match values in com.android.internal.os.Zygote.
268enum MountExternalKind {
269 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700270 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700271 MOUNT_EXTERNAL_READ = 2,
272 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800273 MOUNT_EXTERNAL_LEGACY = 4,
274 MOUNT_EXTERNAL_INSTALLER = 5,
275 MOUNT_EXTERNAL_FULL = 6,
Narayan Kamath973b4662014-03-31 13:41:26 +0100276};
277
Orion Hodson8d005a62018-12-05 12:28:53 +0000278// Must match values in com.android.internal.os.Zygote.
279enum RuntimeFlags : uint32_t {
280 DEBUG_ENABLE_JDWP = 1,
Yabin Cui4d8546d2019-01-29 16:29:20 -0800281 PROFILE_FROM_SHELL = 1 << 15,
Orion Hodson8d005a62018-12-05 12:28:53 +0000282};
283
Chris Wailesaa1c9622019-01-10 16:55:32 -0800284// Forward declaration so we don't have to move the signal handler.
285static bool RemoveBlastulaTableEntry(pid_t blastula_pid);
286
Andreas Gampeb053cce2015-11-17 16:38:59 -0800287static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
288 std::ostringstream oss;
289 oss << __FILE__ << ":" << line << ": " << msg;
290 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100291}
292
293// This signal handler is for zygote mode, since the zygote must reap its children
294static void SigChldHandler(int /*signal_number*/) {
295 pid_t pid;
296 int status;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800297 int64_t blastulas_removed = 0;
Narayan Kamath973b4662014-03-31 13:41:26 +0100298
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700299 // It's necessary to save and restore the errno during this function.
300 // Since errno is stored per thread, changing it here modifies the errno
301 // on the thread on which this signal handler executes. If a signal occurs
302 // between a call and an errno check, it's possible to get the errno set
303 // here.
304 // See b/23572286 for extra information.
305 int saved_errno = errno;
306
Narayan Kamath973b4662014-03-31 13:41:26 +0100307 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800308 // Log process-death status that we care about.
Narayan Kamath973b4662014-03-31 13:41:26 +0100309 if (WIFEXITED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800310 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
311 "Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100312 } else if (WIFSIGNALED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800313 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
314 "Process %d exited due to signal %d (%s)%s", pid,
315 WTERMSIG(status), strsignal(WTERMSIG(status)),
316 WCOREDUMP(status) ? "; core dumped" : "");
Narayan Kamath973b4662014-03-31 13:41:26 +0100317 }
318
319 // If the just-crashed process is the system_server, bring down zygote
320 // so that it is restarted by init and system server will be restarted
321 // from there.
322 if (pid == gSystemServerPid) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800323 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
324 "Exit zygote because system server (pid %d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100325 kill(getpid(), SIGKILL);
326 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800327
328 // Check to see if the PID is in the blastula pool and remove it if it is.
329 if (RemoveBlastulaTableEntry(pid)) {
330 ++blastulas_removed;
331 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100332 }
333
Narayan Kamath160992d2014-04-14 14:46:07 +0100334 // Note that we shouldn't consider ECHILD an error because
335 // the secondary zygote might have no children left to wait for.
336 if (pid < 0 && errno != ECHILD) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800337 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG,
338 "Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100339 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700340
Chris Wailesaa1c9622019-01-10 16:55:32 -0800341 if (blastulas_removed > 0) {
342 if (write(gBlastulaPoolEventFD, &blastulas_removed, sizeof(blastulas_removed)) == -1) {
343 // If this write fails something went terribly wrong. We will now kill
344 // the zygote and let the system bring it back up.
wangmingming16d0dd1a2018-11-14 10:43:36 +0800345 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
346 "Zygote failed to write to blastula pool event FD: %s",
347 strerror(errno));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800348 kill(getpid(), SIGKILL);
349 }
350 }
351
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700352 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100353}
354
yuanhao435e84b2018-01-15 15:37:02 +0800355// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
356// configured very late, because earlier in the runtime we may fork() and
357// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100358// have them be harvested immediately.
359//
yuanhao435e84b2018-01-15 15:37:02 +0800360// Ignore SIGHUP because all processes forked by the zygote are in the same
361// process group as the zygote and we don't want to be notified if we become
362// an orphaned group and have one or more stopped processes. This is not a
363// theoretical concern :
364// - we can become an orphaned group if one of our direct descendants forks
365// and is subsequently killed before its children.
366// - crash_dump routinely STOPs the process it's tracing.
367//
368// See issues b/71965619 and b/25567761 for further details.
369//
Narayan Kamath973b4662014-03-31 13:41:26 +0100370// This ends up being called repeatedly before each fork(), but there's
371// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800372static void SetSignalHandlers() {
373 struct sigaction sig_chld = {};
374 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100375
Chris Wailesaa1c9622019-01-10 16:55:32 -0800376 if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700377 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100378 }
yuanhao435e84b2018-01-15 15:37:02 +0800379
380 struct sigaction sig_hup = {};
381 sig_hup.sa_handler = SIG_IGN;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800382 if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
yuanhao435e84b2018-01-15 15:37:02 +0800383 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
384 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100385}
386
387// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800388static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100389 struct sigaction sa;
390 memset(&sa, 0, sizeof(sa));
391 sa.sa_handler = SIG_DFL;
392
Chris Wailesaa1c9622019-01-10 16:55:32 -0800393 if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700394 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100395 }
396}
397
398// Calls POSIX setgroups() using the int[] object as an argument.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800399// A nullptr argument is tolerated.
400static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) {
401 if (managed_gids == nullptr) {
402 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100403 }
404
Chris Wailesaa1c9622019-01-10 16:55:32 -0800405 ScopedIntArrayRO gids(env, managed_gids);
406 if (gids.get() == nullptr) {
407 fail_fn(CREATE_ERROR("Getting gids int array failed"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100408 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700409
Chris Wailesaa1c9622019-01-10 16:55:32 -0800410 if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
411 fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
412 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100413}
414
415// Sets the resource limits via setrlimit(2) for the values in the
416// two-dimensional array of integers that's passed in. The second dimension
Chris Wailesaa1c9622019-01-10 16:55:32 -0800417// contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
Narayan Kamath973b4662014-03-31 13:41:26 +0100418// treated as an empty array.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800419static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
420 if (managed_rlimits == nullptr) {
421 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100422 }
423
424 rlimit rlim;
425 memset(&rlim, 0, sizeof(rlim));
426
Chris Wailesaa1c9622019-01-10 16:55:32 -0800427 for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
428 ScopedLocalRef<jobject>
429 managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
430 ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
431
432 if (rlimit_handle.size() != 3) {
433 fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100434 }
435
Chris Wailesaa1c9622019-01-10 16:55:32 -0800436 rlim.rlim_cur = rlimit_handle[1];
437 rlim.rlim_max = rlimit_handle[2];
Narayan Kamath973b4662014-03-31 13:41:26 +0100438
Chris Wailesaa1c9622019-01-10 16:55:32 -0800439 if (setrlimit(rlimit_handle[0], &rlim) == -1) {
440 fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
441 rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
Narayan Kamath973b4662014-03-31 13:41:26 +0100442 }
443 }
444}
445
Orion Hodson8d005a62018-12-05 12:28:53 +0000446static void EnableDebugger() {
447 // To let a non-privileged gdbserver attach to this
448 // process, we must set our dumpable flag.
449 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
450 ALOGE("prctl(PR_SET_DUMPABLE) failed");
451 }
452
453 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
454 // is enabled (see kernel/Documentation/security/Yama.txt).
455 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
456 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
457 // case since it's expected behaviour.
458 if (errno != EINVAL) {
459 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
460 }
461 }
462
Orion Hodson2b71ad02018-12-07 16:44:33 +0000463 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
464 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
465 // Set the soft limit on core dump size to 0 without changing the hard limit.
466 rlimit rl;
467 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
468 ALOGE("getrlimit(RLIMIT_CORE) failed");
469 } else {
470 rl.rlim_cur = 0;
471 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
472 ALOGE("setrlimit(RLIMIT_CORE) failed");
473 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000474 }
475 }
476}
477
Narayan Kamath973b4662014-03-31 13:41:26 +0100478// The debug malloc library needs to know whether it's the zygote or a child.
479extern "C" int gMallocLeakZygoteChild;
480
Christopher Ferris76de39e2017-06-20 16:13:40 -0700481static void PreApplicationInit() {
482 // The child process sets this to indicate it's not the zygote.
483 gMallocLeakZygoteChild = 1;
484
485 // Set the jemalloc decay time to 1.
486 mallopt(M_DECAY_TIME, 1);
487}
488
Martijn Coenen86f08a52019-01-03 16:23:01 +0100489static void SetUpSeccompFilter(uid_t uid, bool is_child_zygote) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800490 if (!g_is_security_enforced) {
491 ALOGI("seccomp disabled by setenforce 0");
492 return;
493 }
494
495 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700496 if (uid >= AID_APP_START) {
Martijn Coenen86f08a52019-01-03 16:23:01 +0100497 if (is_child_zygote) {
Martijn Coenen6ef16802019-01-18 16:40:01 +0100498 set_app_zygote_seccomp_filter();
Martijn Coenen86f08a52019-01-03 16:23:01 +0100499 } else {
500 set_app_seccomp_filter();
501 }
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800502 } else {
503 set_system_seccomp_filter();
504 }
505}
506
Chris Wailesaa1c9622019-01-10 16:55:32 -0800507static void EnableKeepCapabilities(fail_fn_t fail_fn) {
508 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
509 fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100510 }
511}
512
Chris Wailesaa1c9622019-01-10 16:55:32 -0800513static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
514 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
515 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100516 if (errno == EINVAL) {
517 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
518 "your kernel is compiled with file capabilities support");
519 } else {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800520 fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100521 }
522 }
523 }
524}
525
Chris Wailesaa1c9622019-01-10 16:55:32 -0800526static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
Josh Gao45dab782017-02-01 14:56:09 -0800527 __user_cap_header_struct capheader;
528 memset(&capheader, 0, sizeof(capheader));
529 capheader.version = _LINUX_CAPABILITY_VERSION_3;
530 capheader.pid = 0;
531
532 __user_cap_data_struct capdata[2];
533 if (capget(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800534 fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800535 }
536
537 capdata[0].inheritable = inheritable;
538 capdata[1].inheritable = inheritable >> 32;
539
540 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800541 fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800542 }
543}
544
Chris Wailesaa1c9622019-01-10 16:55:32 -0800545static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
546 fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100547 __user_cap_header_struct capheader;
548 memset(&capheader, 0, sizeof(capheader));
549 capheader.version = _LINUX_CAPABILITY_VERSION_3;
550 capheader.pid = 0;
551
552 __user_cap_data_struct capdata[2];
553 memset(&capdata, 0, sizeof(capdata));
554 capdata[0].effective = effective;
555 capdata[1].effective = effective >> 32;
556 capdata[0].permitted = permitted;
557 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800558 capdata[0].inheritable = inheritable;
559 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100560
561 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800562 fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
563 "failed: %s", permitted, effective, inheritable, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100564 }
565}
566
Chris Wailesaa1c9622019-01-10 16:55:32 -0800567static void SetSchedulerPolicy(fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100568 errno = -set_sched_policy(0, SP_DEFAULT);
569 if (errno != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800570 fail_fn(CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100571 }
572}
573
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700574static int UnmountTree(const char* path) {
575 size_t path_len = strlen(path);
576
577 FILE* fp = setmntent("/proc/mounts", "r");
Chris Wailesaa1c9622019-01-10 16:55:32 -0800578 if (fp == nullptr) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700579 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
580 return -errno;
581 }
582
583 // Some volumes can be stacked on each other, so force unmount in
584 // reverse order to give us the best chance of success.
585 std::list<std::string> toUnmount;
586 mntent* mentry;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800587 while ((mentry = getmntent(fp)) != nullptr) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700588 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
589 toUnmount.push_front(std::string(mentry->mnt_dir));
590 }
591 }
592 endmntent(fp);
593
Chih-Hung Hsieha1b644e2018-12-11 11:09:20 -0800594 for (const auto& path : toUnmount) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700595 if (umount2(path.c_str(), MNT_DETACH)) {
596 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
597 }
598 }
599 return 0;
600}
601
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800602static void CreateDir(const std::string& dir,
603 mode_t mode, uid_t uid, gid_t gid,
604 fail_fn_t fail_fn) {
605 if (TEMP_FAILURE_RETRY(access(dir.c_str(), F_OK)) == 0) {
606 return;
607 } else if (errno != ENOENT) {
608 fail_fn(CREATE_ERROR("Failed to stat %s: %s", dir.c_str(), strerror(errno)));
609 }
610 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
611 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s: %s",
612 dir.c_str(), strerror(errno)));
613 }
614}
615
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000616static void CreatePkgSandboxTarget(uid_t uid, const std::string& package_name, fail_fn_t fail_fn) {
Sudheer Shanka663b1042018-07-30 17:34:21 -0700617 // Create /mnt/user/0/package/<package-name>
618 userid_t user_id = multiuser_get_user_id(uid);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700619 std::string pkg_sandbox_dir = StringPrintf("/mnt/user/%d", user_id);
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800620 CreateDir(pkg_sandbox_dir, 0751, AID_ROOT, AID_ROOT, fail_fn);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800621
Sudheer Shanka663b1042018-07-30 17:34:21 -0700622 StringAppendF(&pkg_sandbox_dir, "/package");
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800623 CreateDir(pkg_sandbox_dir, 0700, AID_ROOT, AID_ROOT, fail_fn);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800624
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700625 StringAppendF(&pkg_sandbox_dir, "/%s", package_name.c_str());
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000626 CreateDir(pkg_sandbox_dir, 0755, uid, uid, fail_fn);
Sudheer Shanka663b1042018-07-30 17:34:21 -0700627}
628
Chris Wailesaa1c9622019-01-10 16:55:32 -0800629static void BindMount(const std::string& sourceDir, const std::string& targetDir,
630 fail_fn_t fail_fn) {
631 if (TEMP_FAILURE_RETRY(mount(sourceDir.c_str(), targetDir.c_str(), nullptr,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800632 MS_BIND, nullptr)) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800633 fail_fn(CREATE_ERROR("Failed to mount %s to %s: %s",
634 sourceDir.c_str(), targetDir.c_str(), strerror(errno)));
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800635 }
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800636}
637
Chris Wailesaa1c9622019-01-10 16:55:32 -0800638static void MountPkgSpecificDir(const std::string& mntSourceRoot,
639 const std::string& mntTargetRoot,
640 const std::string& packageName,
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800641 uid_t uid,
Chris Wailesaa1c9622019-01-10 16:55:32 -0800642 const char* dirName,
643 fail_fn_t fail_fn) {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700644 std::string mntSourceDir = StringPrintf("%s/Android/%s/%s",
645 mntSourceRoot.c_str(), dirName, packageName.c_str());
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800646
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700647 std::string mntTargetDir = StringPrintf("%s/Android/%s/%s",
648 mntTargetRoot.c_str(), dirName, packageName.c_str());
Chris Wailesaa1c9622019-01-10 16:55:32 -0800649
650 BindMount(mntSourceDir, mntTargetDir, fail_fn);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700651}
652
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000653static void CreateSubDirs(int dirfd, const std::string& parentDirPath,
654 const std::vector<std::string>& subDirs,
655 fail_fn_t fail_fn) {
656 for (auto& dirName : subDirs) {
657 struct stat sb;
658 if (TEMP_FAILURE_RETRY(fstatat(dirfd, dirName.c_str(), &sb, 0)) == 0) {
659 if (S_ISDIR(sb.st_mode)) {
660 continue;
661 } else if (TEMP_FAILURE_RETRY(unlinkat(dirfd, dirName.c_str(), 0)) == -1) {
662 fail_fn(CREATE_ERROR("Failed to unlinkat on %s/%s: %s",
663 parentDirPath.c_str(), dirName.c_str(), strerror(errno)));
664 }
665 } else if (errno != ENOENT) {
666 fail_fn(CREATE_ERROR("Failed to fstatat on %s/%s: %s",
667 parentDirPath.c_str(), dirName.c_str(), strerror(errno)));
668 }
669 if (TEMP_FAILURE_RETRY(mkdirat(dirfd, dirName.c_str(), 0700)) == -1) {
670 fail_fn(CREATE_ERROR("Failed to mkdirat on %s/%s: %s",
671 parentDirPath.c_str(), dirName.c_str(), strerror(errno)));
672 }
Sudheer Shankad8b4f102019-02-12 19:01:21 -0800673 }
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000674}
675
676static void EnsurePkgSpecificDirs(const std::string& path,
677 const std::vector<std::string>& packageNames,
678 bool createSandboxDir,
679 fail_fn_t fail_fn) {
680 std::string androidDir = StringPrintf("%s/Android", path.c_str());
681 android::base::unique_fd androidFd(
682 open(androidDir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
683 if (androidFd.get() < 0) {
684 if (errno == ENOENT || errno == ENOTDIR) {
685 if (errno == ENOTDIR && TEMP_FAILURE_RETRY(unlink(androidDir.c_str())) == -1) {
686 fail_fn(CREATE_ERROR("Failed to unlink %s: %s",
687 androidDir.c_str(), strerror(errno)));
688 }
689 if (TEMP_FAILURE_RETRY(mkdir(androidDir.c_str(), 0700)) == -1) {
690 fail_fn(CREATE_ERROR("Failed to mkdir %s: %s",
691 androidDir.c_str(), strerror(errno)));
692 }
693 androidFd.reset(open(androidDir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
694 }
695
696 if (androidFd.get() < 0) {
697 fail_fn(CREATE_ERROR("Failed to open %s: %s", androidDir.c_str(), strerror(errno)));
698 }
699 }
700
701 std::vector<std::string> dataMediaObbDirs = {"data", "media", "obb"};
702 if (createSandboxDir) {
703 dataMediaObbDirs.push_back("sandbox");
704 }
705 CreateSubDirs(androidFd.get(), androidDir, dataMediaObbDirs, fail_fn);
706 if (createSandboxDir) {
707 dataMediaObbDirs.pop_back();
708 }
709 for (auto& dirName : dataMediaObbDirs) {
710 std::string dataDir = StringPrintf("%s/%s", androidDir.c_str(), dirName.c_str());
711 android::base::unique_fd dataFd(
712 openat(androidFd, dirName.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
713 if (dataFd.get() < 0) {
714 fail_fn(CREATE_ERROR("Failed to openat %s/%s: %s",
715 androidDir.c_str(), dirName.c_str(), strerror(errno)));
716 }
717 CreateSubDirs(dataFd.get(), dataDir, packageNames, fail_fn);
718 }
719}
720
721static void CreatePkgSandboxSource(const std::string& sandboxSource, fail_fn_t fail_fn) {
722
723 struct stat sb;
724 if (TEMP_FAILURE_RETRY(stat(sandboxSource.c_str(), &sb)) == 0) {
725 if (S_ISDIR(sb.st_mode)) {
726 return;
727 } else if (TEMP_FAILURE_RETRY(unlink(sandboxSource.c_str())) == -1) {
728 fail_fn(CREATE_ERROR("Failed to unlink %s: %s",
729 sandboxSource.c_str(), strerror(errno)));
730 }
731 } else if (errno != ENOENT) {
732 fail_fn(CREATE_ERROR("Failed to stat %s: %s",
733 sandboxSource.c_str(), strerror(errno)));
734 }
735 if (TEMP_FAILURE_RETRY(mkdir(sandboxSource.c_str(), 0700)) == -1) {
736 fail_fn(CREATE_ERROR("Failed to mkdir %s: %s",
737 sandboxSource.c_str(), strerror(errno)));
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800738 }
739}
740
Chris Wailesaa1c9622019-01-10 16:55:32 -0800741static void PreparePkgSpecificDirs(const std::vector<std::string>& packageNames,
742 const std::vector<std::string>& volumeLabels,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800743 bool mountAllObbs, const std::string& sandboxId,
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800744 userid_t userId, uid_t uid, fail_fn_t fail_fn) {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700745 for (auto& label : volumeLabels) {
746 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", label.c_str());
747 std::string mntTarget = StringPrintf("/storage/%s", label.c_str());
748 if (label == "emulated") {
749 StringAppendF(&mntSource, "/%d", userId);
750 StringAppendF(&mntTarget, "/%d", userId);
751 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800752
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000753 if (TEMP_FAILURE_RETRY(access(mntSource.c_str(), F_OK)) == -1) {
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800754 ALOGE("Can't access %s: %s", mntSource.c_str(), strerror(errno));
755 continue;
756 }
757
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000758 // Ensure /mnt/runtime/write/emulated/0/Android/{data,media,obb}
759 EnsurePkgSpecificDirs(mntSource, packageNames, true, fail_fn);
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800760
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800761 std::string sandboxSource = StringPrintf("%s/Android/sandbox/%s",
762 mntSource.c_str(), sandboxId.c_str());
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000763 CreatePkgSandboxSource(sandboxSource, fail_fn);
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800764 BindMount(sandboxSource, mntTarget, fail_fn);
765
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000766 // Ensure /storage/emulated/0/Android/{data,media,obb}
767 EnsurePkgSpecificDirs(mntTarget, packageNames, false, fail_fn);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700768 for (auto& package : packageNames) {
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800769 MountPkgSpecificDir(mntSource, mntTarget, package, uid, "data", fail_fn);
770 MountPkgSpecificDir(mntSource, mntTarget, package, uid, "media", fail_fn);
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800771 if (!mountAllObbs) {
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800772 MountPkgSpecificDir(mntSource, mntTarget, package, uid, "obb", fail_fn);
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800773 }
774 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800775
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800776 if (mountAllObbs) {
777 StringAppendF(&mntSource, "/Android/obb");
778 StringAppendF(&mntTarget, "/Android/obb");
Chris Wailesaa1c9622019-01-10 16:55:32 -0800779 BindMount(mntSource, mntTarget, fail_fn);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700780 }
781 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700782}
783
Narayan Kamath973b4662014-03-31 13:41:26 +0100784// Create a private mount namespace and bind mount appropriate emulated
785// storage for the given user.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800786static void MountEmulatedStorage(uid_t uid, jint mount_mode,
787 bool force_mount_namespace, const std::string& package_name,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700788 const std::vector<std::string>& packages_for_uid,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800789 const std::vector<std::string>& visible_vol_ids, const std::string& sandbox_id,
790 fail_fn_t fail_fn) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700791 // See storage config details at http://source.android.com/tech/storage/
792
Jeff Sharkey9527b222015-06-24 15:24:48 -0700793 String8 storageSource;
794 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700795 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700796 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700797 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700798 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700799 storageSource = "/mnt/runtime/write";
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800800 } else if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700801 // Sane default of no storage visible
Chris Wailesaa1c9622019-01-10 16:55:32 -0800802 return;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700803 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400804
805 // Create a second private mount namespace for our process
806 if (unshare(CLONE_NEWNS) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800807 fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400808 }
809
Robert Sesek06f39302017-03-20 17:30:05 -0400810 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
811 if (mount_mode == MOUNT_EXTERNAL_NONE) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800812 return;
Robert Sesek06f39302017-03-20 17:30:05 -0400813 }
814
Jeff Sharkey06376802019-02-11 12:20:02 -0700815 if (GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, true))) {
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800816 if (mount_mode == MOUNT_EXTERNAL_FULL || mount_mode == MOUNT_EXTERNAL_LEGACY) {
817 storageSource = (mount_mode == MOUNT_EXTERNAL_FULL)
818 ? "/mnt/runtime/full" : "/mnt/runtime/write";
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700819 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
Chris Wailesaa1c9622019-01-10 16:55:32 -0800820 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
821 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
822 storageSource.string(),
823 strerror(errno)));
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700824 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700825
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700826 // Mount user-specific symlink helper into place
827 userid_t user_id = multiuser_get_user_id(uid);
828 const String8 userSource(String8::format("/mnt/user/%d", user_id));
829 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800830 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s (%s)",
831 userSource.string(), strerror(errno)));
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700832 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800833
834 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self", nullptr, MS_BIND,
835 nullptr)) == -1) {
836 fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
837 userSource.string(),
838 strerror(errno)));
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700839 }
840 } else {
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800841 if (package_name.empty() || sandbox_id.empty()) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800842 return;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700843 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800844
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700845 userid_t user_id = multiuser_get_user_id(uid);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800846 std::string pkgSandboxDir =
847 StringPrintf("/mnt/user/%d/package/%s", user_id, package_name.c_str());
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700848 bool sandboxAlreadyCreated = true;
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000849 if (TEMP_FAILURE_RETRY(access(pkgSandboxDir.c_str(), F_OK)) == -1) {
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700850 if (errno == ENOENT) {
851 ALOGD("Sandbox not yet created for %s", pkgSandboxDir.c_str());
852 sandboxAlreadyCreated = false;
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000853 CreatePkgSandboxTarget(uid, package_name, fail_fn);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700854 } else {
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000855 fail_fn(CREATE_ERROR("Failed to access %s: %s",
Chris Wailesaa1c9622019-01-10 16:55:32 -0800856 pkgSandboxDir.c_str(), strerror(errno)));
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700857 }
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700858 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800859
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700860 if (TEMP_FAILURE_RETRY(mount(pkgSandboxDir.c_str(), "/storage",
Chris Wailesaa1c9622019-01-10 16:55:32 -0800861 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
862 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
863 pkgSandboxDir.c_str(), strerror(errno)));
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700864 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800865
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000866 if (TEMP_FAILURE_RETRY(access("/storage/obb_mount", F_OK)) == 0) {
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800867 if (mount_mode != MOUNT_EXTERNAL_INSTALLER) {
868 remove("/storage/obb_mount");
869 }
870 } else {
871 if (mount_mode == MOUNT_EXTERNAL_INSTALLER) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800872 int fd =
873 TEMP_FAILURE_RETRY(open("/storage/obb_mount", O_RDWR | O_CREAT, 0660));
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800874 if (fd == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800875 fail_fn(CREATE_ERROR("Couldn't create /storage/obb_mount: %s",
876 strerror(errno)));
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800877 }
878 close(fd);
879 }
880 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700881 // If the sandbox was already created by vold, only then set up the bind mounts for
882 // pkg specific directories. Otherwise, leave as is and bind mounts will be taken
883 // care of by vold later.
884 if (sandboxAlreadyCreated) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800885 PreparePkgSpecificDirs(packages_for_uid, visible_vol_ids,
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800886 mount_mode == MOUNT_EXTERNAL_INSTALLER, sandbox_id, user_id, uid, fail_fn);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700887 }
Sudheer Shanka663b1042018-07-30 17:34:21 -0700888 }
889 } else {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800890 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage", nullptr,
891 MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
892 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
893 storageSource.string(),
894 strerror(errno)));
Sudheer Shanka663b1042018-07-30 17:34:21 -0700895 }
896
897 // Mount user-specific symlink helper into place
898 userid_t user_id = multiuser_get_user_id(uid);
899 const String8 userSource(String8::format("/mnt/user/%d", user_id));
900 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800901 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s",
902 userSource.string()));
Sudheer Shanka663b1042018-07-30 17:34:21 -0700903 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800904
Sudheer Shanka663b1042018-07-30 17:34:21 -0700905 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
Chris Wailesaa1c9622019-01-10 16:55:32 -0800906 nullptr, MS_BIND, nullptr)) == -1) {
907 fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
908 userSource.string(), strerror(errno)));
Sudheer Shanka663b1042018-07-30 17:34:21 -0700909 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700910 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100911}
912
Narayan Kamath973b4662014-03-31 13:41:26 +0100913static bool NeedsNoRandomizeWorkaround() {
914#if !defined(__arm__)
915 return false;
916#else
917 int major;
918 int minor;
919 struct utsname uts;
920 if (uname(&uts) == -1) {
921 return false;
922 }
923
924 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
925 return false;
926 }
927
928 // Kernels before 3.4.* need the workaround.
929 return (major < 3) || ((major == 3) && (minor < 4));
930#endif
931}
Narayan Kamath973b4662014-03-31 13:41:26 +0100932
933// Utility to close down the Zygote socket file descriptors while
934// the child is still running as root with Zygote's privileges. Each
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800935// descriptor (if any) is closed via dup3(), replacing it with a valid
Narayan Kamath973b4662014-03-31 13:41:26 +0100936// (open) descriptor to /dev/null.
937
Chris Wailesaa1c9622019-01-10 16:55:32 -0800938static void DetachDescriptors(JNIEnv* env,
939 const std::vector<int>& fds_to_close,
940 fail_fn_t fail_fn) {
941
942 if (fds_to_close.size() > 0) {
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800943 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800944 if (devnull_fd == -1) {
945 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100946 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800947
948 for (int fd : fds_to_close) {
949 ALOGV("Switching descriptor %d to /dev/null", fd);
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800950 if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
951 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800952 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100953 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100954 }
955}
956
Chris Wailesaa1c9622019-01-10 16:55:32 -0800957void SetThreadName(const std::string& thread_name) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100958 bool hasAt = false;
959 bool hasDot = false;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800960
961 for (const char str_el : thread_name) {
962 if (str_el == '.') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100963 hasDot = true;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800964 } else if (str_el == '@') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100965 hasAt = true;
966 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100967 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800968
969 const char* name_start_ptr = thread_name.c_str();
970 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
971 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
Narayan Kamath973b4662014-03-31 13:41:26 +0100972 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800973
Narayan Kamath973b4662014-03-31 13:41:26 +0100974 // pthread_setname_np fails rather than truncating long strings.
975 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
Chris Wailesaa1c9622019-01-10 16:55:32 -0800976 strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
Narayan Kamath973b4662014-03-31 13:41:26 +0100977 errno = pthread_setname_np(pthread_self(), buf);
978 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700979 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100980 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800981 // Update base::logging default tag.
982 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100983}
984
Chris Wailesaa1c9622019-01-10 16:55:32 -0800985/**
986 * A failure function used to report fatal errors to the managed runtime. This
987 * function is often curried with the process name information and then passed
988 * to called functions.
989 *
990 * @param env Managed runtime environment
991 * @param process_name A native representation of the process name
992 * @param managed_process_name A managed representation of the process name
993 * @param msg The error message to be reported
994 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700995[[noreturn]]
996static void ZygoteFailure(JNIEnv* env,
997 const char* process_name,
998 jstring managed_process_name,
999 const std::string& msg) {
1000 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
1001 if (managed_process_name != nullptr) {
1002 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
1003 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
1004 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -07001005 }
1006 }
1007
Chris Wailesaf594fc2018-11-02 11:00:07 -07001008 const std::string& error_msg =
1009 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -07001010
Chris Wailesaf594fc2018-11-02 11:00:07 -07001011 env->FatalError(error_msg.c_str());
1012 __builtin_unreachable();
1013}
David Sehrde8d0bd2018-06-22 10:45:36 -07001014
Chris Wailesaa1c9622019-01-10 16:55:32 -08001015/**
1016 * A helper method for converting managed strings to native strings. A fatal
1017 * error is generated if a problem is encountered in extracting a non-null
1018 * string.
1019 *
1020 * @param env Managed runtime environment
1021 * @param process_name A native representation of the process name
1022 * @param managed_process_name A managed representation of the process name
1023 * @param managed_string The managed string to extract
1024 *
1025 * @return An empty option if the managed string is null. A optional-wrapped
1026 * string otherwise.
1027 */
Chris Wailesaf594fc2018-11-02 11:00:07 -07001028static std::optional<std::string> ExtractJString(JNIEnv* env,
1029 const char* process_name,
1030 jstring managed_process_name,
1031 jstring managed_string) {
1032 if (managed_string == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001033 return std::nullopt;
Chris Wailesaf594fc2018-11-02 11:00:07 -07001034 } else {
1035 ScopedUtfChars scoped_string_chars(env, managed_string);
1036
1037 if (scoped_string_chars.c_str() != nullptr) {
1038 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -07001039 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001040 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -07001041 }
1042 }
David Sehrde8d0bd2018-06-22 10:45:36 -07001043}
1044
Chris Wailesaa1c9622019-01-10 16:55:32 -08001045/**
1046 * A helper method for converting managed string arrays to native vectors. A
1047 * fatal error is generated if a problem is encountered in extracting a non-null array.
1048 *
1049 * @param env Managed runtime environment
1050 * @param process_name A native representation of the process name
1051 * @param managed_process_name A managed representation of the process name
1052 * @param managed_array The managed integer array to extract
1053 *
1054 * @return An empty option if the managed array is null. A optional-wrapped
1055 * vector otherwise.
1056 */
1057static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
1058 const char* process_name,
1059 jstring managed_process_name,
1060 jintArray managed_array) {
1061 if (managed_array == nullptr) {
1062 return std::nullopt;
1063 } else {
1064 ScopedIntArrayRO managed_array_handle(env, managed_array);
Narayan Kamath973b4662014-03-31 13:41:26 +01001065
Chris Wailesaa1c9622019-01-10 16:55:32 -08001066 if (managed_array_handle.get() != nullptr) {
1067 std::vector<int> native_array;
1068 native_array.reserve(managed_array_handle.size());
1069
1070 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
1071 native_array.push_back(managed_array_handle[array_index]);
1072 }
1073
1074 return std::move(native_array);
1075
1076 } else {
1077 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
1078 }
1079 }
1080}
1081
1082/**
1083 * A helper method for converting managed string arrays to native vectors. A
1084 * fatal error is generated if a problem is encountered in extracting a non-null array.
1085 *
1086 * @param env Managed runtime environment
1087 * @param process_name A native representation of the process name
1088 * @param managed_process_name A managed representation of the process name
1089 * @param managed_array The managed string array to extract
1090 *
1091 * @return An empty option if the managed array is null. A optional-wrapped
1092 * vector otherwise.
1093 */
1094static std::optional<std::vector<std::string>> ExtractJStringArray(JNIEnv* env,
1095 const char* process_name,
1096 jstring managed_process_name,
1097 jobjectArray managed_array) {
1098 if (managed_array == nullptr) {
1099 return std::nullopt;
1100 } else {
1101 jsize element_count = env->GetArrayLength(managed_array);
1102 std::vector<std::string> native_string_vector;
1103 native_string_vector.reserve(element_count);
1104
1105 for (jsize array_index = 0; array_index < element_count; ++array_index) {
1106 jstring managed_string = (jstring) env->GetObjectArrayElement(managed_array, array_index);
1107 auto native_string = ExtractJString(env, process_name, managed_process_name, managed_string);
1108
1109 if (LIKELY(native_string.has_value())) {
1110 native_string_vector.emplace_back(std::move(native_string.value()));
1111 } else {
1112 ZygoteFailure(env, process_name, managed_process_name,
1113 "Null string found in managed string array.");
1114 }
1115 }
1116
1117 return std::move(native_string_vector);
1118 }
1119}
1120
1121/**
1122 * A utility function for blocking signals.
1123 *
1124 * @param signum Signal number to block
1125 * @param fail_fn Fatal error reporting function
1126 *
1127 * @see ZygoteFailure
1128 */
1129static void BlockSignal(int signum, fail_fn_t fail_fn) {
1130 sigset_t sigs;
1131 sigemptyset(&sigs);
1132 sigaddset(&sigs, signum);
1133
1134 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
1135 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
1136 }
1137}
1138
1139
1140/**
1141 * A utility function for unblocking signals.
1142 *
1143 * @param signum Signal number to unblock
1144 * @param fail_fn Fatal error reporting function
1145 *
1146 * @see ZygoteFailure
1147 */
1148static void UnblockSignal(int signum, fail_fn_t fail_fn) {
1149 sigset_t sigs;
1150 sigemptyset(&sigs);
1151 sigaddset(&sigs, signum);
1152
1153 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
1154 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
1155 }
1156}
1157
1158// Utility routine to fork a process from the zygote.
1159static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
1160 const std::vector<int>& fds_to_close,
1161 const std::vector<int>& fds_to_ignore) {
1162 SetSignalHandlers();
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001163
Chris Wailesaf594fc2018-11-02 11:00:07 -07001164 // Curry a failure function.
1165 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
1166 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -07001167
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001168 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
1169 // log, which would result in the logging FDs we close being reopened.
1170 // This would cause failures because the FDs are not whitelisted.
1171 //
1172 // Note that the zygote process is single threaded at this point.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001173 BlockSignal(SIGCHLD, fail_fn);
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001174
Narayan Kamath3764a262016-08-30 15:36:19 +01001175 // Close any logging related FDs before we start evaluating the list of
1176 // file descriptors.
1177 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -07001178 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +01001179
Chris Wailesaf594fc2018-11-02 11:00:07 -07001180 // If this is the first fork for this zygote, create the open FD table. If
1181 // it isn't, we just need to check whether the list of open files has changed
1182 // (and it shouldn't in the normal case).
Chris Wailesaf594fc2018-11-02 11:00:07 -07001183 if (gOpenFdTable == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001184 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
1185 } else {
1186 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001187 }
1188
Josh Gaod7951102018-06-26 16:05:12 -07001189 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
1190
Narayan Kamath973b4662014-03-31 13:41:26 +01001191 pid_t pid = fork();
1192
1193 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -07001194 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -07001195 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -07001196
Narayan Kamath973b4662014-03-31 13:41:26 +01001197 // Clean up any descriptors which must be closed immediately
Chris Wailesaa1c9622019-01-10 16:55:32 -08001198 DetachDescriptors(env, fds_to_close, fail_fn);
Narayan Kamath973b4662014-03-31 13:41:26 +01001199
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001200 // Re-open all remaining open file descriptors so that they aren't shared
1201 // with the zygote across a fork.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001202 gOpenFdTable->ReopenOrDetach(fail_fn);
Josh Gaod7951102018-06-26 16:05:12 -07001203
1204 // Turn fdsan back on.
1205 android_fdsan_set_error_level(fdsan_error_level);
David Sehrde8d0bd2018-06-22 10:45:36 -07001206 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001207
David Sehrde8d0bd2018-06-22 10:45:36 -07001208 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001209 UnblockSignal(SIGCHLD, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001210
Narayan Kamath973b4662014-03-31 13:41:26 +01001211 return pid;
1212}
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001213
Chris Wailesaf594fc2018-11-02 11:00:07 -07001214// Utility routine to specialize a zygote child process.
1215static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
1216 jint runtime_flags, jobjectArray rlimits,
1217 jlong permitted_capabilities, jlong effective_capabilities,
1218 jint mount_external, jstring managed_se_info,
1219 jstring managed_nice_name, bool is_system_server,
1220 bool is_child_zygote, jstring managed_instruction_set,
1221 jstring managed_app_data_dir, jstring managed_package_name,
1222 jobjectArray managed_pacakges_for_uid,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001223 jobjectArray managed_visible_vol_ids, jstring managed_sandbox_id) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001224 const char* process_name = is_system_server ? "system_server" : "zygote";
1225 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
1226 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001227
1228 auto se_info = extract_fn(managed_se_info);
1229 auto nice_name = extract_fn(managed_nice_name);
1230 auto instruction_set = extract_fn(managed_instruction_set);
1231 auto app_data_dir = extract_fn(managed_app_data_dir);
1232 auto package_name = extract_fn(managed_package_name);
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001233 auto sandbox_id = extract_fn(managed_sandbox_id);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001234
Chris Wailesaf594fc2018-11-02 11:00:07 -07001235 // Keep capabilities across UID change, unless we're staying root.
1236 if (uid != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001237 EnableKeepCapabilities(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001238 }
1239
Chris Wailesaa1c9622019-01-10 16:55:32 -08001240 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001241
Chris Wailesaa1c9622019-01-10 16:55:32 -08001242 DropCapabilitiesBoundingSet(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001243
1244 bool use_native_bridge = !is_system_server &&
1245 instruction_set.has_value() &&
1246 android::NativeBridgeAvailable() &&
1247 android::NeedsNativeBridge(instruction_set.value().c_str());
1248
1249 if (use_native_bridge && !app_data_dir.has_value()) {
1250 // The app_data_dir variable should never be empty if we need to use a
1251 // native bridge. In general, app_data_dir will never be empty for normal
1252 // applications. It can only happen in special cases (for isolated
1253 // processes which are not associated with any app). These are launched by
1254 // the framework and should not be emulated anyway.
1255 use_native_bridge = false;
1256 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
1257 }
1258
1259 if (!package_name.has_value()) {
1260 if (is_system_server) {
1261 package_name.emplace("android");
1262 } else {
1263 package_name.emplace("");
1264 }
1265 }
1266
Chris Wailesaa1c9622019-01-10 16:55:32 -08001267 std::vector<std::string> packages_for_uid =
1268 ExtractJStringArray(env, process_name, managed_nice_name, managed_pacakges_for_uid).
1269 value_or(std::vector<std::string>());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001270
Chris Wailesaa1c9622019-01-10 16:55:32 -08001271 std::vector<std::string> visible_vol_ids =
1272 ExtractJStringArray(env, process_name, managed_nice_name, managed_visible_vol_ids).
1273 value_or(std::vector<std::string>());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001274
Chris Wailesaa1c9622019-01-10 16:55:32 -08001275 MountEmulatedStorage(uid, mount_external, use_native_bridge, package_name.value(),
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001276 packages_for_uid, visible_vol_ids, sandbox_id.value_or(""), fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001277
1278 // If this zygote isn't root, it won't be able to create a process group,
1279 // since the directory is owned by root.
1280 if (!is_system_server && getuid() == 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001281 const int rc = createProcessGroup(uid, getpid());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001282 if (rc == -EROFS) {
1283 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
1284 } else if (rc != 0) {
1285 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
1286 }
1287 }
1288
Chris Wailesaa1c9622019-01-10 16:55:32 -08001289 SetGids(env, gids, fail_fn);
1290 SetRLimits(env, rlimits, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001291
1292 if (use_native_bridge) {
1293 // Due to the logic behind use_native_bridge we know that both app_data_dir
1294 // and instruction_set contain values.
1295 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
1296 instruction_set.value().c_str());
1297 }
1298
1299 if (setresgid(gid, gid, gid) == -1) {
1300 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
1301 }
1302
1303 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
1304 // before changing uid from 0, which clears capabilities. The other
1305 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
1306 // breaks SELinux domain transition (see b/71859146). As the result,
1307 // privileged syscalls used below still need to be accessible in app process.
Martijn Coenen86f08a52019-01-03 16:23:01 +01001308 SetUpSeccompFilter(uid, is_child_zygote);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001309
1310 if (setresuid(uid, uid, uid) == -1) {
1311 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1312 }
1313
1314 // The "dumpable" flag of a process, which controls core dump generation, is
1315 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1316 // user or group ID changes. See proc(5) for possible values. In most cases,
1317 // the value is 0, so core dumps are disabled for zygote children. However,
1318 // when running in a Chrome OS container, the value is already set to 2,
1319 // which allows the external crash reporter to collect all core dumps. Since
1320 // only system crashes are interested, core dump is disabled for app
1321 // processes. This also ensures compliance with CTS.
1322 int dumpable = prctl(PR_GET_DUMPABLE);
1323 if (dumpable == -1) {
1324 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1325 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1326 }
1327
1328 if (dumpable == 2 && uid >= AID_APP) {
1329 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1330 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1331 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1332 }
1333 }
1334
Orion Hodson8d005a62018-12-05 12:28:53 +00001335 // Set process properties to enable debugging if required.
1336 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1337 EnableDebugger();
1338 }
Yabin Cui4d8546d2019-01-29 16:29:20 -08001339 if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
1340 // simpleperf needs the process to be dumpable to profile it.
1341 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
1342 ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
1343 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
1344 }
1345 }
Orion Hodson8d005a62018-12-05 12:28:53 +00001346
Chris Wailesaf594fc2018-11-02 11:00:07 -07001347 if (NeedsNoRandomizeWorkaround()) {
1348 // Work around ARM kernel ASLR lossage (http://b/5817320).
1349 int old_personality = personality(0xffffffff);
1350 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1351 if (new_personality == -1) {
1352 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1353 }
1354 }
1355
Chris Wailesaa1c9622019-01-10 16:55:32 -08001356 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001357
Chris Wailesaa1c9622019-01-10 16:55:32 -08001358 SetSchedulerPolicy(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001359
Mathieu Chartier0bccbf72019-01-30 15:56:17 -08001360 __android_log_close();
1361 stats_log_close();
1362
Chris Wailesaf594fc2018-11-02 11:00:07 -07001363 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1364 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1365
1366 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1367 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1368 uid, is_system_server, se_info_ptr, nice_name_ptr));
1369 }
1370
1371 // Make it easier to debug audit logs by setting the main thread's name to the
1372 // nice name rather than "app_process".
1373 if (nice_name.has_value()) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001374 SetThreadName(nice_name.value());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001375 } else if (is_system_server) {
1376 SetThreadName("system_server");
1377 }
1378
1379 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1380 UnsetChldSignalHandler();
1381
1382 if (is_system_server) {
1383 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1384 if (env->ExceptionCheck()) {
1385 fail_fn("Error calling post fork system server hooks.");
1386 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001387
Chris Wailesaf594fc2018-11-02 11:00:07 -07001388 // TODO(oth): Remove hardcoded label here (b/117874058).
1389 static const char* kSystemServerLabel = "u:r:system_server:s0";
1390 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1391 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1392 }
1393 }
1394
1395 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1396 is_system_server, is_child_zygote, managed_instruction_set);
1397
1398 if (env->ExceptionCheck()) {
1399 fail_fn("Error calling post fork hooks.");
1400 }
1401}
1402
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001403static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1404 __user_cap_header_struct capheader;
1405 memset(&capheader, 0, sizeof(capheader));
1406 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1407 capheader.pid = 0;
1408
1409 __user_cap_data_struct capdata[2];
1410 if (capget(&capheader, &capdata[0]) == -1) {
1411 ALOGE("capget failed: %s", strerror(errno));
1412 RuntimeAbort(env, __LINE__, "capget failed");
1413 }
1414
Chris Wailesaf594fc2018-11-02 11:00:07 -07001415 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1416}
1417
1418static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1419 bool is_child_zygote) {
1420 jlong capabilities = 0;
1421
1422 /*
1423 * Grant the following capabilities to the Bluetooth user:
1424 * - CAP_WAKE_ALARM
1425 * - CAP_NET_RAW
1426 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1427 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1428 */
1429
1430 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1431 capabilities |= (1LL << CAP_WAKE_ALARM);
1432 capabilities |= (1LL << CAP_NET_RAW);
1433 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1434 capabilities |= (1LL << CAP_SYS_NICE);
1435 }
1436
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001437 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1438 capabilities |= (1LL << CAP_NET_ADMIN);
1439 capabilities |= (1LL << CAP_NET_BROADCAST);
1440 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1441 capabilities |= (1LL << CAP_NET_RAW);
1442 }
1443
Chris Wailesaf594fc2018-11-02 11:00:07 -07001444 /*
1445 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1446 */
1447
1448 bool gid_wakelock_found = false;
1449 if (gid == AID_WAKELOCK) {
1450 gid_wakelock_found = true;
1451 } else if (gids != nullptr) {
1452 jsize gids_num = env->GetArrayLength(gids);
1453 ScopedIntArrayRO native_gid_proxy(env, gids);
1454
1455 if (native_gid_proxy.get() == nullptr) {
1456 RuntimeAbort(env, __LINE__, "Bad gids array");
1457 }
1458
Chris Wailes31c52c92019-02-14 11:20:02 -08001459 for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
1460 if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001461 gid_wakelock_found = true;
1462 break;
1463 }
1464 }
1465 }
1466
1467 if (gid_wakelock_found) {
1468 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1469 }
1470
1471 /*
1472 * Grant child Zygote processes the following capabilities:
1473 * - CAP_SETUID (change UID of child processes)
1474 * - CAP_SETGID (change GID of child processes)
1475 * - CAP_SETPCAP (change capabilities of child processes)
1476 */
1477
1478 if (is_child_zygote) {
1479 capabilities |= (1LL << CAP_SETUID);
1480 capabilities |= (1LL << CAP_SETGID);
1481 capabilities |= (1LL << CAP_SETPCAP);
1482 }
1483
1484 /*
1485 * Containers run without some capabilities, so drop any caps that are not
1486 * available.
1487 */
1488
1489 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001490}
Chris Wailesaa1c9622019-01-10 16:55:32 -08001491
1492/**
1493 * Adds the given information about a newly created blastula to the Zygote's
1494 * blastula table.
1495 *
1496 * @param blastula_pid Process ID of the newly created blastula
1497 * @param read_pipe_fd File descriptor for the read end of the blastula
1498 * reporting pipe. Used in the ZygoteServer poll loop to track blastula
1499 * specialization.
1500 */
1501static void AddBlastulaTableEntry(pid_t blastula_pid, int read_pipe_fd) {
1502 static int sBlastulaTableInsertIndex = 0;
1503
1504 int search_index = sBlastulaTableInsertIndex;
1505
1506 do {
1507 if (gBlastulaTable[search_index].SetIfInvalid(blastula_pid, read_pipe_fd)) {
1508 // Start our next search right after where we finished this one.
1509 sBlastulaTableInsertIndex = (search_index + 1) % gBlastulaTable.size();
1510
1511 return;
1512 }
1513
1514 search_index = (search_index + 1) % gBlastulaTable.size();
1515 } while (search_index != sBlastulaTableInsertIndex);
1516
1517 // Much like money in the banana stand, there should always be an entry
1518 // in the blastula table.
1519 __builtin_unreachable();
1520}
1521
1522/**
1523 * Invalidates the entry in the BlastulaTable corresponding to the provided
1524 * process ID if it is present. If an entry was removed the blastula pool
1525 * count is decremented.
1526 *
1527 * @param blastula_pid Process ID of the blastula entry to invalidate
1528 * @return True if an entry was invalidated; false otherwise
1529 */
1530static bool RemoveBlastulaTableEntry(pid_t blastula_pid) {
1531 for (BlastulaTableEntry& entry : gBlastulaTable) {
1532 if (entry.ClearForPID(blastula_pid)) {
1533 --gBlastulaPoolCount;
1534 return true;
1535 }
1536 }
1537
1538 return false;
1539}
1540
1541/**
1542 * @return A vector of the read pipe FDs for each of the active blastulas.
1543 */
1544std::vector<int> MakeBlastulaPipeReadFDVector() {
1545 std::vector<int> fd_vec;
1546 fd_vec.reserve(gBlastulaTable.size());
1547
1548 for (BlastulaTableEntry& entry : gBlastulaTable) {
1549 auto entry_values = entry.GetValues();
1550
1551 if (entry_values.has_value()) {
1552 fd_vec.push_back(entry_values.value().read_pipe_fd);
1553 }
1554 }
1555
1556 return fd_vec;
1557}
1558
Narayan Kamath973b4662014-03-31 13:41:26 +01001559} // anonymous namespace
1560
1561namespace android {
1562
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001563static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001564 // security_getenforce is not allowed on app process. Initialize and cache
1565 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001566 g_is_security_enforced = security_getenforce();
1567}
1568
Christopher Ferris76de39e2017-06-20 16:13:40 -07001569static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1570 PreApplicationInit();
1571}
1572
Narayan Kamath973b4662014-03-31 13:41:26 +01001573static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1574 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001575 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001576 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001577 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001578 jstring instruction_set, jstring app_data_dir, jstring package_name,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001579 jobjectArray packages_for_uid, jobjectArray visible_vol_ids, jstring sandbox_id) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001580 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001581
Chris Wailesaa1c9622019-01-10 16:55:32 -08001582 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1583 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1584 }
1585
1586 std::vector<int> fds_to_close =
1587 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1588 std::vector<int> fds_to_ignore =
1589 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1590 .value_or(std::vector<int>());
1591
1592 std::vector<int> blastula_pipes = MakeBlastulaPipeReadFDVector();
1593
1594 fds_to_close.insert(fds_to_close.end(), blastula_pipes.begin(), blastula_pipes.end());
1595 fds_to_ignore.insert(fds_to_ignore.end(), blastula_pipes.begin(), blastula_pipes.end());
1596
Chris Wailesba4c2eb2019-01-11 17:13:00 -08001597 fds_to_close.push_back(gBlastulaPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001598
1599 if (gBlastulaPoolEventFD != -1) {
1600 fds_to_close.push_back(gBlastulaPoolEventFD);
1601 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1602 }
1603
Chris Wailesaf594fc2018-11-02 11:00:07 -07001604 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001605
David Sehrde8d0bd2018-06-22 10:45:36 -07001606 if (pid == 0) {
1607 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1608 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001609 mount_external, se_info, nice_name, false,
1610 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001611 package_name, packages_for_uid, visible_vol_ids, sandbox_id);
David Sehrde8d0bd2018-06-22 10:45:36 -07001612 }
1613 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001614}
1615
1616static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1617 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001618 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1619 jlong effective_capabilities) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001620 std::vector<int> fds_to_close(MakeBlastulaPipeReadFDVector()),
1621 fds_to_ignore(fds_to_close);
1622
Chris Wailesba4c2eb2019-01-11 17:13:00 -08001623 fds_to_close.push_back(gBlastulaPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001624
1625 if (gBlastulaPoolEventFD != -1) {
1626 fds_to_close.push_back(gBlastulaPoolEventFD);
1627 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1628 }
1629
Chris Wailesaf594fc2018-11-02 11:00:07 -07001630 pid_t pid = ForkCommon(env, true,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001631 fds_to_close,
1632 fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001633 if (pid == 0) {
1634 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001635 permitted_capabilities, effective_capabilities,
1636 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001637 false, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001638 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001639 // The zygote process checks whether the child process has died or not.
1640 ALOGI("System server process %d has been created", pid);
1641 gSystemServerPid = pid;
1642 // There is a slight window that the system server process has crashed
1643 // but it went unnoticed because we haven't published its pid yet. So
1644 // we recheck here just to make sure that all is well.
1645 int status;
1646 if (waitpid(pid, &status, WNOHANG) == pid) {
1647 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001648 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001649 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001650
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001651 if (UsePerAppMemcg()) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001652 // Assign system_server to the correct memory cgroup.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001653 // Not all devices mount memcg so check if it is mounted first
Minchan Kim5fa8af22018-06-27 11:32:40 +09001654 // to avoid unnecessarily printing errors and denials in the logs.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001655 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
1656 ALOGE("couldn't add process %d into system memcg group", pid);
Minchan Kim5fa8af22018-06-27 11:32:40 +09001657 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001658 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001659 }
1660 return pid;
1661}
1662
Chris Wailesaa1c9622019-01-10 16:55:32 -08001663/**
1664 * A JNI function that forks a blastula from the Zygote while ensuring proper
1665 * file descriptor hygiene.
1666 *
1667 * @param env Managed runtime environment
1668 * @param read_pipe_fd The read FD for the blastula reporting pipe. Manually closed by blastlas
1669 * in managed code.
1670 * @param write_pipe_fd The write FD for the blastula reporting pipe. Manually closed by the
1671 * zygote in managed code.
1672 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
1673 * the FD hygiene code and automatically "closed" in the new blastula.
1674 * @return
1675 */
1676static jint com_android_internal_os_Zygote_nativeForkBlastula(JNIEnv* env, jclass,
1677 jint read_pipe_fd, jint write_pipe_fd, jintArray managed_session_socket_fds) {
1678 std::vector<int> fds_to_close(MakeBlastulaPipeReadFDVector()),
1679 fds_to_ignore(fds_to_close);
1680
1681 std::vector<int> session_socket_fds =
1682 ExtractJIntArray(env, "blastula", nullptr, managed_session_socket_fds)
1683 .value_or(std::vector<int>());
1684
1685 // The Blastula Pool Event FD is created during the initialization of the
1686 // blastula pool and should always be valid here.
1687
1688 fds_to_close.push_back(gZygoteSocketFD);
1689 fds_to_close.push_back(gBlastulaPoolEventFD);
1690 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
1691
1692 fds_to_ignore.push_back(gZygoteSocketFD);
1693 fds_to_ignore.push_back(gBlastulaPoolSocketFD);
1694 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1695 fds_to_ignore.push_back(read_pipe_fd);
1696 fds_to_ignore.push_back(write_pipe_fd);
1697 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
1698
1699 pid_t blastula_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore);
1700
1701 if (blastula_pid != 0) {
1702 ++gBlastulaPoolCount;
1703 AddBlastulaTableEntry(blastula_pid, read_pipe_fd);
1704 }
1705
1706 return blastula_pid;
1707}
1708
Robert Sesek54e387d2016-12-02 17:27:50 -05001709static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1710 JNIEnv* env, jclass, jstring path) {
1711 ScopedUtfChars path_native(env, path);
1712 const char* path_cstr = path_native.c_str();
1713 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001714 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001715 }
1716 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1717}
1718
doheon1.lee885b7422016-01-20 13:07:27 +09001719static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1720 // Zygote process unmount root storage space initially before every child processes are forked.
1721 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001722 // and no need unmount storage operation in MountEmulatedStorage method.
1723 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1724
1725 // See storage config details at http://source.android.com/tech/storage/
1726 // Create private mount namespace shared by all children
1727 if (unshare(CLONE_NEWNS) == -1) {
1728 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1729 return;
1730 }
1731
1732 // Mark rootfs as being a slave so that changes from default
1733 // namespace only flow into our children.
1734 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1735 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1736 return;
1737 }
1738
1739 // Create a staging tmpfs that is shared by our children; they will
1740 // bind mount storage into their respective private namespaces, which
1741 // are isolated from each other.
1742 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1743 if (target_base != nullptr) {
1744#define STRINGIFY_UID(x) __STRING(x)
1745 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1746 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1747 ALOGE("Failed to mount tmpfs to %s", target_base);
1748 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1749 return;
1750 }
1751#undef STRINGIFY_UID
1752 }
doheon1.lee885b7422016-01-20 13:07:27 +09001753
1754 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001755}
1756
Martijn Coenen86f08a52019-01-03 16:23:01 +01001757static void com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(
1758 JNIEnv* env, jclass, jint uidGidMin, jint uidGidMax) {
1759 if (!g_is_security_enforced) {
1760 ALOGI("seccomp disabled by setenforce 0");
1761 return;
1762 }
1763
Martijn Coenen86f08a52019-01-03 16:23:01 +01001764 bool installed = install_setuidgid_seccomp_filter(uidGidMin, uidGidMax);
1765 if (!installed) {
1766 RuntimeAbort(env, __LINE__, "Could not install setuid/setgid seccomp filter.");
1767 }
Martijn Coenen86f08a52019-01-03 16:23:01 +01001768}
1769
Chris Wailesaa1c9622019-01-10 16:55:32 -08001770/**
1771 * Called from a blastula to specialize the process for a specific application.
1772 *
1773 * @param env Managed runtime environment
1774 * @param uid User ID of the new application
1775 * @param gid Group ID of the new application
1776 * @param gids Extra groups that the process belongs to
1777 * @param runtime_flags Flags for changing the behavior of the managed runtime
1778 * @param rlimits Resource limits
1779 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
1780 * @param se_info SELinux policy information
1781 * @param nice_name New name for this process
1782 * @param is_child_zygote If the process is to become a WebViewZygote
1783 * @param instruction_set The instruction set expected/requested by the new application
1784 * @param app_data_dir Path to the application's data directory
1785 */
1786static void com_android_internal_os_Zygote_nativeSpecializeBlastula(
1787 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
1788 jint runtime_flags, jobjectArray rlimits,
1789 jint mount_external, jstring se_info, jstring nice_name,
1790 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001791 jstring package_name, jobjectArray packages_for_uid, jobjectArray visible_vol_ids,
1792 jstring sandbox_id) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001793 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
1794
1795 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1796 capabilities, capabilities,
1797 mount_external, se_info, nice_name, false,
1798 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001799 package_name, packages_for_uid, visible_vol_ids, sandbox_id);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001800}
1801
1802/**
1803 * A helper method for fetching socket file descriptors that were opened by init from the
1804 * environment.
1805 *
1806 * @param env Managed runtime environment
1807 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
1808 * of the environment variable storing the file descriptors.
1809 */
1810static void com_android_internal_os_Zygote_nativeGetSocketFDs(JNIEnv* env, jclass,
1811 jboolean is_primary) {
1812 std::string android_socket_prefix(ANDROID_SOCKET_PREFIX);
1813 std::string env_var_name = android_socket_prefix + (is_primary ? "zygote" : "zygote_secondary");
1814 char* env_var_val = getenv(env_var_name.c_str());
1815
1816 if (env_var_val != nullptr) {
1817 gZygoteSocketFD = atoi(env_var_val);
1818 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
1819 } else {
1820 ALOGE("Unable to fetch Zygote socket file descriptor");
1821 }
1822
1823 env_var_name = android_socket_prefix + (is_primary ? "blastula_pool" : "blastula_pool_secondary");
1824 env_var_val = getenv(env_var_name.c_str());
1825
1826 if (env_var_val != nullptr) {
1827 gBlastulaPoolSocketFD = atoi(env_var_val);
1828 ALOGV("Zygote:blastulaPoolSocketFD = %d", gBlastulaPoolSocketFD);
1829 } else {
1830 ALOGE("Unable to fetch Blastula pool socket file descriptor");
1831 }
1832}
1833
1834/**
1835 * @param env Managed runtime environment
1836 * @return A managed array of raw file descriptors for the read ends of the blastula reporting
1837 * pipes.
1838 */
1839static jintArray com_android_internal_os_Zygote_nativeGetBlastulaPipeFDs(JNIEnv* env, jclass) {
1840 std::vector<int> blastula_fds = MakeBlastulaPipeReadFDVector();
1841
1842 jintArray managed_blastula_fds = env->NewIntArray(blastula_fds.size());
1843 env->SetIntArrayRegion(managed_blastula_fds, 0, blastula_fds.size(), blastula_fds.data());
1844
1845 return managed_blastula_fds;
1846}
1847
1848/**
1849 * A JNI wrapper around RemoveBlastulaTableEntry.
1850 *
1851 * @param env Managed runtime environment
1852 * @param blastula_pid Process ID of the blastula entry to invalidate
1853 * @return True if an entry was invalidated; false otherwise.
1854 */
1855static jboolean com_android_internal_os_Zygote_nativeRemoveBlastulaTableEntry(JNIEnv* env, jclass,
1856 jint blastula_pid) {
1857 return RemoveBlastulaTableEntry(blastula_pid);
1858}
1859
1860/**
1861 * Creates the blastula pool event FD if it doesn't exist and returns it. This is used by the
1862 * ZygoteServer poll loop to know when to re-fill the blastula pool.
1863 *
1864 * @param env Managed runtime environment
1865 * @return A raw event file descriptor used to communicate (from the signal handler) when the
1866 * Zygote receives a SIGCHLD for a blastula
1867 */
1868static jint com_android_internal_os_Zygote_nativeGetBlastulaPoolEventFD(JNIEnv* env, jclass) {
1869 if (gBlastulaPoolEventFD == -1) {
1870 if ((gBlastulaPoolEventFD = eventfd(0, 0)) == -1) {
1871 ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
1872 }
1873 }
1874
1875 return gBlastulaPoolEventFD;
1876}
1877
1878/**
1879 * @param env Managed runtime environment
1880 * @return The number of blastulas currently in the blastula pool
1881 */
1882static jint com_android_internal_os_Zygote_nativeGetBlastulaPoolCount(JNIEnv* env, jclass) {
1883 return gBlastulaPoolCount;
1884}
1885
Daniel Micay76f6a862015-09-19 17:31:01 -04001886static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001887 { "nativeSecurityInit", "()V",
1888 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001889 { "nativeForkAndSpecialize",
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001890 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001891 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1892 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001893 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001894 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1895 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001896 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001897 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1898 { "nativePreApplicationInit", "()V",
Martijn Coenen86f08a52019-01-03 16:23:01 +01001899 (void *) com_android_internal_os_Zygote_nativePreApplicationInit },
1900 { "nativeInstallSeccompUidGidFilter", "(II)V",
Chris Wailesaa1c9622019-01-10 16:55:32 -08001901 (void *) com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter },
1902 { "nativeForkBlastula", "(II[I)I",
1903 (void *) com_android_internal_os_Zygote_nativeForkBlastula },
1904 { "nativeSpecializeBlastula",
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001905 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V",
Chris Wailesaa1c9622019-01-10 16:55:32 -08001906 (void *) com_android_internal_os_Zygote_nativeSpecializeBlastula },
1907 { "nativeGetSocketFDs", "(Z)V",
1908 (void *) com_android_internal_os_Zygote_nativeGetSocketFDs },
1909 { "nativeGetBlastulaPipeFDs", "()[I",
1910 (void *) com_android_internal_os_Zygote_nativeGetBlastulaPipeFDs },
1911 { "nativeRemoveBlastulaTableEntry", "(I)Z",
1912 (void *) com_android_internal_os_Zygote_nativeRemoveBlastulaTableEntry },
1913 { "nativeGetBlastulaPoolEventFD", "()I",
1914 (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolEventFD },
1915 { "nativeGetBlastulaPoolCount", "()I",
1916 (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolCount }
Narayan Kamath973b4662014-03-31 13:41:26 +01001917};
1918
1919int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001920 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001921 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1922 "callPostForkSystemServerHooks",
1923 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001924 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001925 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001926
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001927 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001928}
1929} // namespace android