blob: 3d3203ed72dc6dc83139e55ecf5693ec6e402c6b [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"
Jeff Sharkey853e53e2019-03-18 14:35:08 -060027#define ATRACE_TAG ATRACE_TAG_DALVIK
Narayan Kamath973b4662014-03-31 13:41:26 +010028
wangmingming16d0dd1a2018-11-14 10:43:36 +080029#include <async_safe/log.h>
30
Narayan Kamath973b4662014-03-31 13:41:26 +010031// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
32#include <sys/mount.h>
33#include <linux/fs.h>
34
Chris Wailesaa1c9622019-01-10 16:55:32 -080035#include <array>
36#include <atomic>
Chris Wailesaf594fc2018-11-02 11:00:07 -070037#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070038#include <list>
Chris Wailesaf594fc2018-11-02 11:00:07 -070039#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080040#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070041#include <string>
Chris Wailesaa1c9622019-01-10 16:55:32 -080042#include <string_view>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070043
Josh Gaod7951102018-06-26 16:05:12 -070044#include <android/fdsan.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080045#include <arpa/inet.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070046#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080047#include <grp.h>
48#include <inttypes.h>
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -070049#include <link.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070050#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070051#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010052#include <paths.h>
53#include <signal.h>
54#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070055#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040056#include <sys/cdefs.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080057#include <sys/eventfd.h>
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -070058#include <sys/mman.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070059#include <sys/personality.h>
60#include <sys/prctl.h>
61#include <sys/resource.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080062#include <sys/socket.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070063#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070064#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070065#include <sys/types.h>
66#include <sys/utsname.h>
67#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080068#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070069
Chris Wailesaa1c9622019-01-10 16:55:32 -080070#include <android-base/logging.h>
Minchan Kim5fa8af22018-06-27 11:32:40 +090071#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080072#include <android-base/file.h>
73#include <android-base/stringprintf.h>
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -070074#include <android-base/strings.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080075#include <android-base/unique_fd.h>
Christopher Ferrisc00c1cf2019-04-09 16:42:32 -070076#include <bionic_malloc.h>
Tim Murraycde0ac72019-04-04 09:19:03 -070077#include <cutils/ashmem.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070078#include <cutils/fs.h>
79#include <cutils/multiuser.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070080#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070081#include <utils/String8.h>
Jeff Sharkey853e53e2019-03-18 14:35:08 -060082#include <utils/Trace.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070083#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080084#include <seccomp_policy.h>
Howard Ro27330412018-10-02 12:08:28 -070085#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070086#include <processgroup/processgroup.h>
Suren Baghdasaryane4433262019-01-04 12:16:57 -080087#include <processgroup/sched_policy.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070088
Andreas Gampeed6b9df2014-11-20 22:02:20 -080089#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070090#include <nativehelper/JNIHelp.h>
91#include <nativehelper/ScopedLocalRef.h>
92#include <nativehelper/ScopedPrimitiveArray.h>
93#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050094#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010095
jgu212eacd062014-09-10 06:55:07 -040096#include "nativebridge/native_bridge.h"
97
Narayan Kamath973b4662014-03-31 13:41:26 +010098namespace {
99
Chris Wailesaa1c9622019-01-10 16:55:32 -0800100// TODO (chriswailes): Add a function to initialize native Zygote data.
101// TODO (chriswailes): Fix mixed indentation style (2 and 4 spaces).
102
Chris Wailesaf594fc2018-11-02 11:00:07 -0700103using namespace std::placeholders;
104
Narayan Kamath973b4662014-03-31 13:41:26 +0100105using android::String8;
Sudheer Shanka663b1042018-07-30 17:34:21 -0700106using android::base::StringAppendF;
Carmen Jacksondd401252017-02-23 15:21:10 -0800107using android::base::StringPrintf;
108using android::base::WriteStringToFile;
Minchan Kim5fa8af22018-06-27 11:32:40 +0900109using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +0100110
Andreas Gamped5758f62018-03-12 12:08:55 -0700111#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
112 append(StringPrintf(__VA_ARGS__))
113
Chris Wailesaa1c9622019-01-10 16:55:32 -0800114// This type is duplicated in fd_utils.h
115typedef const std::function<void(std::string)>& fail_fn_t;
116
Narayan Kamath973b4662014-03-31 13:41:26 +0100117static pid_t gSystemServerPid = 0;
118
Sudheer Shanka663b1042018-07-30 17:34:21 -0700119static const char kIsolatedStorage[] = "persist.sys.isolated_storage";
Sudheer Shankaa3801582019-01-17 17:19:11 -0800120static const char kIsolatedStorageSnapshot[] = "sys.isolated_storage_snapshot";
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700121
122static constexpr const char* kZygoteClassName = "com/android/internal/os/Zygote";
Narayan Kamath973b4662014-03-31 13:41:26 +0100123static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +0100124static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +0100125static jmethodID gCallPostForkChildHooks;
126
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700127static constexpr const char* kZygoteInitClassName = "com/android/internal/os/ZygoteInit";
128static jclass gZygoteInitClass;
129static jmethodID gCreateSystemServerClassLoader;
130
Chris Wailes6d482d542019-04-03 13:00:52 -0700131static bool gIsSecurityEnforced = true;
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800132
Chris Wailesaa1c9622019-01-10 16:55:32 -0800133/**
134 * The maximum number of characters (not including a null terminator) that a
135 * process name may contain.
136 */
137static constexpr size_t MAX_NAME_LENGTH = 15;
138
139/**
140 * The prefix string for environmental variables storing socket FDs created by
141 * init.
142 */
143
144static constexpr std::string_view ANDROID_SOCKET_PREFIX("ANDROID_SOCKET_");
145
146/**
147 * The file descriptor for the Zygote socket opened by init.
148 */
149
150static int gZygoteSocketFD = -1;
151
152/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800153 * The file descriptor for the unspecialized app process (USAP) pool socket opened by init.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800154 */
155
Chris Wailes7e797b62019-02-22 18:29:22 -0800156static int gUsapPoolSocketFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800157
158/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800159 * The number of USAPs currently in this Zygote's pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800160 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800161static std::atomic_uint32_t gUsapPoolCount = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800162
163/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800164 * Event file descriptor used to communicate reaped USAPs to the
Chris Wailesaa1c9622019-01-10 16:55:32 -0800165 * ZygoteServer.
166 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800167static int gUsapPoolEventFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800168
169/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800170 * The maximum value that the gUSAPPoolSizeMax variable may take. This value
171 * is a mirror of ZygoteServer.USAP_POOL_SIZE_MAX_LIMIT
Chris Wailesaa1c9622019-01-10 16:55:32 -0800172 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800173static constexpr int USAP_POOL_SIZE_MAX_LIMIT = 100;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800174
175/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800176 * A helper class containing accounting information for USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800177 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800178class UsapTableEntry {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800179 public:
180 struct EntryStorage {
181 int32_t pid;
182 int32_t read_pipe_fd;
183
184 bool operator!=(const EntryStorage& other) {
185 return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
186 }
187 };
188
189 private:
190 static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
191
192 std::atomic<EntryStorage> mStorage;
193 static_assert(decltype(mStorage)::is_always_lock_free);
194
195 public:
Chris Wailes7e797b62019-02-22 18:29:22 -0800196 constexpr UsapTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
Chris Wailesaa1c9622019-01-10 16:55:32 -0800197
198 /**
199 * If the provided PID matches the one stored in this entry, the entry will
200 * be invalidated and the associated file descriptor will be closed. If the
201 * PIDs don't match nothing will happen.
202 *
203 * @param pid The ID of the process who's entry we want to clear.
204 * @return True if the entry was cleared; false otherwise
205 */
206 bool ClearForPID(int32_t pid) {
207 EntryStorage storage = mStorage.load();
208
209 if (storage.pid == pid) {
210 /*
211 * There are three possible outcomes from this compare-and-exchange:
212 * 1) It succeeds, in which case we close the FD
213 * 2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
214 * the entry has already been cleared.
215 * 3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
216 * case the entry has already been cleared and re-used.
217 *
218 * In all three cases the goal of the caller has been met and we can
219 * return true.
220 */
221 if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
222 close(storage.read_pipe_fd);
223 }
224
225 return true;
226 } else {
227 return false;
228 }
229 }
230
Chris Wailesae937142019-01-24 12:57:33 -0800231 void Clear() {
Chris Wailesdb132a32019-02-20 10:49:27 -0800232 EntryStorage storage = mStorage.load();
233
234 if (storage != INVALID_ENTRY_VALUE) {
235 close(storage.read_pipe_fd);
236 mStorage.store(INVALID_ENTRY_VALUE);
237 }
238 }
239
240 void Invalidate() {
Chris Wailesae937142019-01-24 12:57:33 -0800241 mStorage.store(INVALID_ENTRY_VALUE);
242 }
243
Chris Wailesaa1c9622019-01-10 16:55:32 -0800244 /**
245 * @return A copy of the data stored in this entry.
246 */
247 std::optional<EntryStorage> GetValues() {
248 EntryStorage storage = mStorage.load();
249
250 if (storage != INVALID_ENTRY_VALUE) {
251 return storage;
252 } else {
253 return std::nullopt;
254 }
255 }
256
257 /**
258 * Sets the entry to the given values if it is currently invalid.
259 *
260 * @param pid The process ID for the new entry.
Chris Wailes7e797b62019-02-22 18:29:22 -0800261 * @param read_pipe_fd The read end of the USAP control pipe for this
Chris Wailesaa1c9622019-01-10 16:55:32 -0800262 * process.
263 * @return True if the entry was set; false otherwise.
264 */
265 bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
266 EntryStorage new_value_storage;
267
268 new_value_storage.pid = pid;
269 new_value_storage.read_pipe_fd = read_pipe_fd;
270
271 EntryStorage expected = INVALID_ENTRY_VALUE;
272
273 return mStorage.compare_exchange_strong(expected, new_value_storage);
274 }
275};
276
277/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800278 * A table containing information about the USAPs currently in the pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800279 *
280 * Multiple threads may be attempting to modify the table, either from the
281 * signal handler or from the ZygoteServer poll loop. Atomic loads/stores in
Chris Wailes7e797b62019-02-22 18:29:22 -0800282 * the USAPTableEntry class prevent data races during these concurrent
Chris Wailesaa1c9622019-01-10 16:55:32 -0800283 * operations.
284 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800285static std::array<UsapTableEntry, USAP_POOL_SIZE_MAX_LIMIT> gUsapTable;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800286
287/**
288 * The list of open zygote file descriptors.
289 */
290static FileDescriptorTable* gOpenFdTable = nullptr;
291
Narayan Kamath973b4662014-03-31 13:41:26 +0100292// Must match values in com.android.internal.os.Zygote.
293enum MountExternalKind {
294 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700295 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700296 MOUNT_EXTERNAL_READ = 2,
297 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800298 MOUNT_EXTERNAL_LEGACY = 4,
299 MOUNT_EXTERNAL_INSTALLER = 5,
300 MOUNT_EXTERNAL_FULL = 6,
Narayan Kamath973b4662014-03-31 13:41:26 +0100301};
302
Orion Hodson8d005a62018-12-05 12:28:53 +0000303// Must match values in com.android.internal.os.Zygote.
304enum RuntimeFlags : uint32_t {
305 DEBUG_ENABLE_JDWP = 1,
Yabin Cui4d8546d2019-01-29 16:29:20 -0800306 PROFILE_FROM_SHELL = 1 << 15,
Orion Hodson8d005a62018-12-05 12:28:53 +0000307};
308
Chris Wailesaa1c9622019-01-10 16:55:32 -0800309// Forward declaration so we don't have to move the signal handler.
Chris Wailes7e797b62019-02-22 18:29:22 -0800310static bool RemoveUsapTableEntry(pid_t usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800311
Andreas Gampeb053cce2015-11-17 16:38:59 -0800312static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
313 std::ostringstream oss;
314 oss << __FILE__ << ":" << line << ": " << msg;
315 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100316}
317
318// This signal handler is for zygote mode, since the zygote must reap its children
319static void SigChldHandler(int /*signal_number*/) {
320 pid_t pid;
321 int status;
Chris Wailes7e797b62019-02-22 18:29:22 -0800322 int64_t usaps_removed = 0;
Narayan Kamath973b4662014-03-31 13:41:26 +0100323
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700324 // It's necessary to save and restore the errno during this function.
325 // Since errno is stored per thread, changing it here modifies the errno
326 // on the thread on which this signal handler executes. If a signal occurs
327 // between a call and an errno check, it's possible to get the errno set
328 // here.
329 // See b/23572286 for extra information.
330 int saved_errno = errno;
331
Narayan Kamath973b4662014-03-31 13:41:26 +0100332 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800333 // Log process-death status that we care about.
Narayan Kamath973b4662014-03-31 13:41:26 +0100334 if (WIFEXITED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800335 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
336 "Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100337 } else if (WIFSIGNALED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800338 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
339 "Process %d exited due to signal %d (%s)%s", pid,
340 WTERMSIG(status), strsignal(WTERMSIG(status)),
341 WCOREDUMP(status) ? "; core dumped" : "");
Narayan Kamath973b4662014-03-31 13:41:26 +0100342 }
343
344 // If the just-crashed process is the system_server, bring down zygote
345 // so that it is restarted by init and system server will be restarted
346 // from there.
347 if (pid == gSystemServerPid) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800348 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
349 "Exit zygote because system server (pid %d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100350 kill(getpid(), SIGKILL);
351 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800352
Chris Wailes7e797b62019-02-22 18:29:22 -0800353 // Check to see if the PID is in the USAP pool and remove it if it is.
354 if (RemoveUsapTableEntry(pid)) {
355 ++usaps_removed;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800356 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100357 }
358
Narayan Kamath160992d2014-04-14 14:46:07 +0100359 // Note that we shouldn't consider ECHILD an error because
360 // the secondary zygote might have no children left to wait for.
361 if (pid < 0 && errno != ECHILD) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800362 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG,
363 "Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100364 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700365
Chris Wailes7e797b62019-02-22 18:29:22 -0800366 if (usaps_removed > 0) {
Chris Wailesfe3a3482019-03-13 14:38:04 -0700367 if (TEMP_FAILURE_RETRY(write(gUsapPoolEventFD, &usaps_removed, sizeof(usaps_removed))) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800368 // If this write fails something went terribly wrong. We will now kill
369 // the zygote and let the system bring it back up.
wangmingming16d0dd1a2018-11-14 10:43:36 +0800370 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
Chris Wailes7e797b62019-02-22 18:29:22 -0800371 "Zygote failed to write to USAP pool event FD: %s",
wangmingming16d0dd1a2018-11-14 10:43:36 +0800372 strerror(errno));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800373 kill(getpid(), SIGKILL);
374 }
375 }
376
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700377 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100378}
379
yuanhao435e84b2018-01-15 15:37:02 +0800380// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
381// configured very late, because earlier in the runtime we may fork() and
382// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100383// have them be harvested immediately.
384//
yuanhao435e84b2018-01-15 15:37:02 +0800385// Ignore SIGHUP because all processes forked by the zygote are in the same
386// process group as the zygote and we don't want to be notified if we become
387// an orphaned group and have one or more stopped processes. This is not a
388// theoretical concern :
389// - we can become an orphaned group if one of our direct descendants forks
390// and is subsequently killed before its children.
391// - crash_dump routinely STOPs the process it's tracing.
392//
393// See issues b/71965619 and b/25567761 for further details.
394//
Narayan Kamath973b4662014-03-31 13:41:26 +0100395// This ends up being called repeatedly before each fork(), but there's
396// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800397static void SetSignalHandlers() {
398 struct sigaction sig_chld = {};
399 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100400
Chris Wailesaa1c9622019-01-10 16:55:32 -0800401 if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700402 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100403 }
yuanhao435e84b2018-01-15 15:37:02 +0800404
405 struct sigaction sig_hup = {};
406 sig_hup.sa_handler = SIG_IGN;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800407 if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
yuanhao435e84b2018-01-15 15:37:02 +0800408 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
409 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100410}
411
412// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800413static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100414 struct sigaction sa;
415 memset(&sa, 0, sizeof(sa));
416 sa.sa_handler = SIG_DFL;
417
Chris Wailesaa1c9622019-01-10 16:55:32 -0800418 if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700419 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100420 }
421}
422
423// Calls POSIX setgroups() using the int[] object as an argument.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800424// A nullptr argument is tolerated.
425static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) {
426 if (managed_gids == nullptr) {
427 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100428 }
429
Chris Wailesaa1c9622019-01-10 16:55:32 -0800430 ScopedIntArrayRO gids(env, managed_gids);
431 if (gids.get() == nullptr) {
432 fail_fn(CREATE_ERROR("Getting gids int array failed"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100433 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700434
Chris Wailesaa1c9622019-01-10 16:55:32 -0800435 if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
436 fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
437 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100438}
439
440// Sets the resource limits via setrlimit(2) for the values in the
441// two-dimensional array of integers that's passed in. The second dimension
Chris Wailesaa1c9622019-01-10 16:55:32 -0800442// contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
Narayan Kamath973b4662014-03-31 13:41:26 +0100443// treated as an empty array.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800444static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
445 if (managed_rlimits == nullptr) {
446 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100447 }
448
449 rlimit rlim;
450 memset(&rlim, 0, sizeof(rlim));
451
Chris Wailesaa1c9622019-01-10 16:55:32 -0800452 for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
453 ScopedLocalRef<jobject>
454 managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
455 ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
456
457 if (rlimit_handle.size() != 3) {
458 fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100459 }
460
Chris Wailesaa1c9622019-01-10 16:55:32 -0800461 rlim.rlim_cur = rlimit_handle[1];
462 rlim.rlim_max = rlimit_handle[2];
Narayan Kamath973b4662014-03-31 13:41:26 +0100463
Chris Wailesaa1c9622019-01-10 16:55:32 -0800464 if (setrlimit(rlimit_handle[0], &rlim) == -1) {
465 fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
466 rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
Narayan Kamath973b4662014-03-31 13:41:26 +0100467 }
468 }
469}
470
Orion Hodson8d005a62018-12-05 12:28:53 +0000471static void EnableDebugger() {
472 // To let a non-privileged gdbserver attach to this
473 // process, we must set our dumpable flag.
474 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
475 ALOGE("prctl(PR_SET_DUMPABLE) failed");
476 }
477
478 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
479 // is enabled (see kernel/Documentation/security/Yama.txt).
480 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
481 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
482 // case since it's expected behaviour.
483 if (errno != EINVAL) {
484 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
485 }
486 }
487
Orion Hodson2b71ad02018-12-07 16:44:33 +0000488 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
489 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
490 // Set the soft limit on core dump size to 0 without changing the hard limit.
491 rlimit rl;
492 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
493 ALOGE("getrlimit(RLIMIT_CORE) failed");
494 } else {
495 rl.rlim_cur = 0;
496 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
497 ALOGE("setrlimit(RLIMIT_CORE) failed");
498 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000499 }
500 }
501}
502
Christopher Ferris76de39e2017-06-20 16:13:40 -0700503static void PreApplicationInit() {
504 // The child process sets this to indicate it's not the zygote.
Christopher Ferrisc00c1cf2019-04-09 16:42:32 -0700505 android_mallopt(M_SET_ZYGOTE_CHILD, nullptr, 0);
Christopher Ferris76de39e2017-06-20 16:13:40 -0700506
507 // Set the jemalloc decay time to 1.
508 mallopt(M_DECAY_TIME, 1);
509}
510
Martijn Coenen86f08a52019-01-03 16:23:01 +0100511static void SetUpSeccompFilter(uid_t uid, bool is_child_zygote) {
Chris Wailes6d482d542019-04-03 13:00:52 -0700512 if (!gIsSecurityEnforced) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800513 ALOGI("seccomp disabled by setenforce 0");
514 return;
515 }
516
517 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700518 if (uid >= AID_APP_START) {
Martijn Coenen86f08a52019-01-03 16:23:01 +0100519 if (is_child_zygote) {
Martijn Coenen6ef16802019-01-18 16:40:01 +0100520 set_app_zygote_seccomp_filter();
Martijn Coenen86f08a52019-01-03 16:23:01 +0100521 } else {
522 set_app_seccomp_filter();
523 }
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800524 } else {
525 set_system_seccomp_filter();
526 }
527}
528
Chris Wailesaa1c9622019-01-10 16:55:32 -0800529static void EnableKeepCapabilities(fail_fn_t fail_fn) {
530 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
531 fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100532 }
533}
534
Chris Wailesaa1c9622019-01-10 16:55:32 -0800535static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
536 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
537 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100538 if (errno == EINVAL) {
539 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
540 "your kernel is compiled with file capabilities support");
541 } else {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800542 fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100543 }
544 }
545 }
546}
547
Chris Wailesaa1c9622019-01-10 16:55:32 -0800548static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
Josh Gao45dab782017-02-01 14:56:09 -0800549 __user_cap_header_struct capheader;
550 memset(&capheader, 0, sizeof(capheader));
551 capheader.version = _LINUX_CAPABILITY_VERSION_3;
552 capheader.pid = 0;
553
554 __user_cap_data_struct capdata[2];
555 if (capget(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800556 fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800557 }
558
559 capdata[0].inheritable = inheritable;
560 capdata[1].inheritable = inheritable >> 32;
561
562 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800563 fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800564 }
565}
566
Chris Wailesaa1c9622019-01-10 16:55:32 -0800567static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
568 fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100569 __user_cap_header_struct capheader;
570 memset(&capheader, 0, sizeof(capheader));
571 capheader.version = _LINUX_CAPABILITY_VERSION_3;
572 capheader.pid = 0;
573
574 __user_cap_data_struct capdata[2];
575 memset(&capdata, 0, sizeof(capdata));
576 capdata[0].effective = effective;
577 capdata[1].effective = effective >> 32;
578 capdata[0].permitted = permitted;
579 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800580 capdata[0].inheritable = inheritable;
581 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100582
583 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800584 fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
585 "failed: %s", permitted, effective, inheritable, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100586 }
587}
588
Chris Wailesaa1c9622019-01-10 16:55:32 -0800589static void SetSchedulerPolicy(fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100590 errno = -set_sched_policy(0, SP_DEFAULT);
591 if (errno != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800592 fail_fn(CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100593 }
594}
595
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700596static int UnmountTree(const char* path) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600597 ATRACE_CALL();
598
Sudheer Shanka74584a52019-02-22 13:04:41 -0800599 size_t path_len = strlen(path);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700600
Sudheer Shanka74584a52019-02-22 13:04:41 -0800601 FILE* fp = setmntent("/proc/mounts", "r");
602 if (fp == nullptr) {
603 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
604 return -errno;
605 }
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700606
Sudheer Shanka74584a52019-02-22 13:04:41 -0800607 // Some volumes can be stacked on each other, so force unmount in
608 // reverse order to give us the best chance of success.
609 std::list<std::string> to_unmount;
610 mntent* mentry;
611 while ((mentry = getmntent(fp)) != nullptr) {
612 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
613 to_unmount.push_front(std::string(mentry->mnt_dir));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700614 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800615 }
616 endmntent(fp);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700617
Sudheer Shanka74584a52019-02-22 13:04:41 -0800618 for (const auto& path : to_unmount) {
619 if (umount2(path.c_str(), MNT_DETACH)) {
620 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700621 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800622 }
623 return 0;
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700624}
625
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800626static void CreateDir(const std::string& dir,
627 mode_t mode, uid_t uid, gid_t gid,
628 fail_fn_t fail_fn) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800629 if (TEMP_FAILURE_RETRY(access(dir.c_str(), F_OK)) == 0) {
630 return;
631 } else if (errno != ENOENT) {
632 fail_fn(CREATE_ERROR("Failed to stat %s: %s", dir.c_str(), strerror(errno)));
633 }
634 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
635 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s: %s",
636 dir.c_str(), strerror(errno)));
637 }
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800638}
639
Sudheer Shanka74584a52019-02-22 13:04:41 -0800640static void CreatePkgSandboxTarget(userid_t user_id, fail_fn_t fail_fn) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600641 ATRACE_CALL();
642
Sudheer Shanka74584a52019-02-22 13:04:41 -0800643 // Create /mnt/user/0/package
644 std::string pkg_sandbox_dir = StringPrintf("/mnt/user/%d", user_id);
645 CreateDir(pkg_sandbox_dir, 0751, AID_ROOT, AID_ROOT, fail_fn);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800646
Sudheer Shanka74584a52019-02-22 13:04:41 -0800647 StringAppendF(&pkg_sandbox_dir, "/package");
648 CreateDir(pkg_sandbox_dir, 0755, AID_ROOT, AID_ROOT, fail_fn);
Sudheer Shanka663b1042018-07-30 17:34:21 -0700649}
650
Sudheer Shanka74584a52019-02-22 13:04:41 -0800651static void BindMount(const std::string& source_dir, const std::string& target_dir,
Chris Wailesaa1c9622019-01-10 16:55:32 -0800652 fail_fn_t fail_fn) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800653 if (TEMP_FAILURE_RETRY(mount(source_dir.c_str(), target_dir.c_str(), nullptr,
654 MS_BIND, nullptr)) == -1) {
655 fail_fn(CREATE_ERROR("Failed to mount %s to %s: %s",
656 source_dir.c_str(), target_dir.c_str(), strerror(errno)));
657 }
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800658}
659
Sudheer Shanka74584a52019-02-22 13:04:41 -0800660static void MountPkgSpecificDir(const std::string& mnt_source_root,
661 const std::string& mnt_target_root,
662 const std::string& package_name,
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800663 uid_t uid,
Sudheer Shanka74584a52019-02-22 13:04:41 -0800664 const char* dir_name,
Chris Wailesaa1c9622019-01-10 16:55:32 -0800665 fail_fn_t fail_fn) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600666 ATRACE_CALL();
667
Sudheer Shanka74584a52019-02-22 13:04:41 -0800668 std::string mnt_source_dir = StringPrintf("%s/Android/%s/%s",
669 mnt_source_root.c_str(), dir_name, package_name.c_str());
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800670
Sudheer Shanka74584a52019-02-22 13:04:41 -0800671 std::string mnt_target_dir = StringPrintf("%s/Android/%s/%s",
672 mnt_target_root.c_str(), dir_name, package_name.c_str());
Chris Wailesaa1c9622019-01-10 16:55:32 -0800673
Sudheer Shanka74584a52019-02-22 13:04:41 -0800674 BindMount(mnt_source_dir, mnt_target_dir, fail_fn);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700675}
676
Sudheer Shanka74584a52019-02-22 13:04:41 -0800677static void CreateSubDirs(int parent_fd, const std::string& parent_path,
678 const std::vector<std::string>& sub_dirs,
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000679 fail_fn_t fail_fn) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600680 ATRACE_CALL();
681
Sudheer Shanka74584a52019-02-22 13:04:41 -0800682 for (auto& dir_name : sub_dirs) {
683 struct stat sb;
684 if (TEMP_FAILURE_RETRY(fstatat(parent_fd, dir_name.c_str(), &sb, 0)) == 0) {
685 if (S_ISDIR(sb.st_mode)) {
686 continue;
687 } else if (TEMP_FAILURE_RETRY(unlinkat(parent_fd, dir_name.c_str(), 0)) == -1) {
688 fail_fn(CREATE_ERROR("Failed to unlinkat on %s/%s: %s",
689 parent_path.c_str(), dir_name.c_str(), strerror(errno)));
690 }
691 } else if (errno != ENOENT) {
692 fail_fn(CREATE_ERROR("Failed to fstatat on %s/%s: %s",
693 parent_path.c_str(), dir_name.c_str(), strerror(errno)));
Sudheer Shankad8b4f102019-02-12 19:01:21 -0800694 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800695 if (TEMP_FAILURE_RETRY(mkdirat(parent_fd, dir_name.c_str(), 0700)) == -1 && errno != EEXIST) {
696 fail_fn(CREATE_ERROR("Failed to mkdirat on %s/%s: %s",
697 parent_path.c_str(), dir_name.c_str(), strerror(errno)));
698 }
699 }
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000700}
701
702static void EnsurePkgSpecificDirs(const std::string& path,
Sudheer Shanka74584a52019-02-22 13:04:41 -0800703 const std::vector<std::string>& package_names,
704 bool create_sandbox_dir,
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000705 fail_fn_t fail_fn) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600706 ATRACE_CALL();
707
Sudheer Shanka74584a52019-02-22 13:04:41 -0800708 std::string android_dir = StringPrintf("%s/Android", path.c_str());
709 android::base::unique_fd android_fd(open(android_dir.c_str(),
710 O_RDONLY | O_DIRECTORY | O_CLOEXEC));
711 if (android_fd.get() < 0) {
712 if (errno == ENOENT || errno == ENOTDIR) {
713 if (errno == ENOTDIR && TEMP_FAILURE_RETRY(unlink(android_dir.c_str())) == -1) {
714 fail_fn(CREATE_ERROR("Failed to unlink %s: %s",
715 android_dir.c_str(), strerror(errno)));
716 }
717 if (TEMP_FAILURE_RETRY(mkdir(android_dir.c_str(), 0700)) == -1
718 && errno != EEXIST) {
Sudheer Shankac8cd0c12019-02-14 19:09:48 +0000719 fail_fn(CREATE_ERROR("Failed to mkdir %s: %s",
Sudheer Shanka74584a52019-02-22 13:04:41 -0800720 android_dir.c_str(), strerror(errno)));
721 }
722 android_fd.reset(open(android_dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800723 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800724
725 if (android_fd.get() < 0) {
726 fail_fn(CREATE_ERROR("Failed to open %s: %s", android_dir.c_str(), strerror(errno)));
727 }
728 }
729
730 std::vector<std::string> data_media_obb_dirs = {"data", "media", "obb"};
731 if (create_sandbox_dir) {
732 data_media_obb_dirs.push_back("sandbox");
733 }
734 CreateSubDirs(android_fd.get(), android_dir, data_media_obb_dirs, fail_fn);
735 if (create_sandbox_dir) {
736 data_media_obb_dirs.pop_back();
737 }
738 for (auto& dir_name : data_media_obb_dirs) {
739 std::string data_dir = StringPrintf("%s/%s", android_dir.c_str(), dir_name.c_str());
740 android::base::unique_fd data_fd(openat(android_fd, dir_name.c_str(),
741 O_RDONLY | O_DIRECTORY | O_CLOEXEC));
742 if (data_fd.get() < 0) {
743 fail_fn(CREATE_ERROR("Failed to openat %s/%s: %s",
744 android_dir.c_str(), dir_name.c_str(), strerror(errno)));
745 }
746 CreateSubDirs(data_fd.get(), data_dir, package_names, fail_fn);
747 }
Sudheer Shanka932d51d2019-02-08 10:43:10 -0800748}
749
Sudheer Shanka74584a52019-02-22 13:04:41 -0800750static void CreatePkgSandboxSource(const std::string& sandbox_source, fail_fn_t fail_fn) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600751 ATRACE_CALL();
Chris Wailesaa1c9622019-01-10 16:55:32 -0800752
Sudheer Shanka74584a52019-02-22 13:04:41 -0800753 struct stat sb;
754 if (TEMP_FAILURE_RETRY(stat(sandbox_source.c_str(), &sb)) == 0) {
755 if (S_ISDIR(sb.st_mode)) {
756 return;
757 } else if (TEMP_FAILURE_RETRY(unlink(sandbox_source.c_str())) == -1) {
758 fail_fn(CREATE_ERROR("Failed to unlink %s: %s",
759 sandbox_source.c_str(), strerror(errno)));
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700760 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800761 } else if (errno != ENOENT) {
762 fail_fn(CREATE_ERROR("Failed to stat %s: %s",
763 sandbox_source.c_str(), strerror(errno)));
764 }
765 if (TEMP_FAILURE_RETRY(mkdir(sandbox_source.c_str(), 0700)) == -1 && errno != EEXIST) {
766 fail_fn(CREATE_ERROR("Failed to mkdir %s: %s",
767 sandbox_source.c_str(), strerror(errno)));
768 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700769}
770
Sudheer Shanka74584a52019-02-22 13:04:41 -0800771static void PreparePkgSpecificDirs(const std::vector<std::string>& package_names,
Sudheer Shanka74584a52019-02-22 13:04:41 -0800772 bool mount_all_obbs, const std::string& sandbox_id,
773 userid_t user_id, uid_t uid, fail_fn_t fail_fn) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600774 ATRACE_CALL();
775
Sudheer Shankae51005d2019-02-24 10:24:09 -0800776 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/storage"), closedir);
777 if (!dirp) {
778 fail_fn(CREATE_ERROR("Failed to opendir /storage: %s", strerror(errno)));
779 }
780 struct dirent* ent;
781 while ((ent = readdir(dirp.get()))) {
782 if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..") || !strcmp(ent->d_name, "self")) {
783 continue;
784 }
785 std::string label(ent->d_name);
786
Sudheer Shanka74584a52019-02-22 13:04:41 -0800787 std::string mnt_source = StringPrintf("/mnt/runtime/write/%s", label.c_str());
788 std::string mnt_target = StringPrintf("/storage/%s", label.c_str());
789 if (label == "emulated") {
790 StringAppendF(&mnt_source, "/%d", user_id);
791 StringAppendF(&mnt_target, "/%d", user_id);
792 }
793
794 if (TEMP_FAILURE_RETRY(access(mnt_source.c_str(), F_OK)) == -1) {
795 ALOGE("Can't access %s: %s", mnt_source.c_str(), strerror(errno));
796 continue;
797 } else if (TEMP_FAILURE_RETRY(access(mnt_target.c_str(), F_OK)) == -1) {
798 ALOGE("Can't access %s: %s", mnt_target.c_str(), strerror(errno));
799 continue;
800 }
801
802 // Ensure /mnt/runtime/write/emulated/0/Android/{data,media,obb}
803 EnsurePkgSpecificDirs(mnt_source, package_names, true, fail_fn);
804
805 std::string sandbox_source = StringPrintf("%s/Android/sandbox/%s",
806 mnt_source.c_str(), sandbox_id.c_str());
807 CreatePkgSandboxSource(sandbox_source, fail_fn);
808 BindMount(sandbox_source, mnt_target, fail_fn);
809
810 // Ensure /storage/emulated/0/Android/{data,media,obb}
811 EnsurePkgSpecificDirs(mnt_target, package_names, false, fail_fn);
812 for (auto& package : package_names) {
813 MountPkgSpecificDir(mnt_source, mnt_target, package, uid, "data", fail_fn);
814 MountPkgSpecificDir(mnt_source, mnt_target, package, uid, "media", fail_fn);
815 if (!mount_all_obbs) {
816 MountPkgSpecificDir(mnt_source, mnt_target, package, uid, "obb", fail_fn);
817 }
818 }
819
820 if (mount_all_obbs) {
821 StringAppendF(&mnt_source, "/Android/obb");
822 StringAppendF(&mnt_target, "/Android/obb");
823 BindMount(mnt_source, mnt_target, fail_fn);
824 }
825 }
826}
827
828static void HandleMountModeInstaller(int mount_mode,
829 userid_t user_id,
830 const std::string& sandbox_id,
Sudheer Shanka03b20ec2019-02-21 15:11:00 -0800831 fail_fn_t fail_fn) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600832 ATRACE_CALL();
833
Sudheer Shanka74584a52019-02-22 13:04:41 -0800834 std::string obb_mount_dir = StringPrintf("/mnt/user/%d/obb_mount", user_id);
835 std::string obb_mount_file = StringPrintf("%s/%s", obb_mount_dir.c_str(), sandbox_id.c_str());
836 if (mount_mode == MOUNT_EXTERNAL_INSTALLER) {
837 if (TEMP_FAILURE_RETRY(access(obb_mount_file.c_str(), F_OK)) != -1) {
838 return;
839 } else if (errno != ENOENT) {
840 fail_fn(CREATE_ERROR("Failed to access %s: %s", obb_mount_file.c_str(), strerror(errno)));
Sudheer Shanka03b20ec2019-02-21 15:11:00 -0800841 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800842 if (fs_prepare_dir(obb_mount_dir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
843 fail_fn(CREATE_ERROR("Failed to fs_prepare_dir %s: %s",
844 obb_mount_dir.c_str(), strerror(errno)));
845 }
846 const android::base::unique_fd fd(TEMP_FAILURE_RETRY(
847 open(obb_mount_file.c_str(), O_RDWR | O_CREAT, 0600)));
848 if (fd.get() < 0) {
849 fail_fn(CREATE_ERROR("Failed to create %s: %s", obb_mount_file.c_str(), strerror(errno)));
850 }
851 } else {
852 if (TEMP_FAILURE_RETRY(access(obb_mount_file.c_str(), F_OK)) != -1) {
853 if (TEMP_FAILURE_RETRY(unlink(obb_mount_file.c_str())) == -1) {
854 fail_fn(CREATE_ERROR("Failed to unlink %s: %s",
855 obb_mount_dir.c_str(), strerror(errno)));
856 }
857 } else if (errno != ENOENT) {
858 fail_fn(CREATE_ERROR("Failed to access %s: %s", obb_mount_file.c_str(), strerror(errno)));
859 }
860 }
Sudheer Shanka03b20ec2019-02-21 15:11:00 -0800861}
862
Narayan Kamath973b4662014-03-31 13:41:26 +0100863// Create a private mount namespace and bind mount appropriate emulated
864// storage for the given user.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800865static void MountEmulatedStorage(uid_t uid, jint mount_mode,
866 bool force_mount_namespace, const std::string& package_name,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700867 const std::vector<std::string>& packages_for_uid,
Sudheer Shankae51005d2019-02-24 10:24:09 -0800868 const std::string& sandbox_id,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800869 fail_fn_t fail_fn) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800870 // See storage config details at http://source.android.com/tech/storage/
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600871 ATRACE_CALL();
Jeff Sharkey9527b222015-06-24 15:24:48 -0700872
Sudheer Shanka74584a52019-02-22 13:04:41 -0800873 String8 storage_source;
874 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
875 storage_source = "/mnt/runtime/default";
876 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
877 storage_source = "/mnt/runtime/read";
Sudheer Shanka783c90e2019-04-12 13:55:20 -0700878 } else if (mount_mode == MOUNT_EXTERNAL_WRITE
879 || mount_mode == MOUNT_EXTERNAL_LEGACY
880 || mount_mode == MOUNT_EXTERNAL_INSTALLER) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800881 storage_source = "/mnt/runtime/write";
Sudheer Shanka783c90e2019-04-12 13:55:20 -0700882 } else if (mount_mode == MOUNT_EXTERNAL_FULL) {
883 storage_source = "/mnt/runtime/full";
Sudheer Shanka74584a52019-02-22 13:04:41 -0800884 } else if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
885 // Sane default of no storage visible
886 return;
887 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400888
Sudheer Shanka74584a52019-02-22 13:04:41 -0800889 // Create a second private mount namespace for our process
890 if (unshare(CLONE_NEWNS) == -1) {
891 fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
892 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400893
Sudheer Shanka74584a52019-02-22 13:04:41 -0800894 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
895 if (mount_mode == MOUNT_EXTERNAL_NONE) {
896 return;
897 }
Robert Sesek06f39302017-03-20 17:30:05 -0400898
Sudheer Shanka783c90e2019-04-12 13:55:20 -0700899 if (/* DISABLES CODE */ (false)
900 && GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, true))) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800901 if (mount_mode == MOUNT_EXTERNAL_FULL || mount_mode == MOUNT_EXTERNAL_LEGACY) {
902 storage_source = (mount_mode == MOUNT_EXTERNAL_FULL)
903 ? "/mnt/runtime/full" : "/mnt/runtime/write";
904 if (TEMP_FAILURE_RETRY(mount(storage_source.string(), "/storage",
905 NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
906 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
907 storage_source.string(),
908 strerror(errno)));
909 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700910
Sudheer Shanka74584a52019-02-22 13:04:41 -0800911 // Mount user-specific symlink helper into place
912 userid_t user_id = multiuser_get_user_id(uid);
913 const String8 user_source(String8::format("/mnt/user/%d", user_id));
914 if (fs_prepare_dir(user_source.string(), 0751, 0, 0) == -1) {
915 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s (%s)",
916 user_source.string(), strerror(errno)));
917 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800918
Sudheer Shanka74584a52019-02-22 13:04:41 -0800919 if (TEMP_FAILURE_RETRY(mount(user_source.string(), "/storage/self", nullptr, MS_BIND,
920 nullptr)) == -1) {
921 fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
922 user_source.string(),
923 strerror(errno)));
924 }
Sudheer Shanka663b1042018-07-30 17:34:21 -0700925 } else {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800926 if (package_name.empty() || sandbox_id.empty()) {
927 return;
928 }
Sudheer Shanka663b1042018-07-30 17:34:21 -0700929
Sudheer Shanka74584a52019-02-22 13:04:41 -0800930 userid_t user_id = multiuser_get_user_id(uid);
931 CreatePkgSandboxTarget(user_id, fail_fn);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800932
Sudheer Shankae51005d2019-02-24 10:24:09 -0800933 std::string pkg_sandbox_dir = StringPrintf("/mnt/user/%d/package", user_id);
934 if (TEMP_FAILURE_RETRY(mount(pkg_sandbox_dir.c_str(), "/storage",
Sudheer Shanka74584a52019-02-22 13:04:41 -0800935 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
936 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
Sudheer Shankae51005d2019-02-24 10:24:09 -0800937 pkg_sandbox_dir.c_str(), strerror(errno)));
Sudheer Shanka74584a52019-02-22 13:04:41 -0800938 }
939
940 HandleMountModeInstaller(mount_mode, user_id, sandbox_id, fail_fn);
941
Sudheer Shankae51005d2019-02-24 10:24:09 -0800942 PreparePkgSpecificDirs(packages_for_uid,
Sudheer Shanka74584a52019-02-22 13:04:41 -0800943 mount_mode == MOUNT_EXTERNAL_INSTALLER, sandbox_id, user_id, uid, fail_fn);
Jeff Sharkey9527b222015-06-24 15:24:48 -0700944 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800945 } else {
946 if (TEMP_FAILURE_RETRY(mount(storage_source.string(), "/storage", nullptr,
947 MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
948 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
949 storage_source.string(),
950 strerror(errno)));
951 }
952
953 // Mount user-specific symlink helper into place
954 userid_t user_id = multiuser_get_user_id(uid);
Sudheer Shankae51005d2019-02-24 10:24:09 -0800955 const String8 user_source(String8::format("/mnt/user/%d", user_id));
956 if (fs_prepare_dir(user_source.string(), 0751, 0, 0) == -1) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800957 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s",
Sudheer Shankae51005d2019-02-24 10:24:09 -0800958 user_source.string()));
Sudheer Shanka74584a52019-02-22 13:04:41 -0800959 }
960
Sudheer Shankae51005d2019-02-24 10:24:09 -0800961 if (TEMP_FAILURE_RETRY(mount(user_source.string(), "/storage/self",
Sudheer Shanka74584a52019-02-22 13:04:41 -0800962 nullptr, MS_BIND, nullptr)) == -1) {
963 fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
Sudheer Shankae51005d2019-02-24 10:24:09 -0800964 user_source.string(), strerror(errno)));
Sudheer Shanka74584a52019-02-22 13:04:41 -0800965 }
966 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100967}
968
Narayan Kamath973b4662014-03-31 13:41:26 +0100969static bool NeedsNoRandomizeWorkaround() {
970#if !defined(__arm__)
971 return false;
972#else
973 int major;
974 int minor;
975 struct utsname uts;
976 if (uname(&uts) == -1) {
977 return false;
978 }
979
980 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
981 return false;
982 }
983
984 // Kernels before 3.4.* need the workaround.
985 return (major < 3) || ((major == 3) && (minor < 4));
986#endif
987}
Narayan Kamath973b4662014-03-31 13:41:26 +0100988
989// Utility to close down the Zygote socket file descriptors while
990// the child is still running as root with Zygote's privileges. Each
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800991// descriptor (if any) is closed via dup3(), replacing it with a valid
Narayan Kamath973b4662014-03-31 13:41:26 +0100992// (open) descriptor to /dev/null.
993
Chris Wailesaa1c9622019-01-10 16:55:32 -0800994static void DetachDescriptors(JNIEnv* env,
995 const std::vector<int>& fds_to_close,
996 fail_fn_t fail_fn) {
997
998 if (fds_to_close.size() > 0) {
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800999 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
Chris Wailesaa1c9622019-01-10 16:55:32 -08001000 if (devnull_fd == -1) {
1001 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +01001002 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001003
1004 for (int fd : fds_to_close) {
1005 ALOGV("Switching descriptor %d to /dev/null", fd);
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -08001006 if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
1007 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
Chris Wailesaa1c9622019-01-10 16:55:32 -08001008 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001009 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001010 }
1011}
1012
Chris Wailesaa1c9622019-01-10 16:55:32 -08001013void SetThreadName(const std::string& thread_name) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001014 bool hasAt = false;
1015 bool hasDot = false;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001016
1017 for (const char str_el : thread_name) {
1018 if (str_el == '.') {
Narayan Kamath973b4662014-03-31 13:41:26 +01001019 hasDot = true;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001020 } else if (str_el == '@') {
Narayan Kamath973b4662014-03-31 13:41:26 +01001021 hasAt = true;
1022 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001023 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001024
1025 const char* name_start_ptr = thread_name.c_str();
1026 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
1027 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
Narayan Kamath973b4662014-03-31 13:41:26 +01001028 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001029
Narayan Kamath973b4662014-03-31 13:41:26 +01001030 // pthread_setname_np fails rather than truncating long strings.
1031 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
Chris Wailesaa1c9622019-01-10 16:55:32 -08001032 strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
Narayan Kamath973b4662014-03-31 13:41:26 +01001033 errno = pthread_setname_np(pthread_self(), buf);
1034 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -07001035 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +01001036 }
Andreas Gampe041483a2018-03-05 13:00:42 -08001037 // Update base::logging default tag.
1038 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +01001039}
1040
Chris Wailesaa1c9622019-01-10 16:55:32 -08001041/**
1042 * A failure function used to report fatal errors to the managed runtime. This
1043 * function is often curried with the process name information and then passed
1044 * to called functions.
1045 *
1046 * @param env Managed runtime environment
1047 * @param process_name A native representation of the process name
1048 * @param managed_process_name A managed representation of the process name
1049 * @param msg The error message to be reported
1050 */
Chris Wailesaf594fc2018-11-02 11:00:07 -07001051[[noreturn]]
1052static void ZygoteFailure(JNIEnv* env,
1053 const char* process_name,
1054 jstring managed_process_name,
1055 const std::string& msg) {
1056 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
1057 if (managed_process_name != nullptr) {
1058 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
1059 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
1060 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -07001061 }
1062 }
1063
Chris Wailesaf594fc2018-11-02 11:00:07 -07001064 const std::string& error_msg =
1065 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -07001066
Chris Wailesaf594fc2018-11-02 11:00:07 -07001067 env->FatalError(error_msg.c_str());
1068 __builtin_unreachable();
1069}
David Sehrde8d0bd2018-06-22 10:45:36 -07001070
Chris Wailesaa1c9622019-01-10 16:55:32 -08001071/**
1072 * A helper method for converting managed strings to native strings. A fatal
1073 * error is generated if a problem is encountered in extracting a non-null
1074 * string.
1075 *
1076 * @param env Managed runtime environment
1077 * @param process_name A native representation of the process name
1078 * @param managed_process_name A managed representation of the process name
1079 * @param managed_string The managed string to extract
1080 *
1081 * @return An empty option if the managed string is null. A optional-wrapped
1082 * string otherwise.
1083 */
Chris Wailesaf594fc2018-11-02 11:00:07 -07001084static std::optional<std::string> ExtractJString(JNIEnv* env,
1085 const char* process_name,
1086 jstring managed_process_name,
1087 jstring managed_string) {
1088 if (managed_string == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001089 return std::nullopt;
Chris Wailesaf594fc2018-11-02 11:00:07 -07001090 } else {
1091 ScopedUtfChars scoped_string_chars(env, managed_string);
1092
1093 if (scoped_string_chars.c_str() != nullptr) {
1094 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -07001095 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001096 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -07001097 }
1098 }
David Sehrde8d0bd2018-06-22 10:45:36 -07001099}
1100
Chris Wailesaa1c9622019-01-10 16:55:32 -08001101/**
1102 * A helper method for converting managed string arrays to native vectors. A
1103 * fatal error is generated if a problem is encountered in extracting a non-null array.
1104 *
1105 * @param env Managed runtime environment
1106 * @param process_name A native representation of the process name
1107 * @param managed_process_name A managed representation of the process name
1108 * @param managed_array The managed integer array to extract
1109 *
1110 * @return An empty option if the managed array is null. A optional-wrapped
1111 * vector otherwise.
1112 */
1113static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
1114 const char* process_name,
1115 jstring managed_process_name,
1116 jintArray managed_array) {
1117 if (managed_array == nullptr) {
1118 return std::nullopt;
1119 } else {
1120 ScopedIntArrayRO managed_array_handle(env, managed_array);
Narayan Kamath973b4662014-03-31 13:41:26 +01001121
Chris Wailesaa1c9622019-01-10 16:55:32 -08001122 if (managed_array_handle.get() != nullptr) {
1123 std::vector<int> native_array;
1124 native_array.reserve(managed_array_handle.size());
1125
1126 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
1127 native_array.push_back(managed_array_handle[array_index]);
1128 }
1129
1130 return std::move(native_array);
1131
1132 } else {
1133 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
1134 }
1135 }
1136}
1137
1138/**
1139 * A helper method for converting managed string arrays to native vectors. A
1140 * fatal error is generated if a problem is encountered in extracting a non-null array.
1141 *
1142 * @param env Managed runtime environment
1143 * @param process_name A native representation of the process name
1144 * @param managed_process_name A managed representation of the process name
1145 * @param managed_array The managed string array to extract
1146 *
1147 * @return An empty option if the managed array is null. A optional-wrapped
1148 * vector otherwise.
1149 */
1150static std::optional<std::vector<std::string>> ExtractJStringArray(JNIEnv* env,
1151 const char* process_name,
1152 jstring managed_process_name,
1153 jobjectArray managed_array) {
1154 if (managed_array == nullptr) {
1155 return std::nullopt;
1156 } else {
1157 jsize element_count = env->GetArrayLength(managed_array);
1158 std::vector<std::string> native_string_vector;
1159 native_string_vector.reserve(element_count);
1160
1161 for (jsize array_index = 0; array_index < element_count; ++array_index) {
1162 jstring managed_string = (jstring) env->GetObjectArrayElement(managed_array, array_index);
1163 auto native_string = ExtractJString(env, process_name, managed_process_name, managed_string);
1164
1165 if (LIKELY(native_string.has_value())) {
1166 native_string_vector.emplace_back(std::move(native_string.value()));
1167 } else {
1168 ZygoteFailure(env, process_name, managed_process_name,
1169 "Null string found in managed string array.");
1170 }
1171 }
1172
1173 return std::move(native_string_vector);
1174 }
1175}
1176
1177/**
1178 * A utility function for blocking signals.
1179 *
1180 * @param signum Signal number to block
1181 * @param fail_fn Fatal error reporting function
1182 *
1183 * @see ZygoteFailure
1184 */
1185static void BlockSignal(int signum, fail_fn_t fail_fn) {
1186 sigset_t sigs;
1187 sigemptyset(&sigs);
1188 sigaddset(&sigs, signum);
1189
1190 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
1191 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
1192 }
1193}
1194
1195
1196/**
1197 * A utility function for unblocking signals.
1198 *
1199 * @param signum Signal number to unblock
1200 * @param fail_fn Fatal error reporting function
1201 *
1202 * @see ZygoteFailure
1203 */
1204static void UnblockSignal(int signum, fail_fn_t fail_fn) {
1205 sigset_t sigs;
1206 sigemptyset(&sigs);
1207 sigaddset(&sigs, signum);
1208
1209 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
1210 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
1211 }
1212}
1213
Chris Wailes7e797b62019-02-22 18:29:22 -08001214static void ClearUsapTable() {
1215 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -08001216 entry.Clear();
1217 }
1218
Chris Wailes7e797b62019-02-22 18:29:22 -08001219 gUsapPoolCount = 0;
Chris Wailesae937142019-01-24 12:57:33 -08001220}
1221
Chris Wailesaa1c9622019-01-10 16:55:32 -08001222// Utility routine to fork a process from the zygote.
1223static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
1224 const std::vector<int>& fds_to_close,
1225 const std::vector<int>& fds_to_ignore) {
1226 SetSignalHandlers();
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001227
Chris Wailesaf594fc2018-11-02 11:00:07 -07001228 // Curry a failure function.
1229 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
1230 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -07001231
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001232 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
1233 // log, which would result in the logging FDs we close being reopened.
1234 // This would cause failures because the FDs are not whitelisted.
1235 //
1236 // Note that the zygote process is single threaded at this point.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001237 BlockSignal(SIGCHLD, fail_fn);
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001238
Narayan Kamath3764a262016-08-30 15:36:19 +01001239 // Close any logging related FDs before we start evaluating the list of
1240 // file descriptors.
1241 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -07001242 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +01001243
Chris Wailesaf594fc2018-11-02 11:00:07 -07001244 // If this is the first fork for this zygote, create the open FD table. If
1245 // it isn't, we just need to check whether the list of open files has changed
1246 // (and it shouldn't in the normal case).
Chris Wailesaf594fc2018-11-02 11:00:07 -07001247 if (gOpenFdTable == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001248 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
1249 } else {
1250 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001251 }
1252
Josh Gaod7951102018-06-26 16:05:12 -07001253 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
1254
Narayan Kamath973b4662014-03-31 13:41:26 +01001255 pid_t pid = fork();
1256
1257 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -07001258 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -07001259 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -07001260
Narayan Kamath973b4662014-03-31 13:41:26 +01001261 // Clean up any descriptors which must be closed immediately
Chris Wailesaa1c9622019-01-10 16:55:32 -08001262 DetachDescriptors(env, fds_to_close, fail_fn);
Narayan Kamath973b4662014-03-31 13:41:26 +01001263
Chris Wailes7e797b62019-02-22 18:29:22 -08001264 // Invalidate the entries in the USAP table.
1265 ClearUsapTable();
Chris Wailesae937142019-01-24 12:57:33 -08001266
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001267 // Re-open all remaining open file descriptors so that they aren't shared
1268 // with the zygote across a fork.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001269 gOpenFdTable->ReopenOrDetach(fail_fn);
Josh Gaod7951102018-06-26 16:05:12 -07001270
1271 // Turn fdsan back on.
1272 android_fdsan_set_error_level(fdsan_error_level);
Martin Stjernholma9bd8c32019-02-23 02:35:07 +00001273 } else {
1274 ALOGD("Forked child process %d", pid);
David Sehrde8d0bd2018-06-22 10:45:36 -07001275 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001276
David Sehrde8d0bd2018-06-22 10:45:36 -07001277 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001278 UnblockSignal(SIGCHLD, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001279
Narayan Kamath973b4662014-03-31 13:41:26 +01001280 return pid;
1281}
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001282
Chris Wailesaf594fc2018-11-02 11:00:07 -07001283// Utility routine to specialize a zygote child process.
1284static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
1285 jint runtime_flags, jobjectArray rlimits,
1286 jlong permitted_capabilities, jlong effective_capabilities,
1287 jint mount_external, jstring managed_se_info,
1288 jstring managed_nice_name, bool is_system_server,
1289 bool is_child_zygote, jstring managed_instruction_set,
1290 jstring managed_app_data_dir, jstring managed_package_name,
1291 jobjectArray managed_pacakges_for_uid,
Sudheer Shankae51005d2019-02-24 10:24:09 -08001292 jstring managed_sandbox_id) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001293 const char* process_name = is_system_server ? "system_server" : "zygote";
1294 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
1295 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001296
1297 auto se_info = extract_fn(managed_se_info);
1298 auto nice_name = extract_fn(managed_nice_name);
1299 auto instruction_set = extract_fn(managed_instruction_set);
1300 auto app_data_dir = extract_fn(managed_app_data_dir);
1301 auto package_name = extract_fn(managed_package_name);
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001302 auto sandbox_id = extract_fn(managed_sandbox_id);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001303
Chris Wailesaf594fc2018-11-02 11:00:07 -07001304 // Keep capabilities across UID change, unless we're staying root.
1305 if (uid != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001306 EnableKeepCapabilities(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001307 }
1308
Chris Wailesaa1c9622019-01-10 16:55:32 -08001309 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001310
Chris Wailesaa1c9622019-01-10 16:55:32 -08001311 DropCapabilitiesBoundingSet(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001312
1313 bool use_native_bridge = !is_system_server &&
1314 instruction_set.has_value() &&
1315 android::NativeBridgeAvailable() &&
1316 android::NeedsNativeBridge(instruction_set.value().c_str());
1317
1318 if (use_native_bridge && !app_data_dir.has_value()) {
1319 // The app_data_dir variable should never be empty if we need to use a
1320 // native bridge. In general, app_data_dir will never be empty for normal
1321 // applications. It can only happen in special cases (for isolated
1322 // processes which are not associated with any app). These are launched by
1323 // the framework and should not be emulated anyway.
1324 use_native_bridge = false;
1325 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
1326 }
1327
1328 if (!package_name.has_value()) {
1329 if (is_system_server) {
1330 package_name.emplace("android");
1331 } else {
1332 package_name.emplace("");
1333 }
1334 }
1335
Chris Wailesaa1c9622019-01-10 16:55:32 -08001336 std::vector<std::string> packages_for_uid =
1337 ExtractJStringArray(env, process_name, managed_nice_name, managed_pacakges_for_uid).
1338 value_or(std::vector<std::string>());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001339
Chris Wailesaa1c9622019-01-10 16:55:32 -08001340 MountEmulatedStorage(uid, mount_external, use_native_bridge, package_name.value(),
Sudheer Shankae51005d2019-02-24 10:24:09 -08001341 packages_for_uid, sandbox_id.value_or(""), fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001342
1343 // If this zygote isn't root, it won't be able to create a process group,
1344 // since the directory is owned by root.
1345 if (!is_system_server && getuid() == 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001346 const int rc = createProcessGroup(uid, getpid());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001347 if (rc == -EROFS) {
1348 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
1349 } else if (rc != 0) {
1350 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
1351 }
1352 }
1353
Chris Wailesaa1c9622019-01-10 16:55:32 -08001354 SetGids(env, gids, fail_fn);
1355 SetRLimits(env, rlimits, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001356
1357 if (use_native_bridge) {
1358 // Due to the logic behind use_native_bridge we know that both app_data_dir
1359 // and instruction_set contain values.
1360 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
1361 instruction_set.value().c_str());
1362 }
1363
1364 if (setresgid(gid, gid, gid) == -1) {
1365 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
1366 }
1367
1368 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
1369 // before changing uid from 0, which clears capabilities. The other
1370 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
1371 // breaks SELinux domain transition (see b/71859146). As the result,
1372 // privileged syscalls used below still need to be accessible in app process.
Martijn Coenen86f08a52019-01-03 16:23:01 +01001373 SetUpSeccompFilter(uid, is_child_zygote);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001374
1375 if (setresuid(uid, uid, uid) == -1) {
1376 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1377 }
1378
1379 // The "dumpable" flag of a process, which controls core dump generation, is
1380 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1381 // user or group ID changes. See proc(5) for possible values. In most cases,
1382 // the value is 0, so core dumps are disabled for zygote children. However,
1383 // when running in a Chrome OS container, the value is already set to 2,
1384 // which allows the external crash reporter to collect all core dumps. Since
1385 // only system crashes are interested, core dump is disabled for app
1386 // processes. This also ensures compliance with CTS.
1387 int dumpable = prctl(PR_GET_DUMPABLE);
1388 if (dumpable == -1) {
1389 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1390 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1391 }
1392
1393 if (dumpable == 2 && uid >= AID_APP) {
1394 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1395 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1396 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1397 }
1398 }
1399
Orion Hodson8d005a62018-12-05 12:28:53 +00001400 // Set process properties to enable debugging if required.
1401 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1402 EnableDebugger();
1403 }
Yabin Cui4d8546d2019-01-29 16:29:20 -08001404 if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
1405 // simpleperf needs the process to be dumpable to profile it.
1406 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
1407 ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
1408 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
1409 }
1410 }
Orion Hodson8d005a62018-12-05 12:28:53 +00001411
Chris Wailesaf594fc2018-11-02 11:00:07 -07001412 if (NeedsNoRandomizeWorkaround()) {
1413 // Work around ARM kernel ASLR lossage (http://b/5817320).
1414 int old_personality = personality(0xffffffff);
1415 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1416 if (new_personality == -1) {
1417 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1418 }
1419 }
1420
Chris Wailesaa1c9622019-01-10 16:55:32 -08001421 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001422
Chris Wailesaa1c9622019-01-10 16:55:32 -08001423 SetSchedulerPolicy(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001424
Mathieu Chartier0bccbf72019-01-30 15:56:17 -08001425 __android_log_close();
1426 stats_log_close();
1427
Chris Wailesaf594fc2018-11-02 11:00:07 -07001428 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1429 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1430
1431 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1432 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1433 uid, is_system_server, se_info_ptr, nice_name_ptr));
1434 }
1435
1436 // Make it easier to debug audit logs by setting the main thread's name to the
1437 // nice name rather than "app_process".
1438 if (nice_name.has_value()) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001439 SetThreadName(nice_name.value());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001440 } else if (is_system_server) {
1441 SetThreadName("system_server");
1442 }
1443
1444 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1445 UnsetChldSignalHandler();
1446
1447 if (is_system_server) {
1448 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1449 if (env->ExceptionCheck()) {
1450 fail_fn("Error calling post fork system server hooks.");
1451 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001452
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07001453 // Prefetch the classloader for the system server. This is done early to
1454 // allow a tie-down of the proper system server selinux domain.
1455 env->CallStaticVoidMethod(gZygoteInitClass, gCreateSystemServerClassLoader);
1456 if (env->ExceptionCheck()) {
1457 // Be robust here. The Java code will attempt to create the classloader
1458 // at a later point (but may not have rights to use AoT artifacts).
1459 env->ExceptionClear();
1460 }
1461
Chris Wailesaf594fc2018-11-02 11:00:07 -07001462 // TODO(oth): Remove hardcoded label here (b/117874058).
1463 static const char* kSystemServerLabel = "u:r:system_server:s0";
1464 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1465 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1466 }
1467 }
1468
1469 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1470 is_system_server, is_child_zygote, managed_instruction_set);
1471
1472 if (env->ExceptionCheck()) {
1473 fail_fn("Error calling post fork hooks.");
1474 }
1475}
1476
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001477static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1478 __user_cap_header_struct capheader;
1479 memset(&capheader, 0, sizeof(capheader));
1480 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1481 capheader.pid = 0;
1482
1483 __user_cap_data_struct capdata[2];
1484 if (capget(&capheader, &capdata[0]) == -1) {
1485 ALOGE("capget failed: %s", strerror(errno));
1486 RuntimeAbort(env, __LINE__, "capget failed");
1487 }
1488
Chris Wailesaf594fc2018-11-02 11:00:07 -07001489 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1490}
1491
1492static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1493 bool is_child_zygote) {
1494 jlong capabilities = 0;
1495
1496 /*
1497 * Grant the following capabilities to the Bluetooth user:
1498 * - CAP_WAKE_ALARM
1499 * - CAP_NET_RAW
1500 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1501 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1502 */
1503
1504 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1505 capabilities |= (1LL << CAP_WAKE_ALARM);
1506 capabilities |= (1LL << CAP_NET_RAW);
1507 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1508 capabilities |= (1LL << CAP_SYS_NICE);
1509 }
1510
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001511 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1512 capabilities |= (1LL << CAP_NET_ADMIN);
1513 capabilities |= (1LL << CAP_NET_BROADCAST);
1514 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1515 capabilities |= (1LL << CAP_NET_RAW);
1516 }
1517
Chris Wailesaf594fc2018-11-02 11:00:07 -07001518 /*
1519 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1520 */
1521
1522 bool gid_wakelock_found = false;
1523 if (gid == AID_WAKELOCK) {
1524 gid_wakelock_found = true;
1525 } else if (gids != nullptr) {
1526 jsize gids_num = env->GetArrayLength(gids);
1527 ScopedIntArrayRO native_gid_proxy(env, gids);
1528
1529 if (native_gid_proxy.get() == nullptr) {
1530 RuntimeAbort(env, __LINE__, "Bad gids array");
1531 }
1532
Chris Wailes31c52c92019-02-14 11:20:02 -08001533 for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
1534 if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001535 gid_wakelock_found = true;
1536 break;
1537 }
1538 }
1539 }
1540
1541 if (gid_wakelock_found) {
1542 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1543 }
1544
1545 /*
1546 * Grant child Zygote processes the following capabilities:
1547 * - CAP_SETUID (change UID of child processes)
1548 * - CAP_SETGID (change GID of child processes)
1549 * - CAP_SETPCAP (change capabilities of child processes)
1550 */
1551
1552 if (is_child_zygote) {
1553 capabilities |= (1LL << CAP_SETUID);
1554 capabilities |= (1LL << CAP_SETGID);
1555 capabilities |= (1LL << CAP_SETPCAP);
1556 }
1557
1558 /*
1559 * Containers run without some capabilities, so drop any caps that are not
1560 * available.
1561 */
1562
1563 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001564}
Chris Wailesaa1c9622019-01-10 16:55:32 -08001565
1566/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001567 * Adds the given information about a newly created unspecialized app
1568 * processes to the Zygote's USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001569 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001570 * @param usap_pid Process ID of the newly created USAP
1571 * @param read_pipe_fd File descriptor for the read end of the USAP
1572 * reporting pipe. Used in the ZygoteServer poll loop to track USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001573 * specialization.
1574 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001575static void AddUsapTableEntry(pid_t usap_pid, int read_pipe_fd) {
1576 static int sUsapTableInsertIndex = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001577
Chris Wailes7e797b62019-02-22 18:29:22 -08001578 int search_index = sUsapTableInsertIndex;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001579
1580 do {
Chris Wailes7e797b62019-02-22 18:29:22 -08001581 if (gUsapTable[search_index].SetIfInvalid(usap_pid, read_pipe_fd)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001582 // Start our next search right after where we finished this one.
Chris Wailes7e797b62019-02-22 18:29:22 -08001583 sUsapTableInsertIndex = (search_index + 1) % gUsapTable.size();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001584
1585 return;
1586 }
1587
Chris Wailes7e797b62019-02-22 18:29:22 -08001588 search_index = (search_index + 1) % gUsapTable.size();
1589 } while (search_index != sUsapTableInsertIndex);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001590
1591 // Much like money in the banana stand, there should always be an entry
Chris Wailes7e797b62019-02-22 18:29:22 -08001592 // in the USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001593 __builtin_unreachable();
1594}
1595
1596/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001597 * Invalidates the entry in the USAPTable corresponding to the provided
1598 * process ID if it is present. If an entry was removed the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001599 * count is decremented.
1600 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001601 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001602 * @return True if an entry was invalidated; false otherwise
1603 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001604static bool RemoveUsapTableEntry(pid_t usap_pid) {
1605 for (UsapTableEntry& entry : gUsapTable) {
1606 if (entry.ClearForPID(usap_pid)) {
1607 --gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001608 return true;
1609 }
1610 }
1611
1612 return false;
1613}
1614
1615/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001616 * @return A vector of the read pipe FDs for each of the active USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001617 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001618std::vector<int> MakeUsapPipeReadFDVector() {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001619 std::vector<int> fd_vec;
Chris Wailes7e797b62019-02-22 18:29:22 -08001620 fd_vec.reserve(gUsapTable.size());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001621
Chris Wailes7e797b62019-02-22 18:29:22 -08001622 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001623 auto entry_values = entry.GetValues();
1624
1625 if (entry_values.has_value()) {
1626 fd_vec.push_back(entry_values.value().read_pipe_fd);
1627 }
1628 }
1629
1630 return fd_vec;
1631}
1632
Chris Wailes6d482d542019-04-03 13:00:52 -07001633static void UnmountStorageOnInit(JNIEnv* env) {
1634 // Zygote process unmount root storage space initially before every child processes are forked.
1635 // Every forked child processes (include SystemServer) only mount their own root storage space
1636 // and no need unmount storage operation in MountEmulatedStorage method.
1637 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1638
1639 // See storage config details at http://source.android.com/tech/storage/
1640 // Create private mount namespace shared by all children
1641 if (unshare(CLONE_NEWNS) == -1) {
1642 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1643 return;
1644 }
1645
1646 // Mark rootfs as being a slave so that changes from default
1647 // namespace only flow into our children.
1648 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1649 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1650 return;
1651 }
1652
1653 // Create a staging tmpfs that is shared by our children; they will
1654 // bind mount storage into their respective private namespaces, which
1655 // are isolated from each other.
1656 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1657 if (target_base != nullptr) {
1658#define STRINGIFY_UID(x) __STRING(x)
1659 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1660 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1661 ALOGE("Failed to mount tmpfs to %s", target_base);
1662 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1663 return;
1664 }
1665#undef STRINGIFY_UID
1666 }
1667
1668 UnmountTree("/storage");
1669}
1670
Narayan Kamath973b4662014-03-31 13:41:26 +01001671} // anonymous namespace
1672
1673namespace android {
1674
Christopher Ferris76de39e2017-06-20 16:13:40 -07001675static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1676 PreApplicationInit();
1677}
1678
Narayan Kamath973b4662014-03-31 13:41:26 +01001679static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1680 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001681 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001682 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001683 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001684 jstring instruction_set, jstring app_data_dir, jstring package_name,
Sudheer Shankae51005d2019-02-24 10:24:09 -08001685 jobjectArray packages_for_uid, jstring sandbox_id) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001686 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001687
Chris Wailesaa1c9622019-01-10 16:55:32 -08001688 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1689 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1690 }
1691
1692 std::vector<int> fds_to_close =
1693 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1694 std::vector<int> fds_to_ignore =
1695 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1696 .value_or(std::vector<int>());
1697
Chris Wailes7e797b62019-02-22 18:29:22 -08001698 std::vector<int> usap_pipes = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001699
Chris Wailes7e797b62019-02-22 18:29:22 -08001700 fds_to_close.insert(fds_to_close.end(), usap_pipes.begin(), usap_pipes.end());
1701 fds_to_ignore.insert(fds_to_ignore.end(), usap_pipes.begin(), usap_pipes.end());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001702
Chris Wailes7e797b62019-02-22 18:29:22 -08001703 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001704
Chris Wailes7e797b62019-02-22 18:29:22 -08001705 if (gUsapPoolEventFD != -1) {
1706 fds_to_close.push_back(gUsapPoolEventFD);
1707 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001708 }
1709
Chris Wailesaf594fc2018-11-02 11:00:07 -07001710 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001711
David Sehrde8d0bd2018-06-22 10:45:36 -07001712 if (pid == 0) {
1713 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1714 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001715 mount_external, se_info, nice_name, false,
1716 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
Sudheer Shankae51005d2019-02-24 10:24:09 -08001717 package_name, packages_for_uid, sandbox_id);
David Sehrde8d0bd2018-06-22 10:45:36 -07001718 }
1719 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001720}
1721
1722static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1723 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001724 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1725 jlong effective_capabilities) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001726 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001727 fds_to_ignore(fds_to_close);
1728
Chris Wailes7e797b62019-02-22 18:29:22 -08001729 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001730
Chris Wailes7e797b62019-02-22 18:29:22 -08001731 if (gUsapPoolEventFD != -1) {
1732 fds_to_close.push_back(gUsapPoolEventFD);
1733 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001734 }
1735
Chris Wailesaf594fc2018-11-02 11:00:07 -07001736 pid_t pid = ForkCommon(env, true,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001737 fds_to_close,
1738 fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001739 if (pid == 0) {
1740 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001741 permitted_capabilities, effective_capabilities,
1742 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
Sudheer Shankae51005d2019-02-24 10:24:09 -08001743 false, nullptr, nullptr, nullptr, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001744 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001745 // The zygote process checks whether the child process has died or not.
1746 ALOGI("System server process %d has been created", pid);
1747 gSystemServerPid = pid;
1748 // There is a slight window that the system server process has crashed
1749 // but it went unnoticed because we haven't published its pid yet. So
1750 // we recheck here just to make sure that all is well.
1751 int status;
1752 if (waitpid(pid, &status, WNOHANG) == pid) {
1753 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001754 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001755 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001756
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001757 if (UsePerAppMemcg()) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001758 // Assign system_server to the correct memory cgroup.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001759 // Not all devices mount memcg so check if it is mounted first
Minchan Kim5fa8af22018-06-27 11:32:40 +09001760 // to avoid unnecessarily printing errors and denials in the logs.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001761 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
1762 ALOGE("couldn't add process %d into system memcg group", pid);
Minchan Kim5fa8af22018-06-27 11:32:40 +09001763 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001764 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001765 }
1766 return pid;
1767}
1768
Chris Wailesaa1c9622019-01-10 16:55:32 -08001769/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001770 * A JNI function that forks an unspecialized app process from the Zygote while
1771 * ensuring proper file descriptor hygiene.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001772 *
1773 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001774 * @param read_pipe_fd The read FD for the USAP reporting pipe. Manually closed by blastlas
Chris Wailesaa1c9622019-01-10 16:55:32 -08001775 * in managed code.
Chris Wailes7e797b62019-02-22 18:29:22 -08001776 * @param write_pipe_fd The write FD for the USAP reporting pipe. Manually closed by the
Chris Wailesaa1c9622019-01-10 16:55:32 -08001777 * zygote in managed code.
1778 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
Chris Wailes7e797b62019-02-22 18:29:22 -08001779 * the FD hygiene code and automatically "closed" in the new USAP.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001780 * @return
1781 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001782static jint com_android_internal_os_Zygote_nativeForkUsap(JNIEnv* env,
1783 jclass,
1784 jint read_pipe_fd,
1785 jint write_pipe_fd,
1786 jintArray managed_session_socket_fds) {
1787 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001788 fds_to_ignore(fds_to_close);
1789
1790 std::vector<int> session_socket_fds =
Chris Wailes7e797b62019-02-22 18:29:22 -08001791 ExtractJIntArray(env, "USAP", nullptr, managed_session_socket_fds)
Chris Wailesaa1c9622019-01-10 16:55:32 -08001792 .value_or(std::vector<int>());
1793
Chris Wailes7e797b62019-02-22 18:29:22 -08001794 // The USAP Pool Event FD is created during the initialization of the
1795 // USAP pool and should always be valid here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001796
1797 fds_to_close.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08001798 fds_to_close.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001799 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
1800
1801 fds_to_ignore.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08001802 fds_to_ignore.push_back(gUsapPoolSocketFD);
1803 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001804 fds_to_ignore.push_back(read_pipe_fd);
1805 fds_to_ignore.push_back(write_pipe_fd);
1806 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
1807
Chris Wailes7e797b62019-02-22 18:29:22 -08001808 pid_t usap_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001809
Chris Wailes7e797b62019-02-22 18:29:22 -08001810 if (usap_pid != 0) {
1811 ++gUsapPoolCount;
1812 AddUsapTableEntry(usap_pid, read_pipe_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001813 }
1814
Chris Wailes7e797b62019-02-22 18:29:22 -08001815 return usap_pid;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001816}
1817
Robert Sesek54e387d2016-12-02 17:27:50 -05001818static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1819 JNIEnv* env, jclass, jstring path) {
1820 ScopedUtfChars path_native(env, path);
1821 const char* path_cstr = path_native.c_str();
1822 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001823 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001824 }
1825 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1826}
1827
Martijn Coenen86f08a52019-01-03 16:23:01 +01001828static void com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(
1829 JNIEnv* env, jclass, jint uidGidMin, jint uidGidMax) {
Chris Wailes6d482d542019-04-03 13:00:52 -07001830 if (!gIsSecurityEnforced) {
Martijn Coenen86f08a52019-01-03 16:23:01 +01001831 ALOGI("seccomp disabled by setenforce 0");
1832 return;
1833 }
1834
Martijn Coenen86f08a52019-01-03 16:23:01 +01001835 bool installed = install_setuidgid_seccomp_filter(uidGidMin, uidGidMax);
1836 if (!installed) {
1837 RuntimeAbort(env, __LINE__, "Could not install setuid/setgid seccomp filter.");
1838 }
Martijn Coenen86f08a52019-01-03 16:23:01 +01001839}
1840
Chris Wailesaa1c9622019-01-10 16:55:32 -08001841/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001842 * Called from an unspecialized app process to specialize the process for a
1843 * given application.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001844 *
1845 * @param env Managed runtime environment
1846 * @param uid User ID of the new application
1847 * @param gid Group ID of the new application
1848 * @param gids Extra groups that the process belongs to
1849 * @param runtime_flags Flags for changing the behavior of the managed runtime
1850 * @param rlimits Resource limits
1851 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
1852 * @param se_info SELinux policy information
1853 * @param nice_name New name for this process
1854 * @param is_child_zygote If the process is to become a WebViewZygote
1855 * @param instruction_set The instruction set expected/requested by the new application
1856 * @param app_data_dir Path to the application's data directory
1857 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001858static void com_android_internal_os_Zygote_nativeSpecializeAppProcess(
Chris Wailesaa1c9622019-01-10 16:55:32 -08001859 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
1860 jint runtime_flags, jobjectArray rlimits,
1861 jint mount_external, jstring se_info, jstring nice_name,
1862 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir,
Sudheer Shankae51005d2019-02-24 10:24:09 -08001863 jstring package_name, jobjectArray packages_for_uid,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08001864 jstring sandbox_id) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001865 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
1866
1867 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1868 capabilities, capabilities,
1869 mount_external, se_info, nice_name, false,
1870 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
Sudheer Shankae51005d2019-02-24 10:24:09 -08001871 package_name, packages_for_uid, sandbox_id);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001872}
1873
1874/**
1875 * A helper method for fetching socket file descriptors that were opened by init from the
1876 * environment.
1877 *
1878 * @param env Managed runtime environment
1879 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
1880 * of the environment variable storing the file descriptors.
1881 */
Chris Wailes6d482d542019-04-03 13:00:52 -07001882static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv* env, jclass,
1883 jboolean is_primary) {
1884 /*
1885 * Obtain file descriptors created by init from the environment.
1886 */
1887
Chris Wailesaa1c9622019-01-10 16:55:32 -08001888 std::string android_socket_prefix(ANDROID_SOCKET_PREFIX);
1889 std::string env_var_name = android_socket_prefix + (is_primary ? "zygote" : "zygote_secondary");
1890 char* env_var_val = getenv(env_var_name.c_str());
1891
1892 if (env_var_val != nullptr) {
1893 gZygoteSocketFD = atoi(env_var_val);
1894 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
1895 } else {
1896 ALOGE("Unable to fetch Zygote socket file descriptor");
1897 }
1898
Chris Wailes7e797b62019-02-22 18:29:22 -08001899 env_var_name = android_socket_prefix + (is_primary ? "usap_pool_primary" : "usap_pool_secondary");
Chris Wailesaa1c9622019-01-10 16:55:32 -08001900 env_var_val = getenv(env_var_name.c_str());
1901
1902 if (env_var_val != nullptr) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001903 gUsapPoolSocketFD = atoi(env_var_val);
1904 ALOGV("Zygote:usapPoolSocketFD = %d", gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001905 } else {
Chris Wailes7e797b62019-02-22 18:29:22 -08001906 ALOGE("Unable to fetch USAP pool socket file descriptor");
Chris Wailesaa1c9622019-01-10 16:55:32 -08001907 }
Chris Wailes6d482d542019-04-03 13:00:52 -07001908
1909 /*
1910 * Security Initialization
1911 */
1912
1913 // security_getenforce is not allowed on app process. Initialize and cache
1914 // the value before zygote forks.
1915 gIsSecurityEnforced = security_getenforce();
1916
1917 selinux_android_seapp_context_init();
1918
1919 /*
1920 * Storage Initialization
1921 */
1922
1923 UnmountStorageOnInit(env);
1924
1925 /*
1926 * Performance Initialization
1927 */
1928
1929 if (!SetTaskProfiles(0, {})) {
1930 ZygoteFailure(env, "zygote", nullptr, "Zygote SetTaskProfiles failed");
1931 }
Tim Murraycde0ac72019-04-04 09:19:03 -07001932
1933 /*
1934 * ashmem initialization to avoid dlopen overhead
1935 */
1936 ashmem_init();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001937}
1938
1939/**
1940 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001941 * @return A managed array of raw file descriptors for the read ends of the USAP reporting
Chris Wailesaa1c9622019-01-10 16:55:32 -08001942 * pipes.
1943 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001944static jintArray com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv* env, jclass) {
1945 std::vector<int> usap_fds = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001946
Chris Wailes7e797b62019-02-22 18:29:22 -08001947 jintArray managed_usap_fds = env->NewIntArray(usap_fds.size());
1948 env->SetIntArrayRegion(managed_usap_fds, 0, usap_fds.size(), usap_fds.data());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001949
Chris Wailes7e797b62019-02-22 18:29:22 -08001950 return managed_usap_fds;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001951}
1952
1953/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001954 * A JNI wrapper around RemoveUsapTableEntry.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001955 *
1956 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001957 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001958 * @return True if an entry was invalidated; false otherwise.
1959 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001960static jboolean com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(JNIEnv* env, jclass,
1961 jint usap_pid) {
1962 return RemoveUsapTableEntry(usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001963}
1964
1965/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001966 * Creates the USAP pool event FD if it doesn't exist and returns it. This is used by the
1967 * ZygoteServer poll loop to know when to re-fill the USAP pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001968 *
1969 * @param env Managed runtime environment
1970 * @return A raw event file descriptor used to communicate (from the signal handler) when the
Chris Wailes7e797b62019-02-22 18:29:22 -08001971 * Zygote receives a SIGCHLD for a USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001972 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001973static jint com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv* env, jclass) {
1974 if (gUsapPoolEventFD == -1) {
1975 if ((gUsapPoolEventFD = eventfd(0, 0)) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001976 ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
1977 }
1978 }
1979
Chris Wailes7e797b62019-02-22 18:29:22 -08001980 return gUsapPoolEventFD;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001981}
1982
1983/**
1984 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001985 * @return The number of USAPs currently in the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001986 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001987static jint com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv* env, jclass) {
1988 return gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001989}
1990
Chris Wailesae937142019-01-24 12:57:33 -08001991/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001992 * Kills all processes currently in the USAP pool and closes their read pipe
1993 * FDs.
Chris Wailesae937142019-01-24 12:57:33 -08001994 *
1995 * @param env Managed runtime environment
Chris Wailesae937142019-01-24 12:57:33 -08001996 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001997static void com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv* env, jclass) {
1998 for (auto& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -08001999 auto entry_storage = entry.GetValues();
2000
2001 if (entry_storage.has_value()) {
2002 kill(entry_storage.value().pid, SIGKILL);
Chris Wailesdb132a32019-02-20 10:49:27 -08002003 close(entry_storage.value().read_pipe_fd);
2004
2005 // Avoid a second atomic load by invalidating instead of clearing.
2006 entry.Invalidate();
Chris Wailes7e797b62019-02-22 18:29:22 -08002007 --gUsapPoolCount;
Chris Wailesae937142019-01-24 12:57:33 -08002008 }
2009 }
2010}
2011
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07002012static int disable_execute_only(struct dl_phdr_info *info, size_t size, void *data) {
2013 // Search for any execute-only segments and mark them read+execute.
2014 for (int i = 0; i < info->dlpi_phnum; i++) {
2015 if ((info->dlpi_phdr[i].p_type == PT_LOAD) && (info->dlpi_phdr[i].p_flags == PF_X)) {
2016 mprotect(reinterpret_cast<void*>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr),
2017 info->dlpi_phdr[i].p_memsz, PROT_READ | PROT_EXEC);
2018 }
2019 }
2020 // Return non-zero to exit dl_iterate_phdr.
2021 return 0;
2022}
2023
2024/**
2025 * @param env Managed runtime environment
2026 * @return True if disable was successful.
2027 */
2028static jboolean com_android_internal_os_Zygote_nativeDisableExecuteOnly(JNIEnv* env, jclass) {
2029 return dl_iterate_phdr(disable_execute_only, nullptr) == 0;
2030}
2031
Daniel Micay76f6a862015-09-19 17:31:01 -04002032static const JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -07002033 { "nativeForkAndSpecialize",
Sudheer Shankae51005d2019-02-24 10:24:09 -08002034 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01002035 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
2036 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09002037 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05002038 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
2039 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
Christopher Ferris76de39e2017-06-20 16:13:40 -07002040 { "nativePreApplicationInit", "()V",
Martijn Coenen86f08a52019-01-03 16:23:01 +01002041 (void *) com_android_internal_os_Zygote_nativePreApplicationInit },
2042 { "nativeInstallSeccompUidGidFilter", "(II)V",
Chris Wailesaa1c9622019-01-10 16:55:32 -08002043 (void *) com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter },
Chris Wailes7e797b62019-02-22 18:29:22 -08002044 { "nativeForkUsap", "(II[I)I",
2045 (void *) com_android_internal_os_Zygote_nativeForkUsap },
2046 { "nativeSpecializeAppProcess",
Sudheer Shankae51005d2019-02-24 10:24:09 -08002047 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V",
Chris Wailes7e797b62019-02-22 18:29:22 -08002048 (void *) com_android_internal_os_Zygote_nativeSpecializeAppProcess },
Chris Wailes6d482d542019-04-03 13:00:52 -07002049 { "nativeInitNativeState", "(Z)V",
2050 (void *) com_android_internal_os_Zygote_nativeInitNativeState },
Chris Wailes7e797b62019-02-22 18:29:22 -08002051 { "nativeGetUsapPipeFDs", "()[I",
2052 (void *) com_android_internal_os_Zygote_nativeGetUsapPipeFDs },
2053 { "nativeRemoveUsapTableEntry", "(I)Z",
2054 (void *) com_android_internal_os_Zygote_nativeRemoveUsapTableEntry },
2055 { "nativeGetUsapPoolEventFD", "()I",
2056 (void *) com_android_internal_os_Zygote_nativeGetUsapPoolEventFD },
2057 { "nativeGetUsapPoolCount", "()I",
2058 (void *) com_android_internal_os_Zygote_nativeGetUsapPoolCount },
2059 { "nativeEmptyUsapPool", "()V",
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07002060 (void *) com_android_internal_os_Zygote_nativeEmptyUsapPool },
2061 { "nativeDisableExecuteOnly", "()Z",
2062 (void *) com_android_internal_os_Zygote_nativeDisableExecuteOnly }
Narayan Kamath973b4662014-03-31 13:41:26 +01002063};
2064
2065int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08002066 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01002067 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
2068 "callPostForkSystemServerHooks",
2069 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08002070 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05002071 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01002072
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07002073 gZygoteInitClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteInitClassName));
2074 gCreateSystemServerClassLoader = GetStaticMethodIDOrDie(env, gZygoteInitClass,
2075 "createSystemServerClassLoader",
2076 "()V");
2077
2078 RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
2079
2080 return JNI_OK;
Narayan Kamath973b4662014-03-31 13:41:26 +01002081}
2082} // namespace android