blob: 8ff16912e932bee6f4484e1dc70dee47634d3909 [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
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700119static constexpr const char* kZygoteClassName = "com/android/internal/os/Zygote";
Narayan Kamath973b4662014-03-31 13:41:26 +0100120static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +0100121static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +0100122static jmethodID gCallPostForkChildHooks;
123
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700124static constexpr const char* kZygoteInitClassName = "com/android/internal/os/ZygoteInit";
125static jclass gZygoteInitClass;
126static jmethodID gCreateSystemServerClassLoader;
127
Chris Wailes6d482d542019-04-03 13:00:52 -0700128static bool gIsSecurityEnforced = true;
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800129
Chris Wailesaa1c9622019-01-10 16:55:32 -0800130/**
131 * The maximum number of characters (not including a null terminator) that a
132 * process name may contain.
133 */
134static constexpr size_t MAX_NAME_LENGTH = 15;
135
136/**
137 * The prefix string for environmental variables storing socket FDs created by
138 * init.
139 */
140
141static constexpr std::string_view ANDROID_SOCKET_PREFIX("ANDROID_SOCKET_");
142
143/**
144 * The file descriptor for the Zygote socket opened by init.
145 */
146
147static int gZygoteSocketFD = -1;
148
149/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800150 * The file descriptor for the unspecialized app process (USAP) pool socket opened by init.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800151 */
152
Chris Wailes7e797b62019-02-22 18:29:22 -0800153static int gUsapPoolSocketFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800154
155/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800156 * The number of USAPs currently in this Zygote's pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800157 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800158static std::atomic_uint32_t gUsapPoolCount = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800159
160/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800161 * Event file descriptor used to communicate reaped USAPs to the
Chris Wailesaa1c9622019-01-10 16:55:32 -0800162 * ZygoteServer.
163 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800164static int gUsapPoolEventFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800165
166/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800167 * The maximum value that the gUSAPPoolSizeMax variable may take. This value
168 * is a mirror of ZygoteServer.USAP_POOL_SIZE_MAX_LIMIT
Chris Wailesaa1c9622019-01-10 16:55:32 -0800169 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800170static constexpr int USAP_POOL_SIZE_MAX_LIMIT = 100;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800171
172/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800173 * A helper class containing accounting information for USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800174 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800175class UsapTableEntry {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800176 public:
177 struct EntryStorage {
178 int32_t pid;
179 int32_t read_pipe_fd;
180
181 bool operator!=(const EntryStorage& other) {
182 return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
183 }
184 };
185
186 private:
187 static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
188
189 std::atomic<EntryStorage> mStorage;
190 static_assert(decltype(mStorage)::is_always_lock_free);
191
192 public:
Chris Wailes7e797b62019-02-22 18:29:22 -0800193 constexpr UsapTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
Chris Wailesaa1c9622019-01-10 16:55:32 -0800194
195 /**
196 * If the provided PID matches the one stored in this entry, the entry will
197 * be invalidated and the associated file descriptor will be closed. If the
198 * PIDs don't match nothing will happen.
199 *
200 * @param pid The ID of the process who's entry we want to clear.
201 * @return True if the entry was cleared; false otherwise
202 */
203 bool ClearForPID(int32_t pid) {
204 EntryStorage storage = mStorage.load();
205
206 if (storage.pid == pid) {
207 /*
208 * There are three possible outcomes from this compare-and-exchange:
209 * 1) It succeeds, in which case we close the FD
210 * 2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
211 * the entry has already been cleared.
212 * 3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
213 * case the entry has already been cleared and re-used.
214 *
215 * In all three cases the goal of the caller has been met and we can
216 * return true.
217 */
218 if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
219 close(storage.read_pipe_fd);
220 }
221
222 return true;
223 } else {
224 return false;
225 }
226 }
227
Chris Wailesae937142019-01-24 12:57:33 -0800228 void Clear() {
Chris Wailesdb132a32019-02-20 10:49:27 -0800229 EntryStorage storage = mStorage.load();
230
231 if (storage != INVALID_ENTRY_VALUE) {
232 close(storage.read_pipe_fd);
233 mStorage.store(INVALID_ENTRY_VALUE);
234 }
235 }
236
237 void Invalidate() {
Chris Wailesae937142019-01-24 12:57:33 -0800238 mStorage.store(INVALID_ENTRY_VALUE);
239 }
240
Chris Wailesaa1c9622019-01-10 16:55:32 -0800241 /**
242 * @return A copy of the data stored in this entry.
243 */
244 std::optional<EntryStorage> GetValues() {
245 EntryStorage storage = mStorage.load();
246
247 if (storage != INVALID_ENTRY_VALUE) {
248 return storage;
249 } else {
250 return std::nullopt;
251 }
252 }
253
254 /**
255 * Sets the entry to the given values if it is currently invalid.
256 *
257 * @param pid The process ID for the new entry.
Chris Wailes7e797b62019-02-22 18:29:22 -0800258 * @param read_pipe_fd The read end of the USAP control pipe for this
Chris Wailesaa1c9622019-01-10 16:55:32 -0800259 * process.
260 * @return True if the entry was set; false otherwise.
261 */
262 bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
263 EntryStorage new_value_storage;
264
265 new_value_storage.pid = pid;
266 new_value_storage.read_pipe_fd = read_pipe_fd;
267
268 EntryStorage expected = INVALID_ENTRY_VALUE;
269
270 return mStorage.compare_exchange_strong(expected, new_value_storage);
271 }
272};
273
274/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800275 * A table containing information about the USAPs currently in the pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800276 *
277 * Multiple threads may be attempting to modify the table, either from the
278 * signal handler or from the ZygoteServer poll loop. Atomic loads/stores in
Chris Wailes7e797b62019-02-22 18:29:22 -0800279 * the USAPTableEntry class prevent data races during these concurrent
Chris Wailesaa1c9622019-01-10 16:55:32 -0800280 * operations.
281 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800282static std::array<UsapTableEntry, USAP_POOL_SIZE_MAX_LIMIT> gUsapTable;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800283
284/**
285 * The list of open zygote file descriptors.
286 */
287static FileDescriptorTable* gOpenFdTable = nullptr;
288
Narayan Kamath973b4662014-03-31 13:41:26 +0100289// Must match values in com.android.internal.os.Zygote.
290enum MountExternalKind {
291 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700292 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700293 MOUNT_EXTERNAL_READ = 2,
294 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800295 MOUNT_EXTERNAL_LEGACY = 4,
296 MOUNT_EXTERNAL_INSTALLER = 5,
297 MOUNT_EXTERNAL_FULL = 6,
Narayan Kamath973b4662014-03-31 13:41:26 +0100298};
299
Orion Hodson8d005a62018-12-05 12:28:53 +0000300// Must match values in com.android.internal.os.Zygote.
301enum RuntimeFlags : uint32_t {
302 DEBUG_ENABLE_JDWP = 1,
Yabin Cui4d8546d2019-01-29 16:29:20 -0800303 PROFILE_FROM_SHELL = 1 << 15,
Orion Hodson8d005a62018-12-05 12:28:53 +0000304};
305
Chris Wailesaa1c9622019-01-10 16:55:32 -0800306// Forward declaration so we don't have to move the signal handler.
Chris Wailes7e797b62019-02-22 18:29:22 -0800307static bool RemoveUsapTableEntry(pid_t usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800308
Andreas Gampeb053cce2015-11-17 16:38:59 -0800309static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
310 std::ostringstream oss;
311 oss << __FILE__ << ":" << line << ": " << msg;
312 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100313}
314
315// This signal handler is for zygote mode, since the zygote must reap its children
316static void SigChldHandler(int /*signal_number*/) {
317 pid_t pid;
318 int status;
Chris Wailes7e797b62019-02-22 18:29:22 -0800319 int64_t usaps_removed = 0;
Narayan Kamath973b4662014-03-31 13:41:26 +0100320
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700321 // It's necessary to save and restore the errno during this function.
322 // Since errno is stored per thread, changing it here modifies the errno
323 // on the thread on which this signal handler executes. If a signal occurs
324 // between a call and an errno check, it's possible to get the errno set
325 // here.
326 // See b/23572286 for extra information.
327 int saved_errno = errno;
328
Narayan Kamath973b4662014-03-31 13:41:26 +0100329 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800330 // Log process-death status that we care about.
Narayan Kamath973b4662014-03-31 13:41:26 +0100331 if (WIFEXITED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800332 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
333 "Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100334 } else if (WIFSIGNALED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800335 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
336 "Process %d exited due to signal %d (%s)%s", pid,
337 WTERMSIG(status), strsignal(WTERMSIG(status)),
338 WCOREDUMP(status) ? "; core dumped" : "");
Narayan Kamath973b4662014-03-31 13:41:26 +0100339 }
340
341 // If the just-crashed process is the system_server, bring down zygote
342 // so that it is restarted by init and system server will be restarted
343 // from there.
344 if (pid == gSystemServerPid) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800345 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
346 "Exit zygote because system server (pid %d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100347 kill(getpid(), SIGKILL);
348 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800349
Chris Wailes7e797b62019-02-22 18:29:22 -0800350 // Check to see if the PID is in the USAP pool and remove it if it is.
351 if (RemoveUsapTableEntry(pid)) {
352 ++usaps_removed;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800353 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100354 }
355
Narayan Kamath160992d2014-04-14 14:46:07 +0100356 // Note that we shouldn't consider ECHILD an error because
357 // the secondary zygote might have no children left to wait for.
358 if (pid < 0 && errno != ECHILD) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800359 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG,
360 "Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100361 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700362
Chris Wailes7e797b62019-02-22 18:29:22 -0800363 if (usaps_removed > 0) {
Chris Wailesfe3a3482019-03-13 14:38:04 -0700364 if (TEMP_FAILURE_RETRY(write(gUsapPoolEventFD, &usaps_removed, sizeof(usaps_removed))) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800365 // If this write fails something went terribly wrong. We will now kill
366 // the zygote and let the system bring it back up.
wangmingming16d0dd1a2018-11-14 10:43:36 +0800367 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
Chris Wailes7e797b62019-02-22 18:29:22 -0800368 "Zygote failed to write to USAP pool event FD: %s",
wangmingming16d0dd1a2018-11-14 10:43:36 +0800369 strerror(errno));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800370 kill(getpid(), SIGKILL);
371 }
372 }
373
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700374 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100375}
376
yuanhao435e84b2018-01-15 15:37:02 +0800377// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
378// configured very late, because earlier in the runtime we may fork() and
379// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100380// have them be harvested immediately.
381//
yuanhao435e84b2018-01-15 15:37:02 +0800382// Ignore SIGHUP because all processes forked by the zygote are in the same
383// process group as the zygote and we don't want to be notified if we become
384// an orphaned group and have one or more stopped processes. This is not a
385// theoretical concern :
386// - we can become an orphaned group if one of our direct descendants forks
387// and is subsequently killed before its children.
388// - crash_dump routinely STOPs the process it's tracing.
389//
390// See issues b/71965619 and b/25567761 for further details.
391//
Narayan Kamath973b4662014-03-31 13:41:26 +0100392// This ends up being called repeatedly before each fork(), but there's
393// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800394static void SetSignalHandlers() {
395 struct sigaction sig_chld = {};
396 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100397
Chris Wailesaa1c9622019-01-10 16:55:32 -0800398 if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700399 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100400 }
yuanhao435e84b2018-01-15 15:37:02 +0800401
402 struct sigaction sig_hup = {};
403 sig_hup.sa_handler = SIG_IGN;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800404 if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
yuanhao435e84b2018-01-15 15:37:02 +0800405 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
406 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100407}
408
409// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800410static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100411 struct sigaction sa;
412 memset(&sa, 0, sizeof(sa));
413 sa.sa_handler = SIG_DFL;
414
Chris Wailesaa1c9622019-01-10 16:55:32 -0800415 if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700416 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100417 }
418}
419
420// Calls POSIX setgroups() using the int[] object as an argument.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800421// A nullptr argument is tolerated.
422static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) {
423 if (managed_gids == nullptr) {
424 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100425 }
426
Chris Wailesaa1c9622019-01-10 16:55:32 -0800427 ScopedIntArrayRO gids(env, managed_gids);
428 if (gids.get() == nullptr) {
429 fail_fn(CREATE_ERROR("Getting gids int array failed"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100430 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700431
Chris Wailesaa1c9622019-01-10 16:55:32 -0800432 if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
433 fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
434 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100435}
436
437// Sets the resource limits via setrlimit(2) for the values in the
438// two-dimensional array of integers that's passed in. The second dimension
Chris Wailesaa1c9622019-01-10 16:55:32 -0800439// contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
Narayan Kamath973b4662014-03-31 13:41:26 +0100440// treated as an empty array.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800441static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
442 if (managed_rlimits == nullptr) {
443 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100444 }
445
446 rlimit rlim;
447 memset(&rlim, 0, sizeof(rlim));
448
Chris Wailesaa1c9622019-01-10 16:55:32 -0800449 for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
450 ScopedLocalRef<jobject>
451 managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
452 ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
453
454 if (rlimit_handle.size() != 3) {
455 fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100456 }
457
Chris Wailesaa1c9622019-01-10 16:55:32 -0800458 rlim.rlim_cur = rlimit_handle[1];
459 rlim.rlim_max = rlimit_handle[2];
Narayan Kamath973b4662014-03-31 13:41:26 +0100460
Chris Wailesaa1c9622019-01-10 16:55:32 -0800461 if (setrlimit(rlimit_handle[0], &rlim) == -1) {
462 fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
463 rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
Narayan Kamath973b4662014-03-31 13:41:26 +0100464 }
465 }
466}
467
Orion Hodson8d005a62018-12-05 12:28:53 +0000468static void EnableDebugger() {
469 // To let a non-privileged gdbserver attach to this
470 // process, we must set our dumpable flag.
471 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
472 ALOGE("prctl(PR_SET_DUMPABLE) failed");
473 }
474
475 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
476 // is enabled (see kernel/Documentation/security/Yama.txt).
477 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
478 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
479 // case since it's expected behaviour.
480 if (errno != EINVAL) {
481 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
482 }
483 }
484
Orion Hodson2b71ad02018-12-07 16:44:33 +0000485 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
486 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
487 // Set the soft limit on core dump size to 0 without changing the hard limit.
488 rlimit rl;
489 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
490 ALOGE("getrlimit(RLIMIT_CORE) failed");
491 } else {
492 rl.rlim_cur = 0;
493 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
494 ALOGE("setrlimit(RLIMIT_CORE) failed");
495 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000496 }
497 }
498}
499
Christopher Ferris76de39e2017-06-20 16:13:40 -0700500static void PreApplicationInit() {
501 // The child process sets this to indicate it's not the zygote.
Christopher Ferrisc00c1cf2019-04-09 16:42:32 -0700502 android_mallopt(M_SET_ZYGOTE_CHILD, nullptr, 0);
Christopher Ferris76de39e2017-06-20 16:13:40 -0700503
504 // Set the jemalloc decay time to 1.
505 mallopt(M_DECAY_TIME, 1);
506}
507
Martijn Coenen86f08a52019-01-03 16:23:01 +0100508static void SetUpSeccompFilter(uid_t uid, bool is_child_zygote) {
Chris Wailes6d482d542019-04-03 13:00:52 -0700509 if (!gIsSecurityEnforced) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800510 ALOGI("seccomp disabled by setenforce 0");
511 return;
512 }
513
514 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700515 if (uid >= AID_APP_START) {
Martijn Coenen86f08a52019-01-03 16:23:01 +0100516 if (is_child_zygote) {
Martijn Coenen6ef16802019-01-18 16:40:01 +0100517 set_app_zygote_seccomp_filter();
Martijn Coenen86f08a52019-01-03 16:23:01 +0100518 } else {
519 set_app_seccomp_filter();
520 }
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800521 } else {
522 set_system_seccomp_filter();
523 }
524}
525
Chris Wailesaa1c9622019-01-10 16:55:32 -0800526static void EnableKeepCapabilities(fail_fn_t fail_fn) {
527 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
528 fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100529 }
530}
531
Chris Wailesaa1c9622019-01-10 16:55:32 -0800532static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
533 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
534 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100535 if (errno == EINVAL) {
536 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
537 "your kernel is compiled with file capabilities support");
538 } else {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800539 fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100540 }
541 }
542 }
543}
544
Chris Wailesaa1c9622019-01-10 16:55:32 -0800545static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
Josh Gao45dab782017-02-01 14:56:09 -0800546 __user_cap_header_struct capheader;
547 memset(&capheader, 0, sizeof(capheader));
548 capheader.version = _LINUX_CAPABILITY_VERSION_3;
549 capheader.pid = 0;
550
551 __user_cap_data_struct capdata[2];
552 if (capget(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800553 fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800554 }
555
556 capdata[0].inheritable = inheritable;
557 capdata[1].inheritable = inheritable >> 32;
558
559 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800560 fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800561 }
562}
563
Chris Wailesaa1c9622019-01-10 16:55:32 -0800564static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
565 fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100566 __user_cap_header_struct capheader;
567 memset(&capheader, 0, sizeof(capheader));
568 capheader.version = _LINUX_CAPABILITY_VERSION_3;
569 capheader.pid = 0;
570
571 __user_cap_data_struct capdata[2];
572 memset(&capdata, 0, sizeof(capdata));
573 capdata[0].effective = effective;
574 capdata[1].effective = effective >> 32;
575 capdata[0].permitted = permitted;
576 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800577 capdata[0].inheritable = inheritable;
578 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100579
580 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800581 fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
582 "failed: %s", permitted, effective, inheritable, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100583 }
584}
585
Chris Wailesaa1c9622019-01-10 16:55:32 -0800586static void SetSchedulerPolicy(fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100587 errno = -set_sched_policy(0, SP_DEFAULT);
588 if (errno != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800589 fail_fn(CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100590 }
591}
592
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700593static int UnmountTree(const char* path) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600594 ATRACE_CALL();
595
Sudheer Shanka74584a52019-02-22 13:04:41 -0800596 size_t path_len = strlen(path);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700597
Sudheer Shanka74584a52019-02-22 13:04:41 -0800598 FILE* fp = setmntent("/proc/mounts", "r");
599 if (fp == nullptr) {
600 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
601 return -errno;
602 }
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700603
Sudheer Shanka74584a52019-02-22 13:04:41 -0800604 // Some volumes can be stacked on each other, so force unmount in
605 // reverse order to give us the best chance of success.
606 std::list<std::string> to_unmount;
607 mntent* mentry;
608 while ((mentry = getmntent(fp)) != nullptr) {
609 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
610 to_unmount.push_front(std::string(mentry->mnt_dir));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700611 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800612 }
613 endmntent(fp);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700614
Sudheer Shanka74584a52019-02-22 13:04:41 -0800615 for (const auto& path : to_unmount) {
616 if (umount2(path.c_str(), MNT_DETACH)) {
617 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700618 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800619 }
620 return 0;
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700621}
622
Narayan Kamath973b4662014-03-31 13:41:26 +0100623// Create a private mount namespace and bind mount appropriate emulated
624// storage for the given user.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800625static void MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shanka64501e52019-04-29 10:46:26 -0700626 bool force_mount_namespace,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800627 fail_fn_t fail_fn) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800628 // See storage config details at http://source.android.com/tech/storage/
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600629 ATRACE_CALL();
Jeff Sharkey9527b222015-06-24 15:24:48 -0700630
Sudheer Shanka74584a52019-02-22 13:04:41 -0800631 String8 storage_source;
632 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
633 storage_source = "/mnt/runtime/default";
634 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
635 storage_source = "/mnt/runtime/read";
Sudheer Shanka783c90e2019-04-12 13:55:20 -0700636 } else if (mount_mode == MOUNT_EXTERNAL_WRITE
637 || mount_mode == MOUNT_EXTERNAL_LEGACY
638 || mount_mode == MOUNT_EXTERNAL_INSTALLER) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800639 storage_source = "/mnt/runtime/write";
Sudheer Shanka783c90e2019-04-12 13:55:20 -0700640 } else if (mount_mode == MOUNT_EXTERNAL_FULL) {
641 storage_source = "/mnt/runtime/full";
Sudheer Shanka74584a52019-02-22 13:04:41 -0800642 } else if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
643 // Sane default of no storage visible
644 return;
645 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400646
Sudheer Shanka74584a52019-02-22 13:04:41 -0800647 // Create a second private mount namespace for our process
648 if (unshare(CLONE_NEWNS) == -1) {
649 fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
650 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400651
Sudheer Shanka74584a52019-02-22 13:04:41 -0800652 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
653 if (mount_mode == MOUNT_EXTERNAL_NONE) {
654 return;
655 }
Robert Sesek06f39302017-03-20 17:30:05 -0400656
Sudheer Shanka64501e52019-04-29 10:46:26 -0700657 if (TEMP_FAILURE_RETRY(mount(storage_source.string(), "/storage", nullptr,
658 MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
659 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
660 storage_source.string(),
661 strerror(errno)));
662 }
Jeff Sharkey9527b222015-06-24 15:24:48 -0700663
Sudheer Shanka64501e52019-04-29 10:46:26 -0700664 // Mount user-specific symlink helper into place
665 userid_t user_id = multiuser_get_user_id(uid);
666 const String8 user_source(String8::format("/mnt/user/%d", user_id));
667 if (fs_prepare_dir(user_source.string(), 0751, 0, 0) == -1) {
668 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s",
669 user_source.string()));
670 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800671
Sudheer Shanka64501e52019-04-29 10:46:26 -0700672 if (TEMP_FAILURE_RETRY(mount(user_source.string(), "/storage/self",
673 nullptr, MS_BIND, nullptr)) == -1) {
674 fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
675 user_source.string(), strerror(errno)));
Sudheer Shanka74584a52019-02-22 13:04:41 -0800676 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100677}
678
Narayan Kamath973b4662014-03-31 13:41:26 +0100679static bool NeedsNoRandomizeWorkaround() {
680#if !defined(__arm__)
681 return false;
682#else
683 int major;
684 int minor;
685 struct utsname uts;
686 if (uname(&uts) == -1) {
687 return false;
688 }
689
690 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
691 return false;
692 }
693
694 // Kernels before 3.4.* need the workaround.
695 return (major < 3) || ((major == 3) && (minor < 4));
696#endif
697}
Narayan Kamath973b4662014-03-31 13:41:26 +0100698
699// Utility to close down the Zygote socket file descriptors while
700// the child is still running as root with Zygote's privileges. Each
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800701// descriptor (if any) is closed via dup3(), replacing it with a valid
Narayan Kamath973b4662014-03-31 13:41:26 +0100702// (open) descriptor to /dev/null.
703
Chris Wailesaa1c9622019-01-10 16:55:32 -0800704static void DetachDescriptors(JNIEnv* env,
705 const std::vector<int>& fds_to_close,
706 fail_fn_t fail_fn) {
707
708 if (fds_to_close.size() > 0) {
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800709 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800710 if (devnull_fd == -1) {
711 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100712 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800713
714 for (int fd : fds_to_close) {
715 ALOGV("Switching descriptor %d to /dev/null", fd);
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800716 if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
717 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800718 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100719 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100720 }
721}
722
Chris Wailesaa1c9622019-01-10 16:55:32 -0800723void SetThreadName(const std::string& thread_name) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100724 bool hasAt = false;
725 bool hasDot = false;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800726
727 for (const char str_el : thread_name) {
728 if (str_el == '.') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100729 hasDot = true;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800730 } else if (str_el == '@') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100731 hasAt = true;
732 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100733 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800734
735 const char* name_start_ptr = thread_name.c_str();
736 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
737 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
Narayan Kamath973b4662014-03-31 13:41:26 +0100738 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800739
Narayan Kamath973b4662014-03-31 13:41:26 +0100740 // pthread_setname_np fails rather than truncating long strings.
741 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
Chris Wailesaa1c9622019-01-10 16:55:32 -0800742 strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
Narayan Kamath973b4662014-03-31 13:41:26 +0100743 errno = pthread_setname_np(pthread_self(), buf);
744 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700745 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100746 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800747 // Update base::logging default tag.
748 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100749}
750
Chris Wailesaa1c9622019-01-10 16:55:32 -0800751/**
752 * A failure function used to report fatal errors to the managed runtime. This
753 * function is often curried with the process name information and then passed
754 * to called functions.
755 *
756 * @param env Managed runtime environment
757 * @param process_name A native representation of the process name
758 * @param managed_process_name A managed representation of the process name
759 * @param msg The error message to be reported
760 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700761[[noreturn]]
762static void ZygoteFailure(JNIEnv* env,
763 const char* process_name,
764 jstring managed_process_name,
765 const std::string& msg) {
766 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
767 if (managed_process_name != nullptr) {
768 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
769 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
770 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -0700771 }
772 }
773
Chris Wailesaf594fc2018-11-02 11:00:07 -0700774 const std::string& error_msg =
775 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700776
Chris Wailesaf594fc2018-11-02 11:00:07 -0700777 env->FatalError(error_msg.c_str());
778 __builtin_unreachable();
779}
David Sehrde8d0bd2018-06-22 10:45:36 -0700780
Chris Wailesaa1c9622019-01-10 16:55:32 -0800781/**
782 * A helper method for converting managed strings to native strings. A fatal
783 * error is generated if a problem is encountered in extracting a non-null
784 * string.
785 *
786 * @param env Managed runtime environment
787 * @param process_name A native representation of the process name
788 * @param managed_process_name A managed representation of the process name
789 * @param managed_string The managed string to extract
790 *
791 * @return An empty option if the managed string is null. A optional-wrapped
792 * string otherwise.
793 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700794static std::optional<std::string> ExtractJString(JNIEnv* env,
795 const char* process_name,
796 jstring managed_process_name,
797 jstring managed_string) {
798 if (managed_string == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800799 return std::nullopt;
Chris Wailesaf594fc2018-11-02 11:00:07 -0700800 } else {
801 ScopedUtfChars scoped_string_chars(env, managed_string);
802
803 if (scoped_string_chars.c_str() != nullptr) {
804 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700805 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -0700806 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700807 }
808 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700809}
810
Chris Wailesaa1c9622019-01-10 16:55:32 -0800811/**
812 * A helper method for converting managed string arrays to native vectors. A
813 * fatal error is generated if a problem is encountered in extracting a non-null array.
814 *
815 * @param env Managed runtime environment
816 * @param process_name A native representation of the process name
817 * @param managed_process_name A managed representation of the process name
818 * @param managed_array The managed integer array to extract
819 *
820 * @return An empty option if the managed array is null. A optional-wrapped
821 * vector otherwise.
822 */
823static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
824 const char* process_name,
825 jstring managed_process_name,
826 jintArray managed_array) {
827 if (managed_array == nullptr) {
828 return std::nullopt;
829 } else {
830 ScopedIntArrayRO managed_array_handle(env, managed_array);
Narayan Kamath973b4662014-03-31 13:41:26 +0100831
Chris Wailesaa1c9622019-01-10 16:55:32 -0800832 if (managed_array_handle.get() != nullptr) {
833 std::vector<int> native_array;
834 native_array.reserve(managed_array_handle.size());
835
836 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
837 native_array.push_back(managed_array_handle[array_index]);
838 }
839
840 return std::move(native_array);
841
842 } else {
843 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
844 }
845 }
846}
847
848/**
Chris Wailesaa1c9622019-01-10 16:55:32 -0800849 * A utility function for blocking signals.
850 *
851 * @param signum Signal number to block
852 * @param fail_fn Fatal error reporting function
853 *
854 * @see ZygoteFailure
855 */
856static void BlockSignal(int signum, fail_fn_t fail_fn) {
857 sigset_t sigs;
858 sigemptyset(&sigs);
859 sigaddset(&sigs, signum);
860
861 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
862 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
863 }
864}
865
866
867/**
868 * A utility function for unblocking signals.
869 *
870 * @param signum Signal number to unblock
871 * @param fail_fn Fatal error reporting function
872 *
873 * @see ZygoteFailure
874 */
875static void UnblockSignal(int signum, fail_fn_t fail_fn) {
876 sigset_t sigs;
877 sigemptyset(&sigs);
878 sigaddset(&sigs, signum);
879
880 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
881 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
882 }
883}
884
Chris Wailes7e797b62019-02-22 18:29:22 -0800885static void ClearUsapTable() {
886 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -0800887 entry.Clear();
888 }
889
Chris Wailes7e797b62019-02-22 18:29:22 -0800890 gUsapPoolCount = 0;
Chris Wailesae937142019-01-24 12:57:33 -0800891}
892
Chris Wailesaa1c9622019-01-10 16:55:32 -0800893// Utility routine to fork a process from the zygote.
894static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
895 const std::vector<int>& fds_to_close,
896 const std::vector<int>& fds_to_ignore) {
897 SetSignalHandlers();
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000898
Chris Wailesaf594fc2018-11-02 11:00:07 -0700899 // Curry a failure function.
900 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
901 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -0700902
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000903 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
904 // log, which would result in the logging FDs we close being reopened.
905 // This would cause failures because the FDs are not whitelisted.
906 //
907 // Note that the zygote process is single threaded at this point.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800908 BlockSignal(SIGCHLD, fail_fn);
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000909
Narayan Kamath3764a262016-08-30 15:36:19 +0100910 // Close any logging related FDs before we start evaluating the list of
911 // file descriptors.
912 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -0700913 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +0100914
Chris Wailesaf594fc2018-11-02 11:00:07 -0700915 // If this is the first fork for this zygote, create the open FD table. If
916 // it isn't, we just need to check whether the list of open files has changed
917 // (and it shouldn't in the normal case).
Chris Wailesaf594fc2018-11-02 11:00:07 -0700918 if (gOpenFdTable == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800919 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
920 } else {
921 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100922 }
923
Josh Gaod7951102018-06-26 16:05:12 -0700924 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
925
Narayan Kamath973b4662014-03-31 13:41:26 +0100926 pid_t pid = fork();
927
928 if (pid == 0) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700929 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700930 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700931
Narayan Kamath973b4662014-03-31 13:41:26 +0100932 // Clean up any descriptors which must be closed immediately
Chris Wailesaa1c9622019-01-10 16:55:32 -0800933 DetachDescriptors(env, fds_to_close, fail_fn);
Narayan Kamath973b4662014-03-31 13:41:26 +0100934
Chris Wailes7e797b62019-02-22 18:29:22 -0800935 // Invalidate the entries in the USAP table.
936 ClearUsapTable();
Chris Wailesae937142019-01-24 12:57:33 -0800937
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100938 // Re-open all remaining open file descriptors so that they aren't shared
939 // with the zygote across a fork.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800940 gOpenFdTable->ReopenOrDetach(fail_fn);
Josh Gaod7951102018-06-26 16:05:12 -0700941
942 // Turn fdsan back on.
943 android_fdsan_set_error_level(fdsan_error_level);
Martin Stjernholma9bd8c32019-02-23 02:35:07 +0000944 } else {
945 ALOGD("Forked child process %d", pid);
David Sehrde8d0bd2018-06-22 10:45:36 -0700946 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100947
David Sehrde8d0bd2018-06-22 10:45:36 -0700948 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800949 UnblockSignal(SIGCHLD, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700950
Narayan Kamath973b4662014-03-31 13:41:26 +0100951 return pid;
952}
Luis Hector Chavez72042c92017-07-12 10:03:30 -0700953
Chris Wailesaf594fc2018-11-02 11:00:07 -0700954// Utility routine to specialize a zygote child process.
955static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
956 jint runtime_flags, jobjectArray rlimits,
957 jlong permitted_capabilities, jlong effective_capabilities,
958 jint mount_external, jstring managed_se_info,
959 jstring managed_nice_name, bool is_system_server,
960 bool is_child_zygote, jstring managed_instruction_set,
Sudheer Shanka64501e52019-04-29 10:46:26 -0700961 jstring managed_app_data_dir) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800962 const char* process_name = is_system_server ? "system_server" : "zygote";
963 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
964 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700965
966 auto se_info = extract_fn(managed_se_info);
967 auto nice_name = extract_fn(managed_nice_name);
968 auto instruction_set = extract_fn(managed_instruction_set);
969 auto app_data_dir = extract_fn(managed_app_data_dir);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700970
Chris Wailesaf594fc2018-11-02 11:00:07 -0700971 // Keep capabilities across UID change, unless we're staying root.
972 if (uid != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800973 EnableKeepCapabilities(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700974 }
975
Chris Wailesaa1c9622019-01-10 16:55:32 -0800976 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700977
Chris Wailesaa1c9622019-01-10 16:55:32 -0800978 DropCapabilitiesBoundingSet(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700979
980 bool use_native_bridge = !is_system_server &&
981 instruction_set.has_value() &&
982 android::NativeBridgeAvailable() &&
983 android::NeedsNativeBridge(instruction_set.value().c_str());
984
985 if (use_native_bridge && !app_data_dir.has_value()) {
986 // The app_data_dir variable should never be empty if we need to use a
987 // native bridge. In general, app_data_dir will never be empty for normal
988 // applications. It can only happen in special cases (for isolated
989 // processes which are not associated with any app). These are launched by
990 // the framework and should not be emulated anyway.
991 use_native_bridge = false;
992 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
993 }
994
Sudheer Shanka64501e52019-04-29 10:46:26 -0700995 MountEmulatedStorage(uid, mount_external, use_native_bridge, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -0700996
997 // If this zygote isn't root, it won't be able to create a process group,
998 // since the directory is owned by root.
999 if (!is_system_server && getuid() == 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001000 const int rc = createProcessGroup(uid, getpid());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001001 if (rc == -EROFS) {
1002 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
1003 } else if (rc != 0) {
1004 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
1005 }
1006 }
1007
Chris Wailesaa1c9622019-01-10 16:55:32 -08001008 SetGids(env, gids, fail_fn);
1009 SetRLimits(env, rlimits, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001010
1011 if (use_native_bridge) {
1012 // Due to the logic behind use_native_bridge we know that both app_data_dir
1013 // and instruction_set contain values.
1014 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
1015 instruction_set.value().c_str());
1016 }
1017
1018 if (setresgid(gid, gid, gid) == -1) {
1019 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
1020 }
1021
1022 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
1023 // before changing uid from 0, which clears capabilities. The other
1024 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
1025 // breaks SELinux domain transition (see b/71859146). As the result,
1026 // privileged syscalls used below still need to be accessible in app process.
Martijn Coenen86f08a52019-01-03 16:23:01 +01001027 SetUpSeccompFilter(uid, is_child_zygote);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001028
1029 if (setresuid(uid, uid, uid) == -1) {
1030 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1031 }
1032
1033 // The "dumpable" flag of a process, which controls core dump generation, is
1034 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1035 // user or group ID changes. See proc(5) for possible values. In most cases,
1036 // the value is 0, so core dumps are disabled for zygote children. However,
1037 // when running in a Chrome OS container, the value is already set to 2,
1038 // which allows the external crash reporter to collect all core dumps. Since
1039 // only system crashes are interested, core dump is disabled for app
1040 // processes. This also ensures compliance with CTS.
1041 int dumpable = prctl(PR_GET_DUMPABLE);
1042 if (dumpable == -1) {
1043 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1044 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1045 }
1046
1047 if (dumpable == 2 && uid >= AID_APP) {
1048 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1049 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1050 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1051 }
1052 }
1053
Orion Hodson8d005a62018-12-05 12:28:53 +00001054 // Set process properties to enable debugging if required.
1055 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1056 EnableDebugger();
1057 }
Yabin Cui4d8546d2019-01-29 16:29:20 -08001058 if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
1059 // simpleperf needs the process to be dumpable to profile it.
1060 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
1061 ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
1062 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
1063 }
1064 }
Orion Hodson8d005a62018-12-05 12:28:53 +00001065
Chris Wailesaf594fc2018-11-02 11:00:07 -07001066 if (NeedsNoRandomizeWorkaround()) {
1067 // Work around ARM kernel ASLR lossage (http://b/5817320).
1068 int old_personality = personality(0xffffffff);
1069 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1070 if (new_personality == -1) {
1071 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1072 }
1073 }
1074
Chris Wailesaa1c9622019-01-10 16:55:32 -08001075 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001076
Chris Wailesaa1c9622019-01-10 16:55:32 -08001077 SetSchedulerPolicy(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001078
Mathieu Chartier0bccbf72019-01-30 15:56:17 -08001079 __android_log_close();
1080 stats_log_close();
1081
Chris Wailesaf594fc2018-11-02 11:00:07 -07001082 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1083 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1084
1085 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1086 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1087 uid, is_system_server, se_info_ptr, nice_name_ptr));
1088 }
1089
1090 // Make it easier to debug audit logs by setting the main thread's name to the
1091 // nice name rather than "app_process".
1092 if (nice_name.has_value()) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001093 SetThreadName(nice_name.value());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001094 } else if (is_system_server) {
1095 SetThreadName("system_server");
1096 }
1097
1098 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1099 UnsetChldSignalHandler();
1100
1101 if (is_system_server) {
1102 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1103 if (env->ExceptionCheck()) {
1104 fail_fn("Error calling post fork system server hooks.");
1105 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001106
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07001107 // Prefetch the classloader for the system server. This is done early to
1108 // allow a tie-down of the proper system server selinux domain.
1109 env->CallStaticVoidMethod(gZygoteInitClass, gCreateSystemServerClassLoader);
1110 if (env->ExceptionCheck()) {
1111 // Be robust here. The Java code will attempt to create the classloader
1112 // at a later point (but may not have rights to use AoT artifacts).
1113 env->ExceptionClear();
1114 }
1115
Chris Wailesaf594fc2018-11-02 11:00:07 -07001116 // TODO(oth): Remove hardcoded label here (b/117874058).
1117 static const char* kSystemServerLabel = "u:r:system_server:s0";
1118 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1119 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1120 }
1121 }
1122
1123 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1124 is_system_server, is_child_zygote, managed_instruction_set);
1125
1126 if (env->ExceptionCheck()) {
1127 fail_fn("Error calling post fork hooks.");
1128 }
1129}
1130
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001131static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1132 __user_cap_header_struct capheader;
1133 memset(&capheader, 0, sizeof(capheader));
1134 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1135 capheader.pid = 0;
1136
1137 __user_cap_data_struct capdata[2];
1138 if (capget(&capheader, &capdata[0]) == -1) {
1139 ALOGE("capget failed: %s", strerror(errno));
1140 RuntimeAbort(env, __LINE__, "capget failed");
1141 }
1142
Chris Wailesaf594fc2018-11-02 11:00:07 -07001143 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1144}
1145
1146static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1147 bool is_child_zygote) {
1148 jlong capabilities = 0;
1149
1150 /*
1151 * Grant the following capabilities to the Bluetooth user:
1152 * - CAP_WAKE_ALARM
1153 * - CAP_NET_RAW
1154 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1155 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1156 */
1157
1158 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1159 capabilities |= (1LL << CAP_WAKE_ALARM);
1160 capabilities |= (1LL << CAP_NET_RAW);
1161 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1162 capabilities |= (1LL << CAP_SYS_NICE);
1163 }
1164
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001165 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1166 capabilities |= (1LL << CAP_NET_ADMIN);
1167 capabilities |= (1LL << CAP_NET_BROADCAST);
1168 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1169 capabilities |= (1LL << CAP_NET_RAW);
1170 }
1171
Chris Wailesaf594fc2018-11-02 11:00:07 -07001172 /*
1173 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1174 */
1175
1176 bool gid_wakelock_found = false;
1177 if (gid == AID_WAKELOCK) {
1178 gid_wakelock_found = true;
1179 } else if (gids != nullptr) {
1180 jsize gids_num = env->GetArrayLength(gids);
1181 ScopedIntArrayRO native_gid_proxy(env, gids);
1182
1183 if (native_gid_proxy.get() == nullptr) {
1184 RuntimeAbort(env, __LINE__, "Bad gids array");
1185 }
1186
Chris Wailes31c52c92019-02-14 11:20:02 -08001187 for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
1188 if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001189 gid_wakelock_found = true;
1190 break;
1191 }
1192 }
1193 }
1194
1195 if (gid_wakelock_found) {
1196 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1197 }
1198
1199 /*
1200 * Grant child Zygote processes the following capabilities:
1201 * - CAP_SETUID (change UID of child processes)
1202 * - CAP_SETGID (change GID of child processes)
1203 * - CAP_SETPCAP (change capabilities of child processes)
1204 */
1205
1206 if (is_child_zygote) {
1207 capabilities |= (1LL << CAP_SETUID);
1208 capabilities |= (1LL << CAP_SETGID);
1209 capabilities |= (1LL << CAP_SETPCAP);
1210 }
1211
1212 /*
1213 * Containers run without some capabilities, so drop any caps that are not
1214 * available.
1215 */
1216
1217 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001218}
Chris Wailesaa1c9622019-01-10 16:55:32 -08001219
1220/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001221 * Adds the given information about a newly created unspecialized app
1222 * processes to the Zygote's USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001223 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001224 * @param usap_pid Process ID of the newly created USAP
1225 * @param read_pipe_fd File descriptor for the read end of the USAP
1226 * reporting pipe. Used in the ZygoteServer poll loop to track USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001227 * specialization.
1228 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001229static void AddUsapTableEntry(pid_t usap_pid, int read_pipe_fd) {
1230 static int sUsapTableInsertIndex = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001231
Chris Wailes7e797b62019-02-22 18:29:22 -08001232 int search_index = sUsapTableInsertIndex;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001233
1234 do {
Chris Wailes7e797b62019-02-22 18:29:22 -08001235 if (gUsapTable[search_index].SetIfInvalid(usap_pid, read_pipe_fd)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001236 // Start our next search right after where we finished this one.
Chris Wailes7e797b62019-02-22 18:29:22 -08001237 sUsapTableInsertIndex = (search_index + 1) % gUsapTable.size();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001238
1239 return;
1240 }
1241
Chris Wailes7e797b62019-02-22 18:29:22 -08001242 search_index = (search_index + 1) % gUsapTable.size();
1243 } while (search_index != sUsapTableInsertIndex);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001244
1245 // Much like money in the banana stand, there should always be an entry
Chris Wailes7e797b62019-02-22 18:29:22 -08001246 // in the USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001247 __builtin_unreachable();
1248}
1249
1250/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001251 * Invalidates the entry in the USAPTable corresponding to the provided
1252 * process ID if it is present. If an entry was removed the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001253 * count is decremented.
1254 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001255 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001256 * @return True if an entry was invalidated; false otherwise
1257 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001258static bool RemoveUsapTableEntry(pid_t usap_pid) {
1259 for (UsapTableEntry& entry : gUsapTable) {
1260 if (entry.ClearForPID(usap_pid)) {
1261 --gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001262 return true;
1263 }
1264 }
1265
1266 return false;
1267}
1268
1269/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001270 * @return A vector of the read pipe FDs for each of the active USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001271 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001272std::vector<int> MakeUsapPipeReadFDVector() {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001273 std::vector<int> fd_vec;
Chris Wailes7e797b62019-02-22 18:29:22 -08001274 fd_vec.reserve(gUsapTable.size());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001275
Chris Wailes7e797b62019-02-22 18:29:22 -08001276 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001277 auto entry_values = entry.GetValues();
1278
1279 if (entry_values.has_value()) {
1280 fd_vec.push_back(entry_values.value().read_pipe_fd);
1281 }
1282 }
1283
1284 return fd_vec;
1285}
1286
Chris Wailes6d482d542019-04-03 13:00:52 -07001287static void UnmountStorageOnInit(JNIEnv* env) {
1288 // Zygote process unmount root storage space initially before every child processes are forked.
1289 // Every forked child processes (include SystemServer) only mount their own root storage space
1290 // and no need unmount storage operation in MountEmulatedStorage method.
1291 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1292
1293 // See storage config details at http://source.android.com/tech/storage/
1294 // Create private mount namespace shared by all children
1295 if (unshare(CLONE_NEWNS) == -1) {
1296 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1297 return;
1298 }
1299
1300 // Mark rootfs as being a slave so that changes from default
1301 // namespace only flow into our children.
1302 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1303 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1304 return;
1305 }
1306
1307 // Create a staging tmpfs that is shared by our children; they will
1308 // bind mount storage into their respective private namespaces, which
1309 // are isolated from each other.
1310 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1311 if (target_base != nullptr) {
1312#define STRINGIFY_UID(x) __STRING(x)
1313 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1314 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1315 ALOGE("Failed to mount tmpfs to %s", target_base);
1316 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1317 return;
1318 }
1319#undef STRINGIFY_UID
1320 }
1321
1322 UnmountTree("/storage");
1323}
1324
Narayan Kamath973b4662014-03-31 13:41:26 +01001325} // anonymous namespace
1326
1327namespace android {
1328
Christopher Ferris76de39e2017-06-20 16:13:40 -07001329static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1330 PreApplicationInit();
1331}
1332
Narayan Kamath973b4662014-03-31 13:41:26 +01001333static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1334 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001335 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001336 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001337 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001338 jstring instruction_set, jstring app_data_dir) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001339 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001340
Chris Wailesaa1c9622019-01-10 16:55:32 -08001341 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1342 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1343 }
1344
1345 std::vector<int> fds_to_close =
1346 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1347 std::vector<int> fds_to_ignore =
1348 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1349 .value_or(std::vector<int>());
1350
Chris Wailes7e797b62019-02-22 18:29:22 -08001351 std::vector<int> usap_pipes = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001352
Chris Wailes7e797b62019-02-22 18:29:22 -08001353 fds_to_close.insert(fds_to_close.end(), usap_pipes.begin(), usap_pipes.end());
1354 fds_to_ignore.insert(fds_to_ignore.end(), usap_pipes.begin(), usap_pipes.end());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001355
Chris Wailes7e797b62019-02-22 18:29:22 -08001356 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001357
Chris Wailes7e797b62019-02-22 18:29:22 -08001358 if (gUsapPoolEventFD != -1) {
1359 fds_to_close.push_back(gUsapPoolEventFD);
1360 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001361 }
1362
Chris Wailesaf594fc2018-11-02 11:00:07 -07001363 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001364
David Sehrde8d0bd2018-06-22 10:45:36 -07001365 if (pid == 0) {
1366 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1367 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001368 mount_external, se_info, nice_name, false,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001369 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
David Sehrde8d0bd2018-06-22 10:45:36 -07001370 }
1371 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001372}
1373
1374static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1375 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001376 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1377 jlong effective_capabilities) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001378 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001379 fds_to_ignore(fds_to_close);
1380
Chris Wailes7e797b62019-02-22 18:29:22 -08001381 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001382
Chris Wailes7e797b62019-02-22 18:29:22 -08001383 if (gUsapPoolEventFD != -1) {
1384 fds_to_close.push_back(gUsapPoolEventFD);
1385 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001386 }
1387
Chris Wailesaf594fc2018-11-02 11:00:07 -07001388 pid_t pid = ForkCommon(env, true,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001389 fds_to_close,
1390 fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001391 if (pid == 0) {
1392 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001393 permitted_capabilities, effective_capabilities,
1394 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001395 false, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001396 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001397 // The zygote process checks whether the child process has died or not.
1398 ALOGI("System server process %d has been created", pid);
1399 gSystemServerPid = pid;
1400 // There is a slight window that the system server process has crashed
1401 // but it went unnoticed because we haven't published its pid yet. So
1402 // we recheck here just to make sure that all is well.
1403 int status;
1404 if (waitpid(pid, &status, WNOHANG) == pid) {
1405 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001406 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001407 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001408
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001409 if (UsePerAppMemcg()) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001410 // Assign system_server to the correct memory cgroup.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001411 // Not all devices mount memcg so check if it is mounted first
Minchan Kim5fa8af22018-06-27 11:32:40 +09001412 // to avoid unnecessarily printing errors and denials in the logs.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001413 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
1414 ALOGE("couldn't add process %d into system memcg group", pid);
Minchan Kim5fa8af22018-06-27 11:32:40 +09001415 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001416 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001417 }
1418 return pid;
1419}
1420
Chris Wailesaa1c9622019-01-10 16:55:32 -08001421/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001422 * A JNI function that forks an unspecialized app process from the Zygote while
1423 * ensuring proper file descriptor hygiene.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001424 *
1425 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001426 * @param read_pipe_fd The read FD for the USAP reporting pipe. Manually closed by blastlas
Chris Wailesaa1c9622019-01-10 16:55:32 -08001427 * in managed code.
Chris Wailes7e797b62019-02-22 18:29:22 -08001428 * @param write_pipe_fd The write FD for the USAP reporting pipe. Manually closed by the
Chris Wailesaa1c9622019-01-10 16:55:32 -08001429 * zygote in managed code.
1430 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
Chris Wailes7e797b62019-02-22 18:29:22 -08001431 * the FD hygiene code and automatically "closed" in the new USAP.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001432 * @return
1433 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001434static jint com_android_internal_os_Zygote_nativeForkUsap(JNIEnv* env,
1435 jclass,
1436 jint read_pipe_fd,
1437 jint write_pipe_fd,
1438 jintArray managed_session_socket_fds) {
1439 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001440 fds_to_ignore(fds_to_close);
1441
1442 std::vector<int> session_socket_fds =
Chris Wailes7e797b62019-02-22 18:29:22 -08001443 ExtractJIntArray(env, "USAP", nullptr, managed_session_socket_fds)
Chris Wailesaa1c9622019-01-10 16:55:32 -08001444 .value_or(std::vector<int>());
1445
Chris Wailes7e797b62019-02-22 18:29:22 -08001446 // The USAP Pool Event FD is created during the initialization of the
1447 // USAP pool and should always be valid here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001448
1449 fds_to_close.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08001450 fds_to_close.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001451 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
1452
1453 fds_to_ignore.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08001454 fds_to_ignore.push_back(gUsapPoolSocketFD);
1455 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001456 fds_to_ignore.push_back(read_pipe_fd);
1457 fds_to_ignore.push_back(write_pipe_fd);
1458 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
1459
Chris Wailes7e797b62019-02-22 18:29:22 -08001460 pid_t usap_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001461
Chris Wailes7e797b62019-02-22 18:29:22 -08001462 if (usap_pid != 0) {
1463 ++gUsapPoolCount;
1464 AddUsapTableEntry(usap_pid, read_pipe_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001465 }
1466
Chris Wailes7e797b62019-02-22 18:29:22 -08001467 return usap_pid;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001468}
1469
Robert Sesek54e387d2016-12-02 17:27:50 -05001470static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1471 JNIEnv* env, jclass, jstring path) {
1472 ScopedUtfChars path_native(env, path);
1473 const char* path_cstr = path_native.c_str();
1474 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001475 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001476 }
1477 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1478}
1479
Martijn Coenen86f08a52019-01-03 16:23:01 +01001480static void com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(
1481 JNIEnv* env, jclass, jint uidGidMin, jint uidGidMax) {
Chris Wailes6d482d542019-04-03 13:00:52 -07001482 if (!gIsSecurityEnforced) {
Martijn Coenen86f08a52019-01-03 16:23:01 +01001483 ALOGI("seccomp disabled by setenforce 0");
1484 return;
1485 }
1486
Martijn Coenen86f08a52019-01-03 16:23:01 +01001487 bool installed = install_setuidgid_seccomp_filter(uidGidMin, uidGidMax);
1488 if (!installed) {
1489 RuntimeAbort(env, __LINE__, "Could not install setuid/setgid seccomp filter.");
1490 }
Martijn Coenen86f08a52019-01-03 16:23:01 +01001491}
1492
Chris Wailesaa1c9622019-01-10 16:55:32 -08001493/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001494 * Called from an unspecialized app process to specialize the process for a
1495 * given application.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001496 *
1497 * @param env Managed runtime environment
1498 * @param uid User ID of the new application
1499 * @param gid Group ID of the new application
1500 * @param gids Extra groups that the process belongs to
1501 * @param runtime_flags Flags for changing the behavior of the managed runtime
1502 * @param rlimits Resource limits
1503 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
1504 * @param se_info SELinux policy information
1505 * @param nice_name New name for this process
1506 * @param is_child_zygote If the process is to become a WebViewZygote
1507 * @param instruction_set The instruction set expected/requested by the new application
1508 * @param app_data_dir Path to the application's data directory
1509 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001510static void com_android_internal_os_Zygote_nativeSpecializeAppProcess(
Chris Wailesaa1c9622019-01-10 16:55:32 -08001511 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
1512 jint runtime_flags, jobjectArray rlimits,
1513 jint mount_external, jstring se_info, jstring nice_name,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001514 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001515 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
1516
1517 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1518 capabilities, capabilities,
1519 mount_external, se_info, nice_name, false,
Sudheer Shanka64501e52019-04-29 10:46:26 -07001520 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001521}
1522
1523/**
1524 * A helper method for fetching socket file descriptors that were opened by init from the
1525 * environment.
1526 *
1527 * @param env Managed runtime environment
1528 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
1529 * of the environment variable storing the file descriptors.
1530 */
Chris Wailes6d482d542019-04-03 13:00:52 -07001531static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv* env, jclass,
1532 jboolean is_primary) {
1533 /*
1534 * Obtain file descriptors created by init from the environment.
1535 */
1536
Chris Wailesaa1c9622019-01-10 16:55:32 -08001537 std::string android_socket_prefix(ANDROID_SOCKET_PREFIX);
1538 std::string env_var_name = android_socket_prefix + (is_primary ? "zygote" : "zygote_secondary");
1539 char* env_var_val = getenv(env_var_name.c_str());
1540
1541 if (env_var_val != nullptr) {
1542 gZygoteSocketFD = atoi(env_var_val);
1543 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
1544 } else {
1545 ALOGE("Unable to fetch Zygote socket file descriptor");
1546 }
1547
Chris Wailes7e797b62019-02-22 18:29:22 -08001548 env_var_name = android_socket_prefix + (is_primary ? "usap_pool_primary" : "usap_pool_secondary");
Chris Wailesaa1c9622019-01-10 16:55:32 -08001549 env_var_val = getenv(env_var_name.c_str());
1550
1551 if (env_var_val != nullptr) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001552 gUsapPoolSocketFD = atoi(env_var_val);
1553 ALOGV("Zygote:usapPoolSocketFD = %d", gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001554 } else {
Chris Wailes7e797b62019-02-22 18:29:22 -08001555 ALOGE("Unable to fetch USAP pool socket file descriptor");
Chris Wailesaa1c9622019-01-10 16:55:32 -08001556 }
Chris Wailes6d482d542019-04-03 13:00:52 -07001557
1558 /*
1559 * Security Initialization
1560 */
1561
1562 // security_getenforce is not allowed on app process. Initialize and cache
1563 // the value before zygote forks.
1564 gIsSecurityEnforced = security_getenforce();
1565
1566 selinux_android_seapp_context_init();
1567
1568 /*
1569 * Storage Initialization
1570 */
1571
1572 UnmountStorageOnInit(env);
1573
1574 /*
1575 * Performance Initialization
1576 */
1577
1578 if (!SetTaskProfiles(0, {})) {
1579 ZygoteFailure(env, "zygote", nullptr, "Zygote SetTaskProfiles failed");
1580 }
Tim Murraycde0ac72019-04-04 09:19:03 -07001581
1582 /*
1583 * ashmem initialization to avoid dlopen overhead
1584 */
1585 ashmem_init();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001586}
1587
1588/**
1589 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001590 * @return A managed array of raw file descriptors for the read ends of the USAP reporting
Chris Wailesaa1c9622019-01-10 16:55:32 -08001591 * pipes.
1592 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001593static jintArray com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv* env, jclass) {
1594 std::vector<int> usap_fds = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001595
Chris Wailes7e797b62019-02-22 18:29:22 -08001596 jintArray managed_usap_fds = env->NewIntArray(usap_fds.size());
1597 env->SetIntArrayRegion(managed_usap_fds, 0, usap_fds.size(), usap_fds.data());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001598
Chris Wailes7e797b62019-02-22 18:29:22 -08001599 return managed_usap_fds;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001600}
1601
1602/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001603 * A JNI wrapper around RemoveUsapTableEntry.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001604 *
1605 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001606 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001607 * @return True if an entry was invalidated; false otherwise.
1608 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001609static jboolean com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(JNIEnv* env, jclass,
1610 jint usap_pid) {
1611 return RemoveUsapTableEntry(usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001612}
1613
1614/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001615 * Creates the USAP pool event FD if it doesn't exist and returns it. This is used by the
1616 * ZygoteServer poll loop to know when to re-fill the USAP pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001617 *
1618 * @param env Managed runtime environment
1619 * @return A raw event file descriptor used to communicate (from the signal handler) when the
Chris Wailes7e797b62019-02-22 18:29:22 -08001620 * Zygote receives a SIGCHLD for a USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001621 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001622static jint com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv* env, jclass) {
1623 if (gUsapPoolEventFD == -1) {
1624 if ((gUsapPoolEventFD = eventfd(0, 0)) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001625 ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
1626 }
1627 }
1628
Chris Wailes7e797b62019-02-22 18:29:22 -08001629 return gUsapPoolEventFD;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001630}
1631
1632/**
1633 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001634 * @return The number of USAPs currently in the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001635 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001636static jint com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv* env, jclass) {
1637 return gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001638}
1639
Chris Wailesae937142019-01-24 12:57:33 -08001640/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001641 * Kills all processes currently in the USAP pool and closes their read pipe
1642 * FDs.
Chris Wailesae937142019-01-24 12:57:33 -08001643 *
1644 * @param env Managed runtime environment
Chris Wailesae937142019-01-24 12:57:33 -08001645 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001646static void com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv* env, jclass) {
1647 for (auto& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -08001648 auto entry_storage = entry.GetValues();
1649
1650 if (entry_storage.has_value()) {
1651 kill(entry_storage.value().pid, SIGKILL);
Chris Wailesdb132a32019-02-20 10:49:27 -08001652 close(entry_storage.value().read_pipe_fd);
1653
1654 // Avoid a second atomic load by invalidating instead of clearing.
1655 entry.Invalidate();
Chris Wailes7e797b62019-02-22 18:29:22 -08001656 --gUsapPoolCount;
Chris Wailesae937142019-01-24 12:57:33 -08001657 }
1658 }
1659}
1660
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07001661static int disable_execute_only(struct dl_phdr_info *info, size_t size, void *data) {
1662 // Search for any execute-only segments and mark them read+execute.
1663 for (int i = 0; i < info->dlpi_phnum; i++) {
1664 if ((info->dlpi_phdr[i].p_type == PT_LOAD) && (info->dlpi_phdr[i].p_flags == PF_X)) {
1665 mprotect(reinterpret_cast<void*>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr),
1666 info->dlpi_phdr[i].p_memsz, PROT_READ | PROT_EXEC);
1667 }
1668 }
1669 // Return non-zero to exit dl_iterate_phdr.
1670 return 0;
1671}
1672
1673/**
1674 * @param env Managed runtime environment
1675 * @return True if disable was successful.
1676 */
1677static jboolean com_android_internal_os_Zygote_nativeDisableExecuteOnly(JNIEnv* env, jclass) {
1678 return dl_iterate_phdr(disable_execute_only, nullptr) == 0;
1679}
1680
Daniel Micay76f6a862015-09-19 17:31:01 -04001681static const JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001682 { "nativeForkAndSpecialize",
Sudheer Shanka64501e52019-04-29 10:46:26 -07001683 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001684 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1685 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001686 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001687 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1688 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
Christopher Ferris76de39e2017-06-20 16:13:40 -07001689 { "nativePreApplicationInit", "()V",
Martijn Coenen86f08a52019-01-03 16:23:01 +01001690 (void *) com_android_internal_os_Zygote_nativePreApplicationInit },
1691 { "nativeInstallSeccompUidGidFilter", "(II)V",
Chris Wailesaa1c9622019-01-10 16:55:32 -08001692 (void *) com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter },
Chris Wailes7e797b62019-02-22 18:29:22 -08001693 { "nativeForkUsap", "(II[I)I",
1694 (void *) com_android_internal_os_Zygote_nativeForkUsap },
1695 { "nativeSpecializeAppProcess",
Sudheer Shanka64501e52019-04-29 10:46:26 -07001696 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V",
Chris Wailes7e797b62019-02-22 18:29:22 -08001697 (void *) com_android_internal_os_Zygote_nativeSpecializeAppProcess },
Chris Wailes6d482d542019-04-03 13:00:52 -07001698 { "nativeInitNativeState", "(Z)V",
1699 (void *) com_android_internal_os_Zygote_nativeInitNativeState },
Chris Wailes7e797b62019-02-22 18:29:22 -08001700 { "nativeGetUsapPipeFDs", "()[I",
1701 (void *) com_android_internal_os_Zygote_nativeGetUsapPipeFDs },
1702 { "nativeRemoveUsapTableEntry", "(I)Z",
1703 (void *) com_android_internal_os_Zygote_nativeRemoveUsapTableEntry },
1704 { "nativeGetUsapPoolEventFD", "()I",
1705 (void *) com_android_internal_os_Zygote_nativeGetUsapPoolEventFD },
1706 { "nativeGetUsapPoolCount", "()I",
1707 (void *) com_android_internal_os_Zygote_nativeGetUsapPoolCount },
1708 { "nativeEmptyUsapPool", "()V",
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07001709 (void *) com_android_internal_os_Zygote_nativeEmptyUsapPool },
1710 { "nativeDisableExecuteOnly", "()Z",
1711 (void *) com_android_internal_os_Zygote_nativeDisableExecuteOnly }
Narayan Kamath973b4662014-03-31 13:41:26 +01001712};
1713
1714int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001715 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001716 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1717 "callPostForkSystemServerHooks",
1718 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001719 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001720 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001721
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07001722 gZygoteInitClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteInitClassName));
1723 gCreateSystemServerClassLoader = GetStaticMethodIDOrDie(env, gZygoteInitClass,
1724 "createSystemServerClassLoader",
1725 "()V");
1726
1727 RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
1728
1729 return JNI_OK;
Narayan Kamath973b4662014-03-31 13:41:26 +01001730}
1731} // namespace android