blob: a3f5311e49c46a43765d7b869c5c1e32a7a0e657 [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 Ferris15c02332019-09-11 19:08:52 -070076#include <bionic/malloc.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070077#include <cutils/fs.h>
78#include <cutils/multiuser.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070079#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070080#include <utils/String8.h>
Jeff Sharkey853e53e2019-03-18 14:35:08 -060081#include <utils/Trace.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070082#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080083#include <seccomp_policy.h>
Howard Ro27330412018-10-02 12:08:28 -070084#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070085#include <processgroup/processgroup.h>
Suren Baghdasaryane4433262019-01-04 12:16:57 -080086#include <processgroup/sched_policy.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070087
Andreas Gampeed6b9df2014-11-20 22:02:20 -080088#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070089#include <nativehelper/JNIHelp.h>
90#include <nativehelper/ScopedLocalRef.h>
91#include <nativehelper/ScopedPrimitiveArray.h>
92#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050093#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010094
jgu212eacd062014-09-10 06:55:07 -040095#include "nativebridge/native_bridge.h"
96
Narayan Kamath973b4662014-03-31 13:41:26 +010097namespace {
98
Chris Wailesaa1c9622019-01-10 16:55:32 -080099// TODO (chriswailes): Add a function to initialize native Zygote data.
100// TODO (chriswailes): Fix mixed indentation style (2 and 4 spaces).
101
Chris Wailesaf594fc2018-11-02 11:00:07 -0700102using namespace std::placeholders;
103
Narayan Kamath973b4662014-03-31 13:41:26 +0100104using android::String8;
Sudheer Shanka663b1042018-07-30 17:34:21 -0700105using android::base::StringAppendF;
Carmen Jacksondd401252017-02-23 15:21:10 -0800106using android::base::StringPrintf;
107using android::base::WriteStringToFile;
Minchan Kim5fa8af22018-06-27 11:32:40 +0900108using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +0100109
Andreas Gamped5758f62018-03-12 12:08:55 -0700110#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
111 append(StringPrintf(__VA_ARGS__))
112
Chris Wailesaa1c9622019-01-10 16:55:32 -0800113// This type is duplicated in fd_utils.h
114typedef const std::function<void(std::string)>& fail_fn_t;
115
Narayan Kamath973b4662014-03-31 13:41:26 +0100116static pid_t gSystemServerPid = 0;
117
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700118static constexpr const char* kZygoteClassName = "com/android/internal/os/Zygote";
Narayan Kamath973b4662014-03-31 13:41:26 +0100119static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +0100120static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +0100121static jmethodID gCallPostForkChildHooks;
122
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700123static constexpr const char* kZygoteInitClassName = "com/android/internal/os/ZygoteInit";
124static jclass gZygoteInitClass;
125static jmethodID gCreateSystemServerClassLoader;
126
Chris Wailes6d482d542019-04-03 13:00:52 -0700127static bool gIsSecurityEnforced = true;
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800128
Chris Wailesaa1c9622019-01-10 16:55:32 -0800129/**
130 * The maximum number of characters (not including a null terminator) that a
131 * process name may contain.
132 */
133static constexpr size_t MAX_NAME_LENGTH = 15;
134
135/**
136 * The prefix string for environmental variables storing socket FDs created by
137 * init.
138 */
139
140static constexpr std::string_view ANDROID_SOCKET_PREFIX("ANDROID_SOCKET_");
141
142/**
143 * The file descriptor for the Zygote socket opened by init.
144 */
145
146static int gZygoteSocketFD = -1;
147
148/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800149 * The file descriptor for the unspecialized app process (USAP) pool socket opened by init.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800150 */
151
Chris Wailes7e797b62019-02-22 18:29:22 -0800152static int gUsapPoolSocketFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800153
154/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800155 * The number of USAPs currently in this Zygote's pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800156 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800157static std::atomic_uint32_t gUsapPoolCount = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800158
159/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800160 * Event file descriptor used to communicate reaped USAPs to the
Chris Wailesaa1c9622019-01-10 16:55:32 -0800161 * ZygoteServer.
162 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800163static int gUsapPoolEventFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800164
165/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800166 * The maximum value that the gUSAPPoolSizeMax variable may take. This value
167 * is a mirror of ZygoteServer.USAP_POOL_SIZE_MAX_LIMIT
Chris Wailesaa1c9622019-01-10 16:55:32 -0800168 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800169static constexpr int USAP_POOL_SIZE_MAX_LIMIT = 100;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800170
171/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800172 * A helper class containing accounting information for USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800173 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800174class UsapTableEntry {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800175 public:
176 struct EntryStorage {
177 int32_t pid;
178 int32_t read_pipe_fd;
179
180 bool operator!=(const EntryStorage& other) {
181 return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
182 }
183 };
184
185 private:
186 static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
187
188 std::atomic<EntryStorage> mStorage;
189 static_assert(decltype(mStorage)::is_always_lock_free);
190
191 public:
Chris Wailes7e797b62019-02-22 18:29:22 -0800192 constexpr UsapTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
Chris Wailesaa1c9622019-01-10 16:55:32 -0800193
194 /**
195 * If the provided PID matches the one stored in this entry, the entry will
196 * be invalidated and the associated file descriptor will be closed. If the
197 * PIDs don't match nothing will happen.
198 *
199 * @param pid The ID of the process who's entry we want to clear.
Chris Wailesf68c4e22019-06-05 16:07:50 -0700200 * @return True if the entry was cleared by this call; false otherwise
Chris Wailesaa1c9622019-01-10 16:55:32 -0800201 */
202 bool ClearForPID(int32_t pid) {
203 EntryStorage storage = mStorage.load();
204
205 if (storage.pid == pid) {
206 /*
207 * There are three possible outcomes from this compare-and-exchange:
208 * 1) It succeeds, in which case we close the FD
209 * 2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
210 * the entry has already been cleared.
211 * 3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
212 * case the entry has already been cleared and re-used.
213 *
Chris Wailesf68c4e22019-06-05 16:07:50 -0700214 * In all three cases the goal of the caller has been met, but only in
215 * the first case do we need to decrement the pool count.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800216 */
217 if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
218 close(storage.read_pipe_fd);
Chris Wailesf68c4e22019-06-05 16:07:50 -0700219 return true;
220 } else {
221 return false;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800222 }
223
Chris Wailesaa1c9622019-01-10 16:55:32 -0800224 } else {
225 return false;
226 }
227 }
228
Chris Wailesae937142019-01-24 12:57:33 -0800229 void Clear() {
Chris Wailesdb132a32019-02-20 10:49:27 -0800230 EntryStorage storage = mStorage.load();
231
232 if (storage != INVALID_ENTRY_VALUE) {
233 close(storage.read_pipe_fd);
234 mStorage.store(INVALID_ENTRY_VALUE);
235 }
236 }
237
238 void Invalidate() {
Chris Wailesae937142019-01-24 12:57:33 -0800239 mStorage.store(INVALID_ENTRY_VALUE);
240 }
241
Chris Wailesaa1c9622019-01-10 16:55:32 -0800242 /**
243 * @return A copy of the data stored in this entry.
244 */
245 std::optional<EntryStorage> GetValues() {
246 EntryStorage storage = mStorage.load();
247
248 if (storage != INVALID_ENTRY_VALUE) {
249 return storage;
250 } else {
251 return std::nullopt;
252 }
253 }
254
255 /**
256 * Sets the entry to the given values if it is currently invalid.
257 *
258 * @param pid The process ID for the new entry.
Chris Wailes7e797b62019-02-22 18:29:22 -0800259 * @param read_pipe_fd The read end of the USAP control pipe for this
Chris Wailesaa1c9622019-01-10 16:55:32 -0800260 * process.
261 * @return True if the entry was set; false otherwise.
262 */
263 bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
264 EntryStorage new_value_storage;
265
266 new_value_storage.pid = pid;
267 new_value_storage.read_pipe_fd = read_pipe_fd;
268
269 EntryStorage expected = INVALID_ENTRY_VALUE;
270
271 return mStorage.compare_exchange_strong(expected, new_value_storage);
272 }
273};
274
275/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800276 * A table containing information about the USAPs currently in the pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800277 *
278 * Multiple threads may be attempting to modify the table, either from the
279 * signal handler or from the ZygoteServer poll loop. Atomic loads/stores in
Chris Wailes7e797b62019-02-22 18:29:22 -0800280 * the USAPTableEntry class prevent data races during these concurrent
Chris Wailesaa1c9622019-01-10 16:55:32 -0800281 * operations.
282 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800283static std::array<UsapTableEntry, USAP_POOL_SIZE_MAX_LIMIT> gUsapTable;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800284
285/**
286 * The list of open zygote file descriptors.
287 */
288static FileDescriptorTable* gOpenFdTable = nullptr;
289
Narayan Kamath973b4662014-03-31 13:41:26 +0100290// Must match values in com.android.internal.os.Zygote.
291enum MountExternalKind {
292 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700293 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700294 MOUNT_EXTERNAL_READ = 2,
295 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800296 MOUNT_EXTERNAL_LEGACY = 4,
297 MOUNT_EXTERNAL_INSTALLER = 5,
298 MOUNT_EXTERNAL_FULL = 6,
Narayan Kamath973b4662014-03-31 13:41:26 +0100299};
300
Orion Hodson8d005a62018-12-05 12:28:53 +0000301// Must match values in com.android.internal.os.Zygote.
302enum RuntimeFlags : uint32_t {
303 DEBUG_ENABLE_JDWP = 1,
Yabin Cui4d8546d2019-01-29 16:29:20 -0800304 PROFILE_FROM_SHELL = 1 << 15,
Orion Hodson8d005a62018-12-05 12:28:53 +0000305};
306
Chris Wailesaa1c9622019-01-10 16:55:32 -0800307// Forward declaration so we don't have to move the signal handler.
Chris Wailes7e797b62019-02-22 18:29:22 -0800308static bool RemoveUsapTableEntry(pid_t usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800309
Andreas Gampeb053cce2015-11-17 16:38:59 -0800310static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
311 std::ostringstream oss;
312 oss << __FILE__ << ":" << line << ": " << msg;
313 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100314}
315
316// This signal handler is for zygote mode, since the zygote must reap its children
317static void SigChldHandler(int /*signal_number*/) {
318 pid_t pid;
319 int status;
Chris Wailes7e797b62019-02-22 18:29:22 -0800320 int64_t usaps_removed = 0;
Narayan Kamath973b4662014-03-31 13:41:26 +0100321
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700322 // It's necessary to save and restore the errno during this function.
323 // Since errno is stored per thread, changing it here modifies the errno
324 // on the thread on which this signal handler executes. If a signal occurs
325 // between a call and an errno check, it's possible to get the errno set
326 // here.
327 // See b/23572286 for extra information.
328 int saved_errno = errno;
329
Narayan Kamath973b4662014-03-31 13:41:26 +0100330 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800331 // Log process-death status that we care about.
Narayan Kamath973b4662014-03-31 13:41:26 +0100332 if (WIFEXITED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800333 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
334 "Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Chris Wailesf68c4e22019-06-05 16:07:50 -0700335
336 // Check to see if the PID is in the USAP pool and remove it if it is.
337 if (RemoveUsapTableEntry(pid)) {
338 ++usaps_removed;
339 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100340 } else if (WIFSIGNALED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800341 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
342 "Process %d exited due to signal %d (%s)%s", pid,
343 WTERMSIG(status), strsignal(WTERMSIG(status)),
344 WCOREDUMP(status) ? "; core dumped" : "");
Chris Wailesf68c4e22019-06-05 16:07:50 -0700345
346 // If the process exited due to a signal other than SIGTERM, check to see
347 // if the PID is in the USAP pool and remove it if it is. If the process
348 // was closed by the Zygote using SIGTERM then the USAP pool entry will
349 // have already been removed (see nativeEmptyUsapPool()).
350 if (WTERMSIG(status) != SIGTERM && RemoveUsapTableEntry(pid)) {
351 ++usaps_removed;
352 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100353 }
354
355 // If the just-crashed process is the system_server, bring down zygote
356 // so that it is restarted by init and system server will be restarted
357 // from there.
358 if (pid == gSystemServerPid) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800359 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
360 "Exit zygote because system server (pid %d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100361 kill(getpid(), SIGKILL);
362 }
363 }
364
Narayan Kamath160992d2014-04-14 14:46:07 +0100365 // Note that we shouldn't consider ECHILD an error because
366 // the secondary zygote might have no children left to wait for.
367 if (pid < 0 && errno != ECHILD) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800368 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG,
369 "Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100370 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700371
Chris Wailes7e797b62019-02-22 18:29:22 -0800372 if (usaps_removed > 0) {
Chris Wailesfe3a3482019-03-13 14:38:04 -0700373 if (TEMP_FAILURE_RETRY(write(gUsapPoolEventFD, &usaps_removed, sizeof(usaps_removed))) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800374 // If this write fails something went terribly wrong. We will now kill
375 // the zygote and let the system bring it back up.
wangmingming16d0dd1a2018-11-14 10:43:36 +0800376 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
Chris Wailes7e797b62019-02-22 18:29:22 -0800377 "Zygote failed to write to USAP pool event FD: %s",
wangmingming16d0dd1a2018-11-14 10:43:36 +0800378 strerror(errno));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800379 kill(getpid(), SIGKILL);
380 }
381 }
382
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700383 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100384}
385
yuanhao435e84b2018-01-15 15:37:02 +0800386// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
387// configured very late, because earlier in the runtime we may fork() and
388// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100389// have them be harvested immediately.
390//
yuanhao435e84b2018-01-15 15:37:02 +0800391// Ignore SIGHUP because all processes forked by the zygote are in the same
392// process group as the zygote and we don't want to be notified if we become
393// an orphaned group and have one or more stopped processes. This is not a
394// theoretical concern :
395// - we can become an orphaned group if one of our direct descendants forks
396// and is subsequently killed before its children.
397// - crash_dump routinely STOPs the process it's tracing.
398//
399// See issues b/71965619 and b/25567761 for further details.
400//
Narayan Kamath973b4662014-03-31 13:41:26 +0100401// This ends up being called repeatedly before each fork(), but there's
402// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800403static void SetSignalHandlers() {
404 struct sigaction sig_chld = {};
405 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100406
Chris Wailesaa1c9622019-01-10 16:55:32 -0800407 if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700408 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100409 }
yuanhao435e84b2018-01-15 15:37:02 +0800410
411 struct sigaction sig_hup = {};
412 sig_hup.sa_handler = SIG_IGN;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800413 if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
yuanhao435e84b2018-01-15 15:37:02 +0800414 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
415 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100416}
417
418// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800419static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100420 struct sigaction sa;
421 memset(&sa, 0, sizeof(sa));
422 sa.sa_handler = SIG_DFL;
423
Chris Wailesaa1c9622019-01-10 16:55:32 -0800424 if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700425 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100426 }
427}
428
429// Calls POSIX setgroups() using the int[] object as an argument.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800430// A nullptr argument is tolerated.
431static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) {
432 if (managed_gids == nullptr) {
433 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100434 }
435
Chris Wailesaa1c9622019-01-10 16:55:32 -0800436 ScopedIntArrayRO gids(env, managed_gids);
437 if (gids.get() == nullptr) {
438 fail_fn(CREATE_ERROR("Getting gids int array failed"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100439 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700440
Chris Wailesaa1c9622019-01-10 16:55:32 -0800441 if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
442 fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
443 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100444}
445
446// Sets the resource limits via setrlimit(2) for the values in the
447// two-dimensional array of integers that's passed in. The second dimension
Chris Wailesaa1c9622019-01-10 16:55:32 -0800448// contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
Narayan Kamath973b4662014-03-31 13:41:26 +0100449// treated as an empty array.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800450static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
451 if (managed_rlimits == nullptr) {
452 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100453 }
454
455 rlimit rlim;
456 memset(&rlim, 0, sizeof(rlim));
457
Chris Wailesaa1c9622019-01-10 16:55:32 -0800458 for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
459 ScopedLocalRef<jobject>
460 managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
461 ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
462
463 if (rlimit_handle.size() != 3) {
464 fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100465 }
466
Chris Wailesaa1c9622019-01-10 16:55:32 -0800467 rlim.rlim_cur = rlimit_handle[1];
468 rlim.rlim_max = rlimit_handle[2];
Narayan Kamath973b4662014-03-31 13:41:26 +0100469
Chris Wailesaa1c9622019-01-10 16:55:32 -0800470 if (setrlimit(rlimit_handle[0], &rlim) == -1) {
471 fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
472 rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
Narayan Kamath973b4662014-03-31 13:41:26 +0100473 }
474 }
475}
476
Orion Hodson8d005a62018-12-05 12:28:53 +0000477static void EnableDebugger() {
478 // To let a non-privileged gdbserver attach to this
479 // process, we must set our dumpable flag.
480 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
481 ALOGE("prctl(PR_SET_DUMPABLE) failed");
482 }
483
484 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
485 // is enabled (see kernel/Documentation/security/Yama.txt).
486 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
487 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
488 // case since it's expected behaviour.
489 if (errno != EINVAL) {
490 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
491 }
492 }
493
Orion Hodson2b71ad02018-12-07 16:44:33 +0000494 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
495 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
496 // Set the soft limit on core dump size to 0 without changing the hard limit.
497 rlimit rl;
498 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
499 ALOGE("getrlimit(RLIMIT_CORE) failed");
500 } else {
501 rl.rlim_cur = 0;
502 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
503 ALOGE("setrlimit(RLIMIT_CORE) failed");
504 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000505 }
506 }
507}
508
Christopher Ferris76de39e2017-06-20 16:13:40 -0700509static void PreApplicationInit() {
510 // The child process sets this to indicate it's not the zygote.
Christopher Ferrisc00c1cf2019-04-09 16:42:32 -0700511 android_mallopt(M_SET_ZYGOTE_CHILD, nullptr, 0);
Christopher Ferris76de39e2017-06-20 16:13:40 -0700512
513 // Set the jemalloc decay time to 1.
514 mallopt(M_DECAY_TIME, 1);
515}
516
Martijn Coenen86f08a52019-01-03 16:23:01 +0100517static void SetUpSeccompFilter(uid_t uid, bool is_child_zygote) {
Chris Wailes6d482d542019-04-03 13:00:52 -0700518 if (!gIsSecurityEnforced) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800519 ALOGI("seccomp disabled by setenforce 0");
520 return;
521 }
522
523 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700524 if (uid >= AID_APP_START) {
Martijn Coenen86f08a52019-01-03 16:23:01 +0100525 if (is_child_zygote) {
Martijn Coenen6ef16802019-01-18 16:40:01 +0100526 set_app_zygote_seccomp_filter();
Martijn Coenen86f08a52019-01-03 16:23:01 +0100527 } else {
528 set_app_seccomp_filter();
529 }
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800530 } else {
531 set_system_seccomp_filter();
532 }
533}
534
Chris Wailesaa1c9622019-01-10 16:55:32 -0800535static void EnableKeepCapabilities(fail_fn_t fail_fn) {
536 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
537 fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100538 }
539}
540
Chris Wailesaa1c9622019-01-10 16:55:32 -0800541static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
542 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
543 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100544 if (errno == EINVAL) {
545 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
546 "your kernel is compiled with file capabilities support");
547 } else {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800548 fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100549 }
550 }
551 }
552}
553
Chris Wailesaa1c9622019-01-10 16:55:32 -0800554static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
Josh Gao45dab782017-02-01 14:56:09 -0800555 __user_cap_header_struct capheader;
556 memset(&capheader, 0, sizeof(capheader));
557 capheader.version = _LINUX_CAPABILITY_VERSION_3;
558 capheader.pid = 0;
559
560 __user_cap_data_struct capdata[2];
561 if (capget(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800562 fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800563 }
564
565 capdata[0].inheritable = inheritable;
566 capdata[1].inheritable = inheritable >> 32;
567
568 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800569 fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800570 }
571}
572
Chris Wailesaa1c9622019-01-10 16:55:32 -0800573static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
574 fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100575 __user_cap_header_struct capheader;
576 memset(&capheader, 0, sizeof(capheader));
577 capheader.version = _LINUX_CAPABILITY_VERSION_3;
578 capheader.pid = 0;
579
580 __user_cap_data_struct capdata[2];
581 memset(&capdata, 0, sizeof(capdata));
582 capdata[0].effective = effective;
583 capdata[1].effective = effective >> 32;
584 capdata[0].permitted = permitted;
585 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800586 capdata[0].inheritable = inheritable;
587 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100588
589 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800590 fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
591 "failed: %s", permitted, effective, inheritable, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100592 }
593}
594
Chris Wailesaa1c9622019-01-10 16:55:32 -0800595static void SetSchedulerPolicy(fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100596 errno = -set_sched_policy(0, SP_DEFAULT);
597 if (errno != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800598 fail_fn(CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100599 }
600}
601
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700602static int UnmountTree(const char* path) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600603 ATRACE_CALL();
604
Sudheer Shanka74584a52019-02-22 13:04:41 -0800605 size_t path_len = strlen(path);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700606
Sudheer Shanka74584a52019-02-22 13:04:41 -0800607 FILE* fp = setmntent("/proc/mounts", "r");
608 if (fp == nullptr) {
609 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
610 return -errno;
611 }
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700612
Sudheer Shanka74584a52019-02-22 13:04:41 -0800613 // Some volumes can be stacked on each other, so force unmount in
614 // reverse order to give us the best chance of success.
615 std::list<std::string> to_unmount;
616 mntent* mentry;
617 while ((mentry = getmntent(fp)) != nullptr) {
618 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
619 to_unmount.push_front(std::string(mentry->mnt_dir));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700620 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800621 }
622 endmntent(fp);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700623
Sudheer Shanka74584a52019-02-22 13:04:41 -0800624 for (const auto& path : to_unmount) {
625 if (umount2(path.c_str(), MNT_DETACH)) {
626 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700627 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800628 }
629 return 0;
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700630}
631
Narayan Kamath973b4662014-03-31 13:41:26 +0100632// Create a private mount namespace and bind mount appropriate emulated
633// storage for the given user.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800634static void MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shanka64501e52019-04-29 10:46:26 -0700635 bool force_mount_namespace,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800636 fail_fn_t fail_fn) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800637 // See storage config details at http://source.android.com/tech/storage/
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600638 ATRACE_CALL();
Jeff Sharkey9527b222015-06-24 15:24:48 -0700639
Sudheer Shanka74584a52019-02-22 13:04:41 -0800640 String8 storage_source;
641 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
642 storage_source = "/mnt/runtime/default";
643 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
644 storage_source = "/mnt/runtime/read";
Sudheer Shanka783c90e2019-04-12 13:55:20 -0700645 } else if (mount_mode == MOUNT_EXTERNAL_WRITE
646 || mount_mode == MOUNT_EXTERNAL_LEGACY
647 || mount_mode == MOUNT_EXTERNAL_INSTALLER) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800648 storage_source = "/mnt/runtime/write";
Sudheer Shanka783c90e2019-04-12 13:55:20 -0700649 } else if (mount_mode == MOUNT_EXTERNAL_FULL) {
650 storage_source = "/mnt/runtime/full";
Sudheer Shanka74584a52019-02-22 13:04:41 -0800651 } else if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
652 // Sane default of no storage visible
653 return;
654 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400655
Sudheer Shanka74584a52019-02-22 13:04:41 -0800656 // Create a second private mount namespace for our process
657 if (unshare(CLONE_NEWNS) == -1) {
658 fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
659 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400660
Sudheer Shanka74584a52019-02-22 13:04:41 -0800661 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
662 if (mount_mode == MOUNT_EXTERNAL_NONE) {
663 return;
664 }
Robert Sesek06f39302017-03-20 17:30:05 -0400665
Sudheer Shanka64501e52019-04-29 10:46:26 -0700666 if (TEMP_FAILURE_RETRY(mount(storage_source.string(), "/storage", nullptr,
667 MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
668 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
669 storage_source.string(),
670 strerror(errno)));
671 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700672
Sudheer Shanka64501e52019-04-29 10:46:26 -0700673 // Mount user-specific symlink helper into place
674 userid_t user_id = multiuser_get_user_id(uid);
675 const String8 user_source(String8::format("/mnt/user/%d", user_id));
676 if (fs_prepare_dir(user_source.string(), 0751, 0, 0) == -1) {
677 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s",
678 user_source.string()));
679 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800680
Sudheer Shanka64501e52019-04-29 10:46:26 -0700681 if (TEMP_FAILURE_RETRY(mount(user_source.string(), "/storage/self",
682 nullptr, MS_BIND, nullptr)) == -1) {
683 fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
684 user_source.string(), strerror(errno)));
Sudheer Shanka74584a52019-02-22 13:04:41 -0800685 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100686}
687
Narayan Kamath973b4662014-03-31 13:41:26 +0100688static bool NeedsNoRandomizeWorkaround() {
689#if !defined(__arm__)
690 return false;
691#else
692 int major;
693 int minor;
694 struct utsname uts;
695 if (uname(&uts) == -1) {
696 return false;
697 }
698
699 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
700 return false;
701 }
702
703 // Kernels before 3.4.* need the workaround.
704 return (major < 3) || ((major == 3) && (minor < 4));
705#endif
706}
Narayan Kamath973b4662014-03-31 13:41:26 +0100707
708// Utility to close down the Zygote socket file descriptors while
709// the child is still running as root with Zygote's privileges. Each
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800710// descriptor (if any) is closed via dup3(), replacing it with a valid
Narayan Kamath973b4662014-03-31 13:41:26 +0100711// (open) descriptor to /dev/null.
712
Chris Wailesaa1c9622019-01-10 16:55:32 -0800713static void DetachDescriptors(JNIEnv* env,
714 const std::vector<int>& fds_to_close,
715 fail_fn_t fail_fn) {
716
717 if (fds_to_close.size() > 0) {
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800718 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800719 if (devnull_fd == -1) {
720 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100721 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800722
723 for (int fd : fds_to_close) {
724 ALOGV("Switching descriptor %d to /dev/null", fd);
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800725 if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
726 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800727 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100728 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100729 }
730}
731
Chris Wailesaa1c9622019-01-10 16:55:32 -0800732void SetThreadName(const std::string& thread_name) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100733 bool hasAt = false;
734 bool hasDot = false;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800735
736 for (const char str_el : thread_name) {
737 if (str_el == '.') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100738 hasDot = true;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800739 } else if (str_el == '@') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100740 hasAt = true;
741 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100742 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800743
744 const char* name_start_ptr = thread_name.c_str();
745 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
746 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
Narayan Kamath973b4662014-03-31 13:41:26 +0100747 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800748
Narayan Kamath973b4662014-03-31 13:41:26 +0100749 // pthread_setname_np fails rather than truncating long strings.
750 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
Chris Wailesaa1c9622019-01-10 16:55:32 -0800751 strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
Narayan Kamath973b4662014-03-31 13:41:26 +0100752 errno = pthread_setname_np(pthread_self(), buf);
753 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700754 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100755 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800756 // Update base::logging default tag.
757 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100758}
759
Chris Wailesaa1c9622019-01-10 16:55:32 -0800760/**
761 * A failure function used to report fatal errors to the managed runtime. This
762 * function is often curried with the process name information and then passed
763 * to called functions.
764 *
765 * @param env Managed runtime environment
766 * @param process_name A native representation of the process name
767 * @param managed_process_name A managed representation of the process name
768 * @param msg The error message to be reported
769 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700770[[noreturn]]
771static void ZygoteFailure(JNIEnv* env,
772 const char* process_name,
773 jstring managed_process_name,
774 const std::string& msg) {
775 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
776 if (managed_process_name != nullptr) {
777 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
778 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
779 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -0700780 }
781 }
782
Chris Wailesaf594fc2018-11-02 11:00:07 -0700783 const std::string& error_msg =
784 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700785
Chris Wailesaf594fc2018-11-02 11:00:07 -0700786 env->FatalError(error_msg.c_str());
787 __builtin_unreachable();
788}
David Sehrde8d0bd2018-06-22 10:45:36 -0700789
Chris Wailesaa1c9622019-01-10 16:55:32 -0800790/**
791 * A helper method for converting managed strings to native strings. A fatal
792 * error is generated if a problem is encountered in extracting a non-null
793 * string.
794 *
795 * @param env Managed runtime environment
796 * @param process_name A native representation of the process name
797 * @param managed_process_name A managed representation of the process name
798 * @param managed_string The managed string to extract
799 *
800 * @return An empty option if the managed string is null. A optional-wrapped
801 * string otherwise.
802 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700803static std::optional<std::string> ExtractJString(JNIEnv* env,
804 const char* process_name,
805 jstring managed_process_name,
806 jstring managed_string) {
807 if (managed_string == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800808 return std::nullopt;
Chris Wailesaf594fc2018-11-02 11:00:07 -0700809 } else {
810 ScopedUtfChars scoped_string_chars(env, managed_string);
811
812 if (scoped_string_chars.c_str() != nullptr) {
813 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700814 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -0700815 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700816 }
817 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700818}
819
Chris Wailesaa1c9622019-01-10 16:55:32 -0800820/**
821 * A helper method for converting managed string arrays to native vectors. A
822 * fatal error is generated if a problem is encountered in extracting a non-null array.
823 *
824 * @param env Managed runtime environment
825 * @param process_name A native representation of the process name
826 * @param managed_process_name A managed representation of the process name
827 * @param managed_array The managed integer array to extract
828 *
829 * @return An empty option if the managed array is null. A optional-wrapped
830 * vector otherwise.
831 */
832static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
833 const char* process_name,
834 jstring managed_process_name,
835 jintArray managed_array) {
836 if (managed_array == nullptr) {
837 return std::nullopt;
838 } else {
839 ScopedIntArrayRO managed_array_handle(env, managed_array);
Narayan Kamath973b4662014-03-31 13:41:26 +0100840
Chris Wailesaa1c9622019-01-10 16:55:32 -0800841 if (managed_array_handle.get() != nullptr) {
842 std::vector<int> native_array;
843 native_array.reserve(managed_array_handle.size());
844
845 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
846 native_array.push_back(managed_array_handle[array_index]);
847 }
848
849 return std::move(native_array);
850
851 } else {
852 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
853 }
854 }
855}
856
857/**
Chris Wailesaa1c9622019-01-10 16:55:32 -0800858 * A utility function for blocking signals.
859 *
860 * @param signum Signal number to block
861 * @param fail_fn Fatal error reporting function
862 *
863 * @see ZygoteFailure
864 */
865static void BlockSignal(int signum, fail_fn_t fail_fn) {
866 sigset_t sigs;
867 sigemptyset(&sigs);
868 sigaddset(&sigs, signum);
869
870 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
871 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
872 }
873}
874
875
876/**
877 * A utility function for unblocking signals.
878 *
879 * @param signum Signal number to unblock
880 * @param fail_fn Fatal error reporting function
881 *
882 * @see ZygoteFailure
883 */
884static void UnblockSignal(int signum, fail_fn_t fail_fn) {
885 sigset_t sigs;
886 sigemptyset(&sigs);
887 sigaddset(&sigs, signum);
888
889 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
890 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
891 }
892}
893
Chris Wailes7e797b62019-02-22 18:29:22 -0800894static void ClearUsapTable() {
895 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -0800896 entry.Clear();
897 }
898
Chris Wailes7e797b62019-02-22 18:29:22 -0800899 gUsapPoolCount = 0;
Chris Wailesae937142019-01-24 12:57:33 -0800900}
901
Chris Wailesaa1c9622019-01-10 16:55:32 -0800902// Utility routine to fork a process from the zygote.
903static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
904 const std::vector<int>& fds_to_close,
Mathew Inwood51c53b42019-05-24 14:06:10 +0100905 const std::vector<int>& fds_to_ignore) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800906 SetSignalHandlers();
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000907
Chris Wailesaf594fc2018-11-02 11:00:07 -0700908 // Curry a failure function.
909 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
910 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -0700911
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000912 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
913 // log, which would result in the logging FDs we close being reopened.
914 // This would cause failures because the FDs are not whitelisted.
915 //
916 // Note that the zygote process is single threaded at this point.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800917 BlockSignal(SIGCHLD, fail_fn);
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000918
Narayan Kamath3764a262016-08-30 15:36:19 +0100919 // Close any logging related FDs before we start evaluating the list of
920 // file descriptors.
921 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -0700922 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +0100923
Chris Wailesaf594fc2018-11-02 11:00:07 -0700924 // If this is the first fork for this zygote, create the open FD table. If
925 // it isn't, we just need to check whether the list of open files has changed
926 // (and it shouldn't in the normal case).
Chris Wailesaf594fc2018-11-02 11:00:07 -0700927 if (gOpenFdTable == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800928 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
929 } else {
930 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100931 }
932
Josh Gaod7951102018-06-26 16:05:12 -0700933 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
934
Narayan Kamath973b4662014-03-31 13:41:26 +0100935 pid_t pid = fork();
936
937 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700938 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700939 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700940
Narayan Kamath973b4662014-03-31 13:41:26 +0100941 // Clean up any descriptors which must be closed immediately
Chris Wailesaa1c9622019-01-10 16:55:32 -0800942 DetachDescriptors(env, fds_to_close, fail_fn);
Narayan Kamath973b4662014-03-31 13:41:26 +0100943
Chris Wailes7e797b62019-02-22 18:29:22 -0800944 // Invalidate the entries in the USAP table.
945 ClearUsapTable();
Chris Wailesae937142019-01-24 12:57:33 -0800946
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100947 // Re-open all remaining open file descriptors so that they aren't shared
948 // with the zygote across a fork.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800949 gOpenFdTable->ReopenOrDetach(fail_fn);
Josh Gaod7951102018-06-26 16:05:12 -0700950
951 // Turn fdsan back on.
952 android_fdsan_set_error_level(fdsan_error_level);
Martin Stjernholma9bd8c32019-02-23 02:35:07 +0000953 } else {
954 ALOGD("Forked child process %d", pid);
David Sehrde8d0bd2018-06-22 10:45:36 -0700955 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100956
David Sehrde8d0bd2018-06-22 10:45:36 -0700957 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800958 UnblockSignal(SIGCHLD, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700959
Narayan Kamath973b4662014-03-31 13:41:26 +0100960 return pid;
961}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700962
Chris Wailesaf594fc2018-11-02 11:00:07 -0700963// Utility routine to specialize a zygote child process.
964static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
965 jint runtime_flags, jobjectArray rlimits,
966 jlong permitted_capabilities, jlong effective_capabilities,
967 jint mount_external, jstring managed_se_info,
968 jstring managed_nice_name, bool is_system_server,
969 bool is_child_zygote, jstring managed_instruction_set,
Sudheer Shanka64501e52019-04-29 10:46:26 -0700970 jstring managed_app_data_dir) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800971 const char* process_name = is_system_server ? "system_server" : "zygote";
972 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
973 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700974
975 auto se_info = extract_fn(managed_se_info);
976 auto nice_name = extract_fn(managed_nice_name);
977 auto instruction_set = extract_fn(managed_instruction_set);
978 auto app_data_dir = extract_fn(managed_app_data_dir);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700979
Chris Wailesaf594fc2018-11-02 11:00:07 -0700980 // Keep capabilities across UID change, unless we're staying root.
981 if (uid != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800982 EnableKeepCapabilities(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700983 }
984
Chris Wailesaa1c9622019-01-10 16:55:32 -0800985 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700986
Chris Wailesaa1c9622019-01-10 16:55:32 -0800987 DropCapabilitiesBoundingSet(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700988
989 bool use_native_bridge = !is_system_server &&
990 instruction_set.has_value() &&
991 android::NativeBridgeAvailable() &&
992 android::NeedsNativeBridge(instruction_set.value().c_str());
993
994 if (use_native_bridge && !app_data_dir.has_value()) {
995 // The app_data_dir variable should never be empty if we need to use a
996 // native bridge. In general, app_data_dir will never be empty for normal
997 // applications. It can only happen in special cases (for isolated
998 // processes which are not associated with any app). These are launched by
999 // the framework and should not be emulated anyway.
1000 use_native_bridge = false;
1001 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
1002 }
1003
Sudheer Shanka64501e52019-04-29 10:46:26 -07001004 MountEmulatedStorage(uid, mount_external, use_native_bridge, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001005
1006 // If this zygote isn't root, it won't be able to create a process group,
1007 // since the directory is owned by root.
1008 if (!is_system_server && getuid() == 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001009 const int rc = createProcessGroup(uid, getpid());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001010 if (rc == -EROFS) {
1011 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
1012 } else if (rc != 0) {
1013 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
1014 }
1015 }
1016
Chris Wailesaa1c9622019-01-10 16:55:32 -08001017 SetGids(env, gids, fail_fn);
1018 SetRLimits(env, rlimits, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001019
1020 if (use_native_bridge) {
1021 // Due to the logic behind use_native_bridge we know that both app_data_dir
1022 // and instruction_set contain values.
1023 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
1024 instruction_set.value().c_str());
1025 }
1026
1027 if (setresgid(gid, gid, gid) == -1) {
1028 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
1029 }
1030
1031 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
1032 // before changing uid from 0, which clears capabilities. The other
1033 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
1034 // breaks SELinux domain transition (see b/71859146). As the result,
1035 // privileged syscalls used below still need to be accessible in app process.
Martijn Coenen86f08a52019-01-03 16:23:01 +01001036 SetUpSeccompFilter(uid, is_child_zygote);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001037
1038 if (setresuid(uid, uid, uid) == -1) {
1039 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1040 }
1041
1042 // The "dumpable" flag of a process, which controls core dump generation, is
1043 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1044 // user or group ID changes. See proc(5) for possible values. In most cases,
1045 // the value is 0, so core dumps are disabled for zygote children. However,
1046 // when running in a Chrome OS container, the value is already set to 2,
1047 // which allows the external crash reporter to collect all core dumps. Since
1048 // only system crashes are interested, core dump is disabled for app
1049 // processes. This also ensures compliance with CTS.
1050 int dumpable = prctl(PR_GET_DUMPABLE);
1051 if (dumpable == -1) {
1052 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1053 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1054 }
1055
1056 if (dumpable == 2 && uid >= AID_APP) {
1057 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1058 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1059 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1060 }
1061 }
1062
Orion Hodson8d005a62018-12-05 12:28:53 +00001063 // Set process properties to enable debugging if required.
1064 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1065 EnableDebugger();
1066 }
Yabin Cui4d8546d2019-01-29 16:29:20 -08001067 if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
1068 // simpleperf needs the process to be dumpable to profile it.
1069 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
1070 ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
1071 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
1072 }
1073 }
Orion Hodson8d005a62018-12-05 12:28:53 +00001074
Chris Wailesaf594fc2018-11-02 11:00:07 -07001075 if (NeedsNoRandomizeWorkaround()) {
1076 // Work around ARM kernel ASLR lossage (http://b/5817320).
1077 int old_personality = personality(0xffffffff);
1078 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1079 if (new_personality == -1) {
1080 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1081 }
1082 }
1083
Chris Wailesaa1c9622019-01-10 16:55:32 -08001084 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001085
Chris Wailesaa1c9622019-01-10 16:55:32 -08001086 SetSchedulerPolicy(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001087
Mathieu Chartier0bccbf72019-01-30 15:56:17 -08001088 __android_log_close();
1089 stats_log_close();
1090
Chris Wailesaf594fc2018-11-02 11:00:07 -07001091 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1092 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1093
1094 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1095 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1096 uid, is_system_server, se_info_ptr, nice_name_ptr));
1097 }
1098
1099 // Make it easier to debug audit logs by setting the main thread's name to the
1100 // nice name rather than "app_process".
1101 if (nice_name.has_value()) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001102 SetThreadName(nice_name.value());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001103 } else if (is_system_server) {
1104 SetThreadName("system_server");
1105 }
1106
1107 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1108 UnsetChldSignalHandler();
1109
1110 if (is_system_server) {
Mathieu Chartier742981e2019-11-21 14:30:03 -08001111 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks, runtime_flags);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001112 if (env->ExceptionCheck()) {
1113 fail_fn("Error calling post fork system server hooks.");
1114 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001115
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07001116 // Prefetch the classloader for the system server. This is done early to
1117 // allow a tie-down of the proper system server selinux domain.
1118 env->CallStaticVoidMethod(gZygoteInitClass, gCreateSystemServerClassLoader);
1119 if (env->ExceptionCheck()) {
1120 // Be robust here. The Java code will attempt to create the classloader
1121 // at a later point (but may not have rights to use AoT artifacts).
1122 env->ExceptionClear();
1123 }
1124
Chris Wailesaf594fc2018-11-02 11:00:07 -07001125 // TODO(oth): Remove hardcoded label here (b/117874058).
1126 static const char* kSystemServerLabel = "u:r:system_server:s0";
1127 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1128 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1129 }
1130 }
1131
1132 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1133 is_system_server, is_child_zygote, managed_instruction_set);
1134
1135 if (env->ExceptionCheck()) {
1136 fail_fn("Error calling post fork hooks.");
1137 }
1138}
1139
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001140static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1141 __user_cap_header_struct capheader;
1142 memset(&capheader, 0, sizeof(capheader));
1143 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1144 capheader.pid = 0;
1145
1146 __user_cap_data_struct capdata[2];
1147 if (capget(&capheader, &capdata[0]) == -1) {
1148 ALOGE("capget failed: %s", strerror(errno));
1149 RuntimeAbort(env, __LINE__, "capget failed");
1150 }
1151
Chris Wailesaf594fc2018-11-02 11:00:07 -07001152 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1153}
1154
1155static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1156 bool is_child_zygote) {
1157 jlong capabilities = 0;
1158
1159 /*
1160 * Grant the following capabilities to the Bluetooth user:
1161 * - CAP_WAKE_ALARM
Nitin Shivpure99cec9d2019-05-29 14:02:49 +05301162 * - CAP_NET_ADMIN
Chris Wailesaf594fc2018-11-02 11:00:07 -07001163 * - CAP_NET_RAW
1164 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1165 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1166 */
1167
1168 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1169 capabilities |= (1LL << CAP_WAKE_ALARM);
Nitin Shivpure99cec9d2019-05-29 14:02:49 +05301170 capabilities |= (1LL << CAP_NET_ADMIN);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001171 capabilities |= (1LL << CAP_NET_RAW);
1172 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1173 capabilities |= (1LL << CAP_SYS_NICE);
1174 }
1175
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001176 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1177 capabilities |= (1LL << CAP_NET_ADMIN);
1178 capabilities |= (1LL << CAP_NET_BROADCAST);
1179 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1180 capabilities |= (1LL << CAP_NET_RAW);
1181 }
1182
Chris Wailesaf594fc2018-11-02 11:00:07 -07001183 /*
1184 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1185 */
1186
1187 bool gid_wakelock_found = false;
1188 if (gid == AID_WAKELOCK) {
1189 gid_wakelock_found = true;
1190 } else if (gids != nullptr) {
1191 jsize gids_num = env->GetArrayLength(gids);
1192 ScopedIntArrayRO native_gid_proxy(env, gids);
1193
1194 if (native_gid_proxy.get() == nullptr) {
1195 RuntimeAbort(env, __LINE__, "Bad gids array");
1196 }
1197
Chris Wailes31c52c92019-02-14 11:20:02 -08001198 for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
1199 if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001200 gid_wakelock_found = true;
1201 break;
1202 }
1203 }
1204 }
1205
1206 if (gid_wakelock_found) {
1207 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1208 }
1209
1210 /*
1211 * Grant child Zygote processes the following capabilities:
1212 * - CAP_SETUID (change UID of child processes)
1213 * - CAP_SETGID (change GID of child processes)
1214 * - CAP_SETPCAP (change capabilities of child processes)
1215 */
1216
1217 if (is_child_zygote) {
1218 capabilities |= (1LL << CAP_SETUID);
1219 capabilities |= (1LL << CAP_SETGID);
1220 capabilities |= (1LL << CAP_SETPCAP);
1221 }
1222
1223 /*
1224 * Containers run without some capabilities, so drop any caps that are not
1225 * available.
1226 */
1227
1228 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001229}
Chris Wailesaa1c9622019-01-10 16:55:32 -08001230
1231/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001232 * Adds the given information about a newly created unspecialized app
1233 * processes to the Zygote's USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001234 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001235 * @param usap_pid Process ID of the newly created USAP
1236 * @param read_pipe_fd File descriptor for the read end of the USAP
1237 * reporting pipe. Used in the ZygoteServer poll loop to track USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001238 * specialization.
1239 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001240static void AddUsapTableEntry(pid_t usap_pid, int read_pipe_fd) {
1241 static int sUsapTableInsertIndex = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001242
Chris Wailes7e797b62019-02-22 18:29:22 -08001243 int search_index = sUsapTableInsertIndex;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001244
1245 do {
Chris Wailes7e797b62019-02-22 18:29:22 -08001246 if (gUsapTable[search_index].SetIfInvalid(usap_pid, read_pipe_fd)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001247 // Start our next search right after where we finished this one.
Chris Wailes7e797b62019-02-22 18:29:22 -08001248 sUsapTableInsertIndex = (search_index + 1) % gUsapTable.size();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001249
1250 return;
1251 }
1252
Chris Wailes7e797b62019-02-22 18:29:22 -08001253 search_index = (search_index + 1) % gUsapTable.size();
1254 } while (search_index != sUsapTableInsertIndex);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001255
1256 // Much like money in the banana stand, there should always be an entry
Chris Wailes7e797b62019-02-22 18:29:22 -08001257 // in the USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001258 __builtin_unreachable();
1259}
1260
1261/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001262 * Invalidates the entry in the USAPTable corresponding to the provided
1263 * process ID if it is present. If an entry was removed the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001264 * count is decremented.
1265 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001266 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001267 * @return True if an entry was invalidated; false otherwise
1268 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001269static bool RemoveUsapTableEntry(pid_t usap_pid) {
1270 for (UsapTableEntry& entry : gUsapTable) {
1271 if (entry.ClearForPID(usap_pid)) {
1272 --gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001273 return true;
1274 }
1275 }
1276
1277 return false;
1278}
1279
1280/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001281 * @return A vector of the read pipe FDs for each of the active USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001282 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001283std::vector<int> MakeUsapPipeReadFDVector() {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001284 std::vector<int> fd_vec;
Chris Wailes7e797b62019-02-22 18:29:22 -08001285 fd_vec.reserve(gUsapTable.size());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001286
Chris Wailes7e797b62019-02-22 18:29:22 -08001287 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001288 auto entry_values = entry.GetValues();
1289
1290 if (entry_values.has_value()) {
1291 fd_vec.push_back(entry_values.value().read_pipe_fd);
1292 }
1293 }
1294
1295 return fd_vec;
1296}
1297
Chris Wailes6d482d542019-04-03 13:00:52 -07001298static void UnmountStorageOnInit(JNIEnv* env) {
1299 // Zygote process unmount root storage space initially before every child processes are forked.
1300 // Every forked child processes (include SystemServer) only mount their own root storage space
1301 // and no need unmount storage operation in MountEmulatedStorage method.
1302 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1303
1304 // See storage config details at http://source.android.com/tech/storage/
1305 // Create private mount namespace shared by all children
1306 if (unshare(CLONE_NEWNS) == -1) {
1307 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1308 return;
1309 }
1310
1311 // Mark rootfs as being a slave so that changes from default
1312 // namespace only flow into our children.
1313 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1314 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1315 return;
1316 }
1317
1318 // Create a staging tmpfs that is shared by our children; they will
1319 // bind mount storage into their respective private namespaces, which
1320 // are isolated from each other.
1321 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1322 if (target_base != nullptr) {
1323#define STRINGIFY_UID(x) __STRING(x)
1324 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1325 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1326 ALOGE("Failed to mount tmpfs to %s", target_base);
1327 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1328 return;
1329 }
1330#undef STRINGIFY_UID
1331 }
1332
1333 UnmountTree("/storage");
1334}
1335
Narayan Kamath973b4662014-03-31 13:41:26 +01001336} // anonymous namespace
1337
1338namespace android {
1339
Christopher Ferris76de39e2017-06-20 16:13:40 -07001340static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1341 PreApplicationInit();
1342}
1343
Narayan Kamath973b4662014-03-31 13:41:26 +01001344static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1345 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001346 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001347 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001348 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001349 jstring instruction_set, jstring app_data_dir) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001350 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001351
Chris Wailesaa1c9622019-01-10 16:55:32 -08001352 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1353 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1354 }
1355
1356 std::vector<int> fds_to_close =
1357 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1358 std::vector<int> fds_to_ignore =
1359 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1360 .value_or(std::vector<int>());
1361
Chris Wailes7e797b62019-02-22 18:29:22 -08001362 std::vector<int> usap_pipes = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001363
Chris Wailes7e797b62019-02-22 18:29:22 -08001364 fds_to_close.insert(fds_to_close.end(), usap_pipes.begin(), usap_pipes.end());
1365 fds_to_ignore.insert(fds_to_ignore.end(), usap_pipes.begin(), usap_pipes.end());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001366
Chris Wailes7e797b62019-02-22 18:29:22 -08001367 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001368
Chris Wailes7e797b62019-02-22 18:29:22 -08001369 if (gUsapPoolEventFD != -1) {
1370 fds_to_close.push_back(gUsapPoolEventFD);
1371 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001372 }
1373
Mathew Inwood51c53b42019-05-24 14:06:10 +01001374 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001375
David Sehrde8d0bd2018-06-22 10:45:36 -07001376 if (pid == 0) {
1377 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1378 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001379 mount_external, se_info, nice_name, false,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001380 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
David Sehrde8d0bd2018-06-22 10:45:36 -07001381 }
1382 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001383}
1384
1385static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1386 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001387 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1388 jlong effective_capabilities) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001389 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001390 fds_to_ignore(fds_to_close);
1391
Chris Wailes7e797b62019-02-22 18:29:22 -08001392 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001393
Chris Wailes7e797b62019-02-22 18:29:22 -08001394 if (gUsapPoolEventFD != -1) {
1395 fds_to_close.push_back(gUsapPoolEventFD);
1396 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001397 }
1398
Chris Wailesaf594fc2018-11-02 11:00:07 -07001399 pid_t pid = ForkCommon(env, true,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001400 fds_to_close,
Mathew Inwood51c53b42019-05-24 14:06:10 +01001401 fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001402 if (pid == 0) {
1403 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001404 permitted_capabilities, effective_capabilities,
1405 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001406 false, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001407 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001408 // The zygote process checks whether the child process has died or not.
1409 ALOGI("System server process %d has been created", pid);
1410 gSystemServerPid = pid;
1411 // There is a slight window that the system server process has crashed
1412 // but it went unnoticed because we haven't published its pid yet. So
1413 // we recheck here just to make sure that all is well.
1414 int status;
1415 if (waitpid(pid, &status, WNOHANG) == pid) {
1416 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001417 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001418 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001419
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001420 if (UsePerAppMemcg()) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001421 // Assign system_server to the correct memory cgroup.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001422 // Not all devices mount memcg so check if it is mounted first
Minchan Kim5fa8af22018-06-27 11:32:40 +09001423 // to avoid unnecessarily printing errors and denials in the logs.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001424 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
1425 ALOGE("couldn't add process %d into system memcg group", pid);
Minchan Kim5fa8af22018-06-27 11:32:40 +09001426 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001427 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001428 }
1429 return pid;
1430}
1431
Chris Wailesaa1c9622019-01-10 16:55:32 -08001432/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001433 * A JNI function that forks an unspecialized app process from the Zygote while
1434 * ensuring proper file descriptor hygiene.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001435 *
1436 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001437 * @param read_pipe_fd The read FD for the USAP reporting pipe. Manually closed by blastlas
Chris Wailesaa1c9622019-01-10 16:55:32 -08001438 * in managed code.
Chris Wailes7e797b62019-02-22 18:29:22 -08001439 * @param write_pipe_fd The write FD for the USAP reporting pipe. Manually closed by the
Chris Wailesaa1c9622019-01-10 16:55:32 -08001440 * zygote in managed code.
1441 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
Chris Wailes7e797b62019-02-22 18:29:22 -08001442 * the FD hygiene code and automatically "closed" in the new USAP.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001443 * @return
1444 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001445static jint com_android_internal_os_Zygote_nativeForkUsap(JNIEnv* env,
1446 jclass,
1447 jint read_pipe_fd,
1448 jint write_pipe_fd,
Mathew Inwood51c53b42019-05-24 14:06:10 +01001449 jintArray managed_session_socket_fds) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001450 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001451 fds_to_ignore(fds_to_close);
1452
1453 std::vector<int> session_socket_fds =
Chris Wailes7e797b62019-02-22 18:29:22 -08001454 ExtractJIntArray(env, "USAP", nullptr, managed_session_socket_fds)
Chris Wailesaa1c9622019-01-10 16:55:32 -08001455 .value_or(std::vector<int>());
1456
Chris Wailes7e797b62019-02-22 18:29:22 -08001457 // The USAP Pool Event FD is created during the initialization of the
1458 // USAP pool and should always be valid here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001459
1460 fds_to_close.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08001461 fds_to_close.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001462 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
1463
1464 fds_to_ignore.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08001465 fds_to_ignore.push_back(gUsapPoolSocketFD);
1466 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001467 fds_to_ignore.push_back(read_pipe_fd);
1468 fds_to_ignore.push_back(write_pipe_fd);
1469 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
1470
Mathew Inwood51c53b42019-05-24 14:06:10 +01001471 pid_t usap_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001472
Chris Wailes7e797b62019-02-22 18:29:22 -08001473 if (usap_pid != 0) {
1474 ++gUsapPoolCount;
1475 AddUsapTableEntry(usap_pid, read_pipe_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001476 }
1477
Chris Wailes7e797b62019-02-22 18:29:22 -08001478 return usap_pid;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001479}
1480
Robert Sesek54e387d2016-12-02 17:27:50 -05001481static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1482 JNIEnv* env, jclass, jstring path) {
1483 ScopedUtfChars path_native(env, path);
1484 const char* path_cstr = path_native.c_str();
1485 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001486 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001487 }
1488 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1489}
1490
Martijn Coenen86f08a52019-01-03 16:23:01 +01001491static void com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(
1492 JNIEnv* env, jclass, jint uidGidMin, jint uidGidMax) {
Chris Wailes6d482d542019-04-03 13:00:52 -07001493 if (!gIsSecurityEnforced) {
Martijn Coenen86f08a52019-01-03 16:23:01 +01001494 ALOGI("seccomp disabled by setenforce 0");
1495 return;
1496 }
1497
Martijn Coenen86f08a52019-01-03 16:23:01 +01001498 bool installed = install_setuidgid_seccomp_filter(uidGidMin, uidGidMax);
1499 if (!installed) {
1500 RuntimeAbort(env, __LINE__, "Could not install setuid/setgid seccomp filter.");
1501 }
Martijn Coenen86f08a52019-01-03 16:23:01 +01001502}
1503
Chris Wailesaa1c9622019-01-10 16:55:32 -08001504/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001505 * Called from an unspecialized app process to specialize the process for a
1506 * given application.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001507 *
1508 * @param env Managed runtime environment
1509 * @param uid User ID of the new application
1510 * @param gid Group ID of the new application
1511 * @param gids Extra groups that the process belongs to
1512 * @param runtime_flags Flags for changing the behavior of the managed runtime
1513 * @param rlimits Resource limits
1514 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
1515 * @param se_info SELinux policy information
1516 * @param nice_name New name for this process
1517 * @param is_child_zygote If the process is to become a WebViewZygote
1518 * @param instruction_set The instruction set expected/requested by the new application
1519 * @param app_data_dir Path to the application's data directory
1520 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001521static void com_android_internal_os_Zygote_nativeSpecializeAppProcess(
Chris Wailesaa1c9622019-01-10 16:55:32 -08001522 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
1523 jint runtime_flags, jobjectArray rlimits,
1524 jint mount_external, jstring se_info, jstring nice_name,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001525 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001526 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
1527
1528 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1529 capabilities, capabilities,
1530 mount_external, se_info, nice_name, false,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001531 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001532}
1533
1534/**
1535 * A helper method for fetching socket file descriptors that were opened by init from the
1536 * environment.
1537 *
1538 * @param env Managed runtime environment
1539 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
1540 * of the environment variable storing the file descriptors.
1541 */
Chris Wailes6d482d542019-04-03 13:00:52 -07001542static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv* env, jclass,
1543 jboolean is_primary) {
1544 /*
1545 * Obtain file descriptors created by init from the environment.
1546 */
1547
Chris Wailesaa1c9622019-01-10 16:55:32 -08001548 std::string android_socket_prefix(ANDROID_SOCKET_PREFIX);
1549 std::string env_var_name = android_socket_prefix + (is_primary ? "zygote" : "zygote_secondary");
1550 char* env_var_val = getenv(env_var_name.c_str());
1551
1552 if (env_var_val != nullptr) {
1553 gZygoteSocketFD = atoi(env_var_val);
1554 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
1555 } else {
1556 ALOGE("Unable to fetch Zygote socket file descriptor");
1557 }
1558
Chris Wailes7e797b62019-02-22 18:29:22 -08001559 env_var_name = android_socket_prefix + (is_primary ? "usap_pool_primary" : "usap_pool_secondary");
Chris Wailesaa1c9622019-01-10 16:55:32 -08001560 env_var_val = getenv(env_var_name.c_str());
1561
1562 if (env_var_val != nullptr) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001563 gUsapPoolSocketFD = atoi(env_var_val);
1564 ALOGV("Zygote:usapPoolSocketFD = %d", gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001565 } else {
Chris Wailes7e797b62019-02-22 18:29:22 -08001566 ALOGE("Unable to fetch USAP pool socket file descriptor");
Chris Wailesaa1c9622019-01-10 16:55:32 -08001567 }
Chris Wailes6d482d542019-04-03 13:00:52 -07001568
1569 /*
1570 * Security Initialization
1571 */
1572
1573 // security_getenforce is not allowed on app process. Initialize and cache
1574 // the value before zygote forks.
1575 gIsSecurityEnforced = security_getenforce();
1576
1577 selinux_android_seapp_context_init();
1578
1579 /*
1580 * Storage Initialization
1581 */
1582
1583 UnmountStorageOnInit(env);
1584
1585 /*
1586 * Performance Initialization
1587 */
1588
1589 if (!SetTaskProfiles(0, {})) {
1590 ZygoteFailure(env, "zygote", nullptr, "Zygote SetTaskProfiles failed");
1591 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001592}
1593
1594/**
1595 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001596 * @return A managed array of raw file descriptors for the read ends of the USAP reporting
Chris Wailesaa1c9622019-01-10 16:55:32 -08001597 * pipes.
1598 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001599static jintArray com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv* env, jclass) {
1600 std::vector<int> usap_fds = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001601
Chris Wailes7e797b62019-02-22 18:29:22 -08001602 jintArray managed_usap_fds = env->NewIntArray(usap_fds.size());
1603 env->SetIntArrayRegion(managed_usap_fds, 0, usap_fds.size(), usap_fds.data());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001604
Chris Wailes7e797b62019-02-22 18:29:22 -08001605 return managed_usap_fds;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001606}
1607
1608/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001609 * A JNI wrapper around RemoveUsapTableEntry.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001610 *
1611 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001612 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001613 * @return True if an entry was invalidated; false otherwise.
1614 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001615static jboolean com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(JNIEnv* env, jclass,
1616 jint usap_pid) {
1617 return RemoveUsapTableEntry(usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001618}
1619
1620/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001621 * Creates the USAP pool event FD if it doesn't exist and returns it. This is used by the
1622 * ZygoteServer poll loop to know when to re-fill the USAP pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001623 *
1624 * @param env Managed runtime environment
1625 * @return A raw event file descriptor used to communicate (from the signal handler) when the
Chris Wailes7e797b62019-02-22 18:29:22 -08001626 * Zygote receives a SIGCHLD for a USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001627 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001628static jint com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv* env, jclass) {
1629 if (gUsapPoolEventFD == -1) {
1630 if ((gUsapPoolEventFD = eventfd(0, 0)) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001631 ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
1632 }
1633 }
1634
Chris Wailes7e797b62019-02-22 18:29:22 -08001635 return gUsapPoolEventFD;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001636}
1637
1638/**
1639 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001640 * @return The number of USAPs currently in the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001641 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001642static jint com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv* env, jclass) {
1643 return gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001644}
1645
Chris Wailesae937142019-01-24 12:57:33 -08001646/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001647 * Kills all processes currently in the USAP pool and closes their read pipe
1648 * FDs.
Chris Wailesae937142019-01-24 12:57:33 -08001649 *
1650 * @param env Managed runtime environment
Chris Wailesae937142019-01-24 12:57:33 -08001651 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001652static void com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv* env, jclass) {
1653 for (auto& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -08001654 auto entry_storage = entry.GetValues();
1655
1656 if (entry_storage.has_value()) {
Chris Wailesf68c4e22019-06-05 16:07:50 -07001657 kill(entry_storage.value().pid, SIGTERM);
1658
1659 // Clean up the USAP table entry here. This avoids a potential race
1660 // where a newly created USAP might not be able to find a valid table
1661 // entry if signal handler (which would normally do the cleanup) doesn't
1662 // run between now and when the new process is created.
1663
Chris Wailesdb132a32019-02-20 10:49:27 -08001664 close(entry_storage.value().read_pipe_fd);
1665
1666 // Avoid a second atomic load by invalidating instead of clearing.
1667 entry.Invalidate();
Chris Wailes7e797b62019-02-22 18:29:22 -08001668 --gUsapPoolCount;
Chris Wailesae937142019-01-24 12:57:33 -08001669 }
1670 }
1671}
1672
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07001673static int disable_execute_only(struct dl_phdr_info *info, size_t size, void *data) {
1674 // Search for any execute-only segments and mark them read+execute.
1675 for (int i = 0; i < info->dlpi_phnum; i++) {
1676 if ((info->dlpi_phdr[i].p_type == PT_LOAD) && (info->dlpi_phdr[i].p_flags == PF_X)) {
1677 mprotect(reinterpret_cast<void*>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr),
1678 info->dlpi_phdr[i].p_memsz, PROT_READ | PROT_EXEC);
1679 }
1680 }
1681 // Return non-zero to exit dl_iterate_phdr.
1682 return 0;
1683}
1684
1685/**
1686 * @param env Managed runtime environment
1687 * @return True if disable was successful.
1688 */
1689static jboolean com_android_internal_os_Zygote_nativeDisableExecuteOnly(JNIEnv* env, jclass) {
1690 return dl_iterate_phdr(disable_execute_only, nullptr) == 0;
1691}
1692
Chris Wailesf68c4e22019-06-05 16:07:50 -07001693static void com_android_internal_os_Zygote_nativeBlockSigTerm(JNIEnv* env, jclass) {
1694 auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
1695 BlockSignal(SIGTERM, fail_fn);
1696}
1697
1698static void com_android_internal_os_Zygote_nativeUnblockSigTerm(JNIEnv* env, jclass) {
1699 auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
1700 UnblockSignal(SIGTERM, fail_fn);
1701}
1702
Daniel Micay76f6a862015-09-19 17:31:01 -04001703static const JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001704 { "nativeForkAndSpecialize",
Sudheer Shanka64501e52019-04-29 10:46:26 -07001705 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001706 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1707 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001708 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001709 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1710 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
Christopher Ferris76de39e2017-06-20 16:13:40 -07001711 { "nativePreApplicationInit", "()V",
Martijn Coenen86f08a52019-01-03 16:23:01 +01001712 (void *) com_android_internal_os_Zygote_nativePreApplicationInit },
1713 { "nativeInstallSeccompUidGidFilter", "(II)V",
Chris Wailesaa1c9622019-01-10 16:55:32 -08001714 (void *) com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter },
Mathew Inwood51c53b42019-05-24 14:06:10 +01001715 { "nativeForkUsap", "(II[I)I",
Chris Wailes7e797b62019-02-22 18:29:22 -08001716 (void *) com_android_internal_os_Zygote_nativeForkUsap },
1717 { "nativeSpecializeAppProcess",
Sudheer Shanka64501e52019-04-29 10:46:26 -07001718 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V",
Chris Wailes7e797b62019-02-22 18:29:22 -08001719 (void *) com_android_internal_os_Zygote_nativeSpecializeAppProcess },
Chris Wailes6d482d542019-04-03 13:00:52 -07001720 { "nativeInitNativeState", "(Z)V",
1721 (void *) com_android_internal_os_Zygote_nativeInitNativeState },
Chris Wailes7e797b62019-02-22 18:29:22 -08001722 { "nativeGetUsapPipeFDs", "()[I",
1723 (void *) com_android_internal_os_Zygote_nativeGetUsapPipeFDs },
1724 { "nativeRemoveUsapTableEntry", "(I)Z",
1725 (void *) com_android_internal_os_Zygote_nativeRemoveUsapTableEntry },
1726 { "nativeGetUsapPoolEventFD", "()I",
1727 (void *) com_android_internal_os_Zygote_nativeGetUsapPoolEventFD },
1728 { "nativeGetUsapPoolCount", "()I",
1729 (void *) com_android_internal_os_Zygote_nativeGetUsapPoolCount },
1730 { "nativeEmptyUsapPool", "()V",
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07001731 (void *) com_android_internal_os_Zygote_nativeEmptyUsapPool },
1732 { "nativeDisableExecuteOnly", "()Z",
Chris Wailesf68c4e22019-06-05 16:07:50 -07001733 (void *) com_android_internal_os_Zygote_nativeDisableExecuteOnly },
1734 { "nativeBlockSigTerm", "()V",
1735 (void* ) com_android_internal_os_Zygote_nativeBlockSigTerm },
1736 { "nativeUnblockSigTerm", "()V",
1737 (void* ) com_android_internal_os_Zygote_nativeUnblockSigTerm }
Narayan Kamath973b4662014-03-31 13:41:26 +01001738};
1739
1740int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001741 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001742 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1743 "callPostForkSystemServerHooks",
Mathieu Chartier742981e2019-11-21 14:30:03 -08001744 "(I)V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001745 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001746 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001747
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07001748 gZygoteInitClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteInitClassName));
1749 gCreateSystemServerClassLoader = GetStaticMethodIDOrDie(env, gZygoteInitClass,
1750 "createSystemServerClassLoader",
1751 "()V");
1752
1753 RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
1754
1755 return JNI_OK;
Narayan Kamath973b4662014-03-31 13:41:26 +01001756}
1757} // namespace android