blob: f28c4221c63704f8b79a4cdd855a33834baaa922 [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 Ferris8269f3a32019-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>
Chris Wailesee1fd452019-04-10 18:05:25 -070079#include <cutils/sockets.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
Zima11d9102019-08-15 16:50:23 +0100119static constexpr const char* kPropFuse = "persist.sys.fuse";
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700120static constexpr const char* kZygoteClassName = "com/android/internal/os/Zygote";
Zima11d9102019-08-15 16:50:23 +0100121
Narayan Kamath973b4662014-03-31 13:41:26 +0100122static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +0100123static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +0100124static jmethodID gCallPostForkChildHooks;
125
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700126static constexpr const char* kZygoteInitClassName = "com/android/internal/os/ZygoteInit";
127static jclass gZygoteInitClass;
128static jmethodID gCreateSystemServerClassLoader;
129
Chris Wailes6d482d542019-04-03 13:00:52 -0700130static bool gIsSecurityEnforced = true;
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800131
Chris Wailesaa1c9622019-01-10 16:55:32 -0800132/**
133 * The maximum number of characters (not including a null terminator) that a
134 * process name may contain.
135 */
136static constexpr size_t MAX_NAME_LENGTH = 15;
137
138/**
Chris Wailesaa1c9622019-01-10 16:55:32 -0800139 * The file descriptor for the Zygote socket opened by init.
140 */
141
142static int gZygoteSocketFD = -1;
143
144/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800145 * The file descriptor for the unspecialized app process (USAP) pool socket opened by init.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800146 */
147
Chris Wailes7e797b62019-02-22 18:29:22 -0800148static int gUsapPoolSocketFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800149
150/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800151 * The number of USAPs currently in this Zygote's pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800152 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800153static std::atomic_uint32_t gUsapPoolCount = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800154
155/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800156 * Event file descriptor used to communicate reaped USAPs to the
Chris Wailesaa1c9622019-01-10 16:55:32 -0800157 * ZygoteServer.
158 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800159static int gUsapPoolEventFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800160
161/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800162 * The maximum value that the gUSAPPoolSizeMax variable may take. This value
163 * is a mirror of ZygoteServer.USAP_POOL_SIZE_MAX_LIMIT
Chris Wailesaa1c9622019-01-10 16:55:32 -0800164 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800165static constexpr int USAP_POOL_SIZE_MAX_LIMIT = 100;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800166
Chris Wailes3d748212019-05-09 17:11:00 -0700167/** The numeric value for the maximum priority a process may possess. */
168static constexpr int PROCESS_PRIORITY_MAX = -20;
169
170/** The numeric value for the minimum priority a process may possess. */
171static constexpr int PROCESS_PRIORITY_MIN = 19;
172
173/** The numeric value for the normal priority a process should have. */
174static constexpr int PROCESS_PRIORITY_DEFAULT = 0;
175
Chris Wailesaa1c9622019-01-10 16:55:32 -0800176/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800177 * A helper class containing accounting information for USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800178 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800179class UsapTableEntry {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800180 public:
181 struct EntryStorage {
182 int32_t pid;
183 int32_t read_pipe_fd;
184
185 bool operator!=(const EntryStorage& other) {
186 return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
187 }
188 };
189
190 private:
191 static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
192
193 std::atomic<EntryStorage> mStorage;
194 static_assert(decltype(mStorage)::is_always_lock_free);
195
196 public:
Chris Wailes7e797b62019-02-22 18:29:22 -0800197 constexpr UsapTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
Chris Wailesaa1c9622019-01-10 16:55:32 -0800198
199 /**
200 * If the provided PID matches the one stored in this entry, the entry will
201 * be invalidated and the associated file descriptor will be closed. If the
202 * PIDs don't match nothing will happen.
203 *
204 * @param pid The ID of the process who's entry we want to clear.
Chris Wailesfb329ba2019-06-05 16:07:50 -0700205 * @return True if the entry was cleared by this call; false otherwise
Chris Wailesaa1c9622019-01-10 16:55:32 -0800206 */
207 bool ClearForPID(int32_t pid) {
208 EntryStorage storage = mStorage.load();
209
210 if (storage.pid == pid) {
211 /*
212 * There are three possible outcomes from this compare-and-exchange:
213 * 1) It succeeds, in which case we close the FD
214 * 2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
215 * the entry has already been cleared.
216 * 3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
217 * case the entry has already been cleared and re-used.
218 *
Chris Wailesfb329ba2019-06-05 16:07:50 -0700219 * In all three cases the goal of the caller has been met, but only in
220 * the first case do we need to decrement the pool count.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800221 */
222 if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
223 close(storage.read_pipe_fd);
Chris Wailesfb329ba2019-06-05 16:07:50 -0700224 return true;
225 } else {
226 return false;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800227 }
228
Chris Wailesaa1c9622019-01-10 16:55:32 -0800229 } else {
230 return false;
231 }
232 }
233
Chris Wailesae937142019-01-24 12:57:33 -0800234 void Clear() {
Chris Wailesdb132a32019-02-20 10:49:27 -0800235 EntryStorage storage = mStorage.load();
236
237 if (storage != INVALID_ENTRY_VALUE) {
238 close(storage.read_pipe_fd);
239 mStorage.store(INVALID_ENTRY_VALUE);
240 }
241 }
242
243 void Invalidate() {
Chris Wailesae937142019-01-24 12:57:33 -0800244 mStorage.store(INVALID_ENTRY_VALUE);
245 }
246
Chris Wailesaa1c9622019-01-10 16:55:32 -0800247 /**
248 * @return A copy of the data stored in this entry.
249 */
250 std::optional<EntryStorage> GetValues() {
251 EntryStorage storage = mStorage.load();
252
253 if (storage != INVALID_ENTRY_VALUE) {
254 return storage;
255 } else {
256 return std::nullopt;
257 }
258 }
259
260 /**
261 * Sets the entry to the given values if it is currently invalid.
262 *
263 * @param pid The process ID for the new entry.
Chris Wailes7e797b62019-02-22 18:29:22 -0800264 * @param read_pipe_fd The read end of the USAP control pipe for this
Chris Wailesaa1c9622019-01-10 16:55:32 -0800265 * process.
266 * @return True if the entry was set; false otherwise.
267 */
268 bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
269 EntryStorage new_value_storage;
270
271 new_value_storage.pid = pid;
272 new_value_storage.read_pipe_fd = read_pipe_fd;
273
274 EntryStorage expected = INVALID_ENTRY_VALUE;
275
276 return mStorage.compare_exchange_strong(expected, new_value_storage);
277 }
278};
279
280/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800281 * A table containing information about the USAPs currently in the pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800282 *
283 * Multiple threads may be attempting to modify the table, either from the
284 * signal handler or from the ZygoteServer poll loop. Atomic loads/stores in
Chris Wailes7e797b62019-02-22 18:29:22 -0800285 * the USAPTableEntry class prevent data races during these concurrent
Chris Wailesaa1c9622019-01-10 16:55:32 -0800286 * operations.
287 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800288static std::array<UsapTableEntry, USAP_POOL_SIZE_MAX_LIMIT> gUsapTable;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800289
290/**
291 * The list of open zygote file descriptors.
292 */
293static FileDescriptorTable* gOpenFdTable = nullptr;
294
Narayan Kamath973b4662014-03-31 13:41:26 +0100295// Must match values in com.android.internal.os.Zygote.
Sudheer Shankac31097d2019-06-09 23:26:41 -0700296// The order of entries here must be kept in sync with ExternalStorageViews array values.
Narayan Kamath973b4662014-03-31 13:41:26 +0100297enum MountExternalKind {
298 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700299 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700300 MOUNT_EXTERNAL_READ = 2,
301 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800302 MOUNT_EXTERNAL_LEGACY = 4,
303 MOUNT_EXTERNAL_INSTALLER = 5,
304 MOUNT_EXTERNAL_FULL = 6,
Zim74a9bba2019-09-03 20:49:13 +0100305 MOUNT_EXTERNAL_PASS_THROUGH = 7,
306 MOUNT_EXTERNAL_COUNT = 8
Sudheer Shankac31097d2019-06-09 23:26:41 -0700307};
308
309// The order of entries here must be kept in sync with MountExternalKind enum values.
310static const std::array<const std::string, MOUNT_EXTERNAL_COUNT> ExternalStorageViews = {
311 "", // MOUNT_EXTERNAL_NONE
312 "/mnt/runtime/default", // MOUNT_EXTERNAL_DEFAULT
313 "/mnt/runtime/read", // MOUNT_EXTERNAL_READ
314 "/mnt/runtime/write", // MOUNT_EXTERNAL_WRITE
315 "/mnt/runtime/write", // MOUNT_EXTERNAL_LEGACY
316 "/mnt/runtime/write", // MOUNT_EXTERNAL_INSTALLER
317 "/mnt/runtime/full", // MOUNT_EXTERNAL_FULL
Narayan Kamath973b4662014-03-31 13:41:26 +0100318};
319
Orion Hodson8d005a62018-12-05 12:28:53 +0000320// Must match values in com.android.internal.os.Zygote.
321enum RuntimeFlags : uint32_t {
322 DEBUG_ENABLE_JDWP = 1,
Yabin Cui4d8546d2019-01-29 16:29:20 -0800323 PROFILE_FROM_SHELL = 1 << 15,
Orion Hodson8d005a62018-12-05 12:28:53 +0000324};
325
Chris Wailesaa1c9622019-01-10 16:55:32 -0800326// Forward declaration so we don't have to move the signal handler.
Chris Wailes7e797b62019-02-22 18:29:22 -0800327static bool RemoveUsapTableEntry(pid_t usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800328
Andreas Gampeb053cce2015-11-17 16:38:59 -0800329static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
330 std::ostringstream oss;
331 oss << __FILE__ << ":" << line << ": " << msg;
332 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100333}
334
335// This signal handler is for zygote mode, since the zygote must reap its children
336static void SigChldHandler(int /*signal_number*/) {
337 pid_t pid;
338 int status;
Chris Wailes7e797b62019-02-22 18:29:22 -0800339 int64_t usaps_removed = 0;
Narayan Kamath973b4662014-03-31 13:41:26 +0100340
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700341 // It's necessary to save and restore the errno during this function.
342 // Since errno is stored per thread, changing it here modifies the errno
343 // on the thread on which this signal handler executes. If a signal occurs
344 // between a call and an errno check, it's possible to get the errno set
345 // here.
346 // See b/23572286 for extra information.
347 int saved_errno = errno;
348
Narayan Kamath973b4662014-03-31 13:41:26 +0100349 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800350 // Log process-death status that we care about.
Narayan Kamath973b4662014-03-31 13:41:26 +0100351 if (WIFEXITED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800352 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
353 "Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Chris Wailesfb329ba2019-06-05 16:07:50 -0700354
355 // Check to see if the PID is in the USAP pool and remove it if it is.
356 if (RemoveUsapTableEntry(pid)) {
357 ++usaps_removed;
358 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100359 } else if (WIFSIGNALED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800360 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
361 "Process %d exited due to signal %d (%s)%s", pid,
362 WTERMSIG(status), strsignal(WTERMSIG(status)),
363 WCOREDUMP(status) ? "; core dumped" : "");
Chris Wailesfb329ba2019-06-05 16:07:50 -0700364
365 // If the process exited due to a signal other than SIGTERM, check to see
366 // if the PID is in the USAP pool and remove it if it is. If the process
367 // was closed by the Zygote using SIGTERM then the USAP pool entry will
368 // have already been removed (see nativeEmptyUsapPool()).
369 if (WTERMSIG(status) != SIGTERM && RemoveUsapTableEntry(pid)) {
370 ++usaps_removed;
371 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100372 }
373
374 // If the just-crashed process is the system_server, bring down zygote
375 // so that it is restarted by init and system server will be restarted
376 // from there.
377 if (pid == gSystemServerPid) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800378 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
379 "Exit zygote because system server (pid %d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100380 kill(getpid(), SIGKILL);
381 }
382 }
383
Narayan Kamath160992d2014-04-14 14:46:07 +0100384 // Note that we shouldn't consider ECHILD an error because
385 // the secondary zygote might have no children left to wait for.
386 if (pid < 0 && errno != ECHILD) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800387 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG,
388 "Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100389 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700390
Chris Wailes7e797b62019-02-22 18:29:22 -0800391 if (usaps_removed > 0) {
Chris Wailesfe3a3482019-03-13 14:38:04 -0700392 if (TEMP_FAILURE_RETRY(write(gUsapPoolEventFD, &usaps_removed, sizeof(usaps_removed))) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800393 // If this write fails something went terribly wrong. We will now kill
394 // the zygote and let the system bring it back up.
wangmingming16d0dd1a2018-11-14 10:43:36 +0800395 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
Chris Wailes7e797b62019-02-22 18:29:22 -0800396 "Zygote failed to write to USAP pool event FD: %s",
wangmingming16d0dd1a2018-11-14 10:43:36 +0800397 strerror(errno));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800398 kill(getpid(), SIGKILL);
399 }
400 }
401
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700402 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100403}
404
yuanhao435e84b2018-01-15 15:37:02 +0800405// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
406// configured very late, because earlier in the runtime we may fork() and
407// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100408// have them be harvested immediately.
409//
yuanhao435e84b2018-01-15 15:37:02 +0800410// Ignore SIGHUP because all processes forked by the zygote are in the same
411// process group as the zygote and we don't want to be notified if we become
412// an orphaned group and have one or more stopped processes. This is not a
413// theoretical concern :
414// - we can become an orphaned group if one of our direct descendants forks
415// and is subsequently killed before its children.
416// - crash_dump routinely STOPs the process it's tracing.
417//
418// See issues b/71965619 and b/25567761 for further details.
419//
Narayan Kamath973b4662014-03-31 13:41:26 +0100420// This ends up being called repeatedly before each fork(), but there's
421// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800422static void SetSignalHandlers() {
423 struct sigaction sig_chld = {};
424 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100425
Chris Wailesaa1c9622019-01-10 16:55:32 -0800426 if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700427 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100428 }
yuanhao435e84b2018-01-15 15:37:02 +0800429
430 struct sigaction sig_hup = {};
431 sig_hup.sa_handler = SIG_IGN;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800432 if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
yuanhao435e84b2018-01-15 15:37:02 +0800433 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
434 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100435}
436
437// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800438static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100439 struct sigaction sa;
440 memset(&sa, 0, sizeof(sa));
441 sa.sa_handler = SIG_DFL;
442
Chris Wailesaa1c9622019-01-10 16:55:32 -0800443 if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700444 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100445 }
446}
447
448// Calls POSIX setgroups() using the int[] object as an argument.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800449// A nullptr argument is tolerated.
450static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) {
451 if (managed_gids == nullptr) {
452 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100453 }
454
Chris Wailesaa1c9622019-01-10 16:55:32 -0800455 ScopedIntArrayRO gids(env, managed_gids);
456 if (gids.get() == nullptr) {
457 fail_fn(CREATE_ERROR("Getting gids int array failed"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100458 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700459
Chris Wailesaa1c9622019-01-10 16:55:32 -0800460 if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
461 fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
462 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100463}
464
465// Sets the resource limits via setrlimit(2) for the values in the
466// two-dimensional array of integers that's passed in. The second dimension
Chris Wailesaa1c9622019-01-10 16:55:32 -0800467// contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
Narayan Kamath973b4662014-03-31 13:41:26 +0100468// treated as an empty array.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800469static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
470 if (managed_rlimits == nullptr) {
471 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100472 }
473
474 rlimit rlim;
475 memset(&rlim, 0, sizeof(rlim));
476
Chris Wailesaa1c9622019-01-10 16:55:32 -0800477 for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
478 ScopedLocalRef<jobject>
479 managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
480 ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
481
482 if (rlimit_handle.size() != 3) {
483 fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100484 }
485
Chris Wailesaa1c9622019-01-10 16:55:32 -0800486 rlim.rlim_cur = rlimit_handle[1];
487 rlim.rlim_max = rlimit_handle[2];
Narayan Kamath973b4662014-03-31 13:41:26 +0100488
Chris Wailesaa1c9622019-01-10 16:55:32 -0800489 if (setrlimit(rlimit_handle[0], &rlim) == -1) {
490 fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
491 rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
Narayan Kamath973b4662014-03-31 13:41:26 +0100492 }
493 }
494}
495
Orion Hodson8d005a62018-12-05 12:28:53 +0000496static void EnableDebugger() {
497 // To let a non-privileged gdbserver attach to this
498 // process, we must set our dumpable flag.
499 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
500 ALOGE("prctl(PR_SET_DUMPABLE) failed");
501 }
502
503 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
504 // is enabled (see kernel/Documentation/security/Yama.txt).
505 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
506 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
507 // case since it's expected behaviour.
508 if (errno != EINVAL) {
509 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
510 }
511 }
512
Orion Hodson2b71ad02018-12-07 16:44:33 +0000513 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
514 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
515 // Set the soft limit on core dump size to 0 without changing the hard limit.
516 rlimit rl;
517 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
518 ALOGE("getrlimit(RLIMIT_CORE) failed");
519 } else {
520 rl.rlim_cur = 0;
521 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
522 ALOGE("setrlimit(RLIMIT_CORE) failed");
523 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000524 }
525 }
526}
527
Christopher Ferris76de39e2017-06-20 16:13:40 -0700528static void PreApplicationInit() {
529 // The child process sets this to indicate it's not the zygote.
Christopher Ferrised364d62019-04-09 16:42:32 -0700530 android_mallopt(M_SET_ZYGOTE_CHILD, nullptr, 0);
Christopher Ferris76de39e2017-06-20 16:13:40 -0700531
532 // Set the jemalloc decay time to 1.
533 mallopt(M_DECAY_TIME, 1);
534}
535
Martijn Coenen86f08a52019-01-03 16:23:01 +0100536static void SetUpSeccompFilter(uid_t uid, bool is_child_zygote) {
Chris Wailes6d482d542019-04-03 13:00:52 -0700537 if (!gIsSecurityEnforced) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800538 ALOGI("seccomp disabled by setenforce 0");
539 return;
540 }
541
542 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700543 if (uid >= AID_APP_START) {
Martijn Coenen86f08a52019-01-03 16:23:01 +0100544 if (is_child_zygote) {
Martijn Coenen6ef16802019-01-18 16:40:01 +0100545 set_app_zygote_seccomp_filter();
Martijn Coenen86f08a52019-01-03 16:23:01 +0100546 } else {
547 set_app_seccomp_filter();
548 }
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800549 } else {
550 set_system_seccomp_filter();
551 }
552}
553
Chris Wailesaa1c9622019-01-10 16:55:32 -0800554static void EnableKeepCapabilities(fail_fn_t fail_fn) {
555 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
556 fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100557 }
558}
559
Chris Wailesaa1c9622019-01-10 16:55:32 -0800560static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
561 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
562 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100563 if (errno == EINVAL) {
564 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
565 "your kernel is compiled with file capabilities support");
566 } else {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800567 fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100568 }
569 }
570 }
571}
572
Chris Wailesaa1c9622019-01-10 16:55:32 -0800573static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
Josh Gao45dab782017-02-01 14:56:09 -0800574 __user_cap_header_struct capheader;
575 memset(&capheader, 0, sizeof(capheader));
576 capheader.version = _LINUX_CAPABILITY_VERSION_3;
577 capheader.pid = 0;
578
579 __user_cap_data_struct capdata[2];
580 if (capget(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800581 fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800582 }
583
584 capdata[0].inheritable = inheritable;
585 capdata[1].inheritable = inheritable >> 32;
586
587 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800588 fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800589 }
590}
591
Chris Wailesaa1c9622019-01-10 16:55:32 -0800592static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
593 fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100594 __user_cap_header_struct capheader;
595 memset(&capheader, 0, sizeof(capheader));
596 capheader.version = _LINUX_CAPABILITY_VERSION_3;
597 capheader.pid = 0;
598
599 __user_cap_data_struct capdata[2];
600 memset(&capdata, 0, sizeof(capdata));
601 capdata[0].effective = effective;
602 capdata[1].effective = effective >> 32;
603 capdata[0].permitted = permitted;
604 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800605 capdata[0].inheritable = inheritable;
606 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100607
608 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800609 fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
610 "failed: %s", permitted, effective, inheritable, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100611 }
612}
613
Riddle Hsu32dbdca2019-05-17 23:10:16 -0600614static void SetSchedulerPolicy(fail_fn_t fail_fn, bool is_top_app) {
615 SchedPolicy policy = is_top_app ? SP_TOP_APP : SP_DEFAULT;
616
617 if (is_top_app && cpusets_enabled()) {
618 errno = -set_cpuset_policy(0, policy);
619 if (errno != 0) {
620 fail_fn(CREATE_ERROR("set_cpuset_policy(0, %d) failed: %s", policy, strerror(errno)));
621 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100622 }
Riddle Hsu32dbdca2019-05-17 23:10:16 -0600623
624 errno = -set_sched_policy(0, policy);
625 if (errno != 0) {
626 fail_fn(CREATE_ERROR("set_sched_policy(0, %d) failed: %s", policy, strerror(errno)));
627 }
628
629 // We are going to lose the permission to set scheduler policy during the specialization, so make
630 // sure that we don't cache the fd of cgroup path that may cause sepolicy violation by writing
631 // value to the cached fd directly when creating new thread.
632 DropTaskProfilesResourceCaching();
Narayan Kamath973b4662014-03-31 13:41:26 +0100633}
634
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700635static int UnmountTree(const char* path) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600636 ATRACE_CALL();
637
Sudheer Shanka74584a52019-02-22 13:04:41 -0800638 size_t path_len = strlen(path);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700639
Sudheer Shanka74584a52019-02-22 13:04:41 -0800640 FILE* fp = setmntent("/proc/mounts", "r");
641 if (fp == nullptr) {
642 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
643 return -errno;
644 }
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700645
Sudheer Shanka74584a52019-02-22 13:04:41 -0800646 // Some volumes can be stacked on each other, so force unmount in
647 // reverse order to give us the best chance of success.
648 std::list<std::string> to_unmount;
649 mntent* mentry;
650 while ((mentry = getmntent(fp)) != nullptr) {
651 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
652 to_unmount.push_front(std::string(mentry->mnt_dir));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700653 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800654 }
655 endmntent(fp);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700656
Sudheer Shanka74584a52019-02-22 13:04:41 -0800657 for (const auto& path : to_unmount) {
658 if (umount2(path.c_str(), MNT_DETACH)) {
659 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700660 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800661 }
662 return 0;
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700663}
664
Sudheer Shankac31097d2019-06-09 23:26:41 -0700665static void CreateDir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
666 fail_fn_t fail_fn) {
667 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
668 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s: %s",
669 dir.c_str(), strerror(errno)));
670 }
671}
672
673static void BindMount(const std::string& source_dir, const std::string& target_dir,
674 fail_fn_t fail_fn) {
675 if (TEMP_FAILURE_RETRY(mount(source_dir.c_str(), target_dir.c_str(), nullptr,
676 MS_BIND | MS_REC, nullptr)) == -1) {
677 fail_fn(CREATE_ERROR("Failed to mount %s to %s: %s",
678 source_dir.c_str(), target_dir.c_str(), strerror(errno)));
679 }
680}
681
Narayan Kamath973b4662014-03-31 13:41:26 +0100682// Create a private mount namespace and bind mount appropriate emulated
683// storage for the given user.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800684static void MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shankae73ae322019-04-29 10:46:26 -0700685 bool force_mount_namespace,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800686 fail_fn_t fail_fn) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800687 // See storage config details at http://source.android.com/tech/storage/
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600688 ATRACE_CALL();
Jeff Sharkey9527b222015-06-24 15:24:48 -0700689
Sudheer Shankac31097d2019-06-09 23:26:41 -0700690 if (mount_mode < 0 || mount_mode >= MOUNT_EXTERNAL_COUNT) {
691 fail_fn(CREATE_ERROR("Unknown mount_mode: %d", mount_mode));
692 }
693
694 if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800695 // Sane default of no storage visible
696 return;
697 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400698
Sudheer Shanka74584a52019-02-22 13:04:41 -0800699 // Create a second private mount namespace for our process
700 if (unshare(CLONE_NEWNS) == -1) {
701 fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
702 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400703
Sudheer Shanka74584a52019-02-22 13:04:41 -0800704 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
705 if (mount_mode == MOUNT_EXTERNAL_NONE) {
706 return;
707 }
Robert Sesek06f39302017-03-20 17:30:05 -0400708
Zima11d9102019-08-15 16:50:23 +0100709 const userid_t user_id = multiuser_get_user_id(uid);
Sudheer Shankac31097d2019-06-09 23:26:41 -0700710 const std::string user_source = StringPrintf("/mnt/user/%d", user_id);
Zim74a9bba2019-09-03 20:49:13 +0100711 const std::string pass_through_source = StringPrintf("/mnt/pass_through/%d", user_id);
Zima11d9102019-08-15 16:50:23 +0100712 bool isFuse = GetBoolProperty(kPropFuse, false);
713
Sudheer Shankac31097d2019-06-09 23:26:41 -0700714 CreateDir(user_source, 0751, AID_ROOT, AID_ROOT, fail_fn);
Zima11d9102019-08-15 16:50:23 +0100715
716 if (isFuse) {
Zim74a9bba2019-09-03 20:49:13 +0100717 BindMount(mount_mode == MOUNT_EXTERNAL_PASS_THROUGH ? pass_through_source : user_source,
718 "/storage", fail_fn);
Zima11d9102019-08-15 16:50:23 +0100719 } else {
720 const std::string& storage_source = ExternalStorageViews[mount_mode];
721 BindMount(storage_source, "/storage", fail_fn);
722
723 // Mount user-specific symlink helper into place
724 BindMount(user_source, "/storage/self", fail_fn);
725 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100726}
727
Narayan Kamath973b4662014-03-31 13:41:26 +0100728static bool NeedsNoRandomizeWorkaround() {
729#if !defined(__arm__)
730 return false;
731#else
732 int major;
733 int minor;
734 struct utsname uts;
735 if (uname(&uts) == -1) {
736 return false;
737 }
738
739 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
740 return false;
741 }
742
743 // Kernels before 3.4.* need the workaround.
744 return (major < 3) || ((major == 3) && (minor < 4));
745#endif
746}
Narayan Kamath973b4662014-03-31 13:41:26 +0100747
748// Utility to close down the Zygote socket file descriptors while
749// the child is still running as root with Zygote's privileges. Each
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800750// descriptor (if any) is closed via dup3(), replacing it with a valid
Narayan Kamath973b4662014-03-31 13:41:26 +0100751// (open) descriptor to /dev/null.
752
Chris Wailesaa1c9622019-01-10 16:55:32 -0800753static void DetachDescriptors(JNIEnv* env,
754 const std::vector<int>& fds_to_close,
755 fail_fn_t fail_fn) {
756
757 if (fds_to_close.size() > 0) {
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800758 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800759 if (devnull_fd == -1) {
760 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100761 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800762
763 for (int fd : fds_to_close) {
764 ALOGV("Switching descriptor %d to /dev/null", fd);
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800765 if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
766 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800767 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100768 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100769 }
770}
771
Chris Wailesaa1c9622019-01-10 16:55:32 -0800772void SetThreadName(const std::string& thread_name) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100773 bool hasAt = false;
774 bool hasDot = false;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800775
776 for (const char str_el : thread_name) {
777 if (str_el == '.') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100778 hasDot = true;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800779 } else if (str_el == '@') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100780 hasAt = true;
781 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100782 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800783
784 const char* name_start_ptr = thread_name.c_str();
785 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
786 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
Narayan Kamath973b4662014-03-31 13:41:26 +0100787 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800788
Narayan Kamath973b4662014-03-31 13:41:26 +0100789 // pthread_setname_np fails rather than truncating long strings.
790 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
Chris Wailesaa1c9622019-01-10 16:55:32 -0800791 strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
Narayan Kamath973b4662014-03-31 13:41:26 +0100792 errno = pthread_setname_np(pthread_self(), buf);
793 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700794 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100795 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800796 // Update base::logging default tag.
797 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100798}
799
Chris Wailesaa1c9622019-01-10 16:55:32 -0800800/**
801 * A failure function used to report fatal errors to the managed runtime. This
802 * function is often curried with the process name information and then passed
803 * to called functions.
804 *
805 * @param env Managed runtime environment
806 * @param process_name A native representation of the process name
807 * @param managed_process_name A managed representation of the process name
808 * @param msg The error message to be reported
809 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700810[[noreturn]]
811static void ZygoteFailure(JNIEnv* env,
812 const char* process_name,
813 jstring managed_process_name,
814 const std::string& msg) {
815 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
816 if (managed_process_name != nullptr) {
817 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
818 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
819 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -0700820 }
821 }
822
Chris Wailesaf594fc2018-11-02 11:00:07 -0700823 const std::string& error_msg =
824 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700825
Chris Wailesaf594fc2018-11-02 11:00:07 -0700826 env->FatalError(error_msg.c_str());
827 __builtin_unreachable();
828}
David Sehrde8d0bd2018-06-22 10:45:36 -0700829
Chris Wailesaa1c9622019-01-10 16:55:32 -0800830/**
831 * A helper method for converting managed strings to native strings. A fatal
832 * error is generated if a problem is encountered in extracting a non-null
833 * string.
834 *
835 * @param env Managed runtime environment
836 * @param process_name A native representation of the process name
837 * @param managed_process_name A managed representation of the process name
838 * @param managed_string The managed string to extract
839 *
840 * @return An empty option if the managed string is null. A optional-wrapped
841 * string otherwise.
842 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700843static std::optional<std::string> ExtractJString(JNIEnv* env,
844 const char* process_name,
845 jstring managed_process_name,
846 jstring managed_string) {
847 if (managed_string == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800848 return std::nullopt;
Chris Wailesaf594fc2018-11-02 11:00:07 -0700849 } else {
850 ScopedUtfChars scoped_string_chars(env, managed_string);
851
852 if (scoped_string_chars.c_str() != nullptr) {
853 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700854 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -0700855 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700856 }
857 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700858}
859
Chris Wailesaa1c9622019-01-10 16:55:32 -0800860/**
861 * A helper method for converting managed string arrays to native vectors. A
862 * fatal error is generated if a problem is encountered in extracting a non-null array.
863 *
864 * @param env Managed runtime environment
865 * @param process_name A native representation of the process name
866 * @param managed_process_name A managed representation of the process name
867 * @param managed_array The managed integer array to extract
868 *
869 * @return An empty option if the managed array is null. A optional-wrapped
870 * vector otherwise.
871 */
872static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
873 const char* process_name,
874 jstring managed_process_name,
875 jintArray managed_array) {
876 if (managed_array == nullptr) {
877 return std::nullopt;
878 } else {
879 ScopedIntArrayRO managed_array_handle(env, managed_array);
Narayan Kamath973b4662014-03-31 13:41:26 +0100880
Chris Wailesaa1c9622019-01-10 16:55:32 -0800881 if (managed_array_handle.get() != nullptr) {
882 std::vector<int> native_array;
883 native_array.reserve(managed_array_handle.size());
884
885 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
886 native_array.push_back(managed_array_handle[array_index]);
887 }
888
889 return std::move(native_array);
890
891 } else {
892 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
893 }
894 }
895}
896
897/**
Chris Wailesaa1c9622019-01-10 16:55:32 -0800898 * A utility function for blocking signals.
899 *
900 * @param signum Signal number to block
901 * @param fail_fn Fatal error reporting function
902 *
903 * @see ZygoteFailure
904 */
905static void BlockSignal(int signum, fail_fn_t fail_fn) {
906 sigset_t sigs;
907 sigemptyset(&sigs);
908 sigaddset(&sigs, signum);
909
910 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
911 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
912 }
913}
914
915
916/**
917 * A utility function for unblocking signals.
918 *
919 * @param signum Signal number to unblock
920 * @param fail_fn Fatal error reporting function
921 *
922 * @see ZygoteFailure
923 */
924static void UnblockSignal(int signum, fail_fn_t fail_fn) {
925 sigset_t sigs;
926 sigemptyset(&sigs);
927 sigaddset(&sigs, signum);
928
929 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
930 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
931 }
932}
933
Chris Wailes7e797b62019-02-22 18:29:22 -0800934static void ClearUsapTable() {
935 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -0800936 entry.Clear();
937 }
938
Chris Wailes7e797b62019-02-22 18:29:22 -0800939 gUsapPoolCount = 0;
Chris Wailesae937142019-01-24 12:57:33 -0800940}
941
Chris Wailesaa1c9622019-01-10 16:55:32 -0800942// Utility routine to fork a process from the zygote.
943static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
944 const std::vector<int>& fds_to_close,
Chris Wailes3d748212019-05-09 17:11:00 -0700945 const std::vector<int>& fds_to_ignore,
946 bool is_priority_fork) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800947 SetSignalHandlers();
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000948
Chris Wailesaf594fc2018-11-02 11:00:07 -0700949 // Curry a failure function.
950 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
951 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -0700952
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000953 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
954 // log, which would result in the logging FDs we close being reopened.
955 // This would cause failures because the FDs are not whitelisted.
956 //
957 // Note that the zygote process is single threaded at this point.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800958 BlockSignal(SIGCHLD, fail_fn);
Narayan Kamathdfcc79e2016-11-07 16:22:48 +0000959
Narayan Kamath3764a262016-08-30 15:36:19 +0100960 // Close any logging related FDs before we start evaluating the list of
961 // file descriptors.
962 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -0700963 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +0100964
Chris Wailesaf594fc2018-11-02 11:00:07 -0700965 // If this is the first fork for this zygote, create the open FD table. If
966 // it isn't, we just need to check whether the list of open files has changed
967 // (and it shouldn't in the normal case).
Chris Wailesaf594fc2018-11-02 11:00:07 -0700968 if (gOpenFdTable == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800969 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
970 } else {
971 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100972 }
973
Josh Gaod7951102018-06-26 16:05:12 -0700974 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
975
Narayan Kamath973b4662014-03-31 13:41:26 +0100976 pid_t pid = fork();
977
978 if (pid == 0) {
Chris Wailes3d748212019-05-09 17:11:00 -0700979 if (is_priority_fork) {
980 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
981 } else {
982 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MIN);
983 }
984
David Sehrde8d0bd2018-06-22 10:45:36 -0700985 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -0700986 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -0700987
Narayan Kamath973b4662014-03-31 13:41:26 +0100988 // Clean up any descriptors which must be closed immediately
Chris Wailesaa1c9622019-01-10 16:55:32 -0800989 DetachDescriptors(env, fds_to_close, fail_fn);
Narayan Kamath973b4662014-03-31 13:41:26 +0100990
Chris Wailes7e797b62019-02-22 18:29:22 -0800991 // Invalidate the entries in the USAP table.
992 ClearUsapTable();
Chris Wailesae937142019-01-24 12:57:33 -0800993
Narayan Kamathc5f27a72016-08-19 13:45:24 +0100994 // Re-open all remaining open file descriptors so that they aren't shared
995 // with the zygote across a fork.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800996 gOpenFdTable->ReopenOrDetach(fail_fn);
Josh Gaod7951102018-06-26 16:05:12 -0700997
998 // Turn fdsan back on.
999 android_fdsan_set_error_level(fdsan_error_level);
Martin Stjernholma9bd8c32019-02-23 02:35:07 +00001000 } else {
1001 ALOGD("Forked child process %d", pid);
David Sehrde8d0bd2018-06-22 10:45:36 -07001002 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001003
David Sehrde8d0bd2018-06-22 10:45:36 -07001004 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001005 UnblockSignal(SIGCHLD, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001006
Narayan Kamath973b4662014-03-31 13:41:26 +01001007 return pid;
1008}
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001009
Chris Wailesaf594fc2018-11-02 11:00:07 -07001010// Utility routine to specialize a zygote child process.
1011static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
1012 jint runtime_flags, jobjectArray rlimits,
1013 jlong permitted_capabilities, jlong effective_capabilities,
1014 jint mount_external, jstring managed_se_info,
1015 jstring managed_nice_name, bool is_system_server,
1016 bool is_child_zygote, jstring managed_instruction_set,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001017 jstring managed_app_data_dir, bool is_top_app) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001018 const char* process_name = is_system_server ? "system_server" : "zygote";
1019 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
1020 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001021
1022 auto se_info = extract_fn(managed_se_info);
1023 auto nice_name = extract_fn(managed_nice_name);
1024 auto instruction_set = extract_fn(managed_instruction_set);
1025 auto app_data_dir = extract_fn(managed_app_data_dir);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001026
Chris Wailesaf594fc2018-11-02 11:00:07 -07001027 // Keep capabilities across UID change, unless we're staying root.
1028 if (uid != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001029 EnableKeepCapabilities(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001030 }
1031
Chris Wailesaa1c9622019-01-10 16:55:32 -08001032 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001033
Chris Wailesaa1c9622019-01-10 16:55:32 -08001034 DropCapabilitiesBoundingSet(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001035
1036 bool use_native_bridge = !is_system_server &&
1037 instruction_set.has_value() &&
1038 android::NativeBridgeAvailable() &&
1039 android::NeedsNativeBridge(instruction_set.value().c_str());
1040
1041 if (use_native_bridge && !app_data_dir.has_value()) {
1042 // The app_data_dir variable should never be empty if we need to use a
1043 // native bridge. In general, app_data_dir will never be empty for normal
1044 // applications. It can only happen in special cases (for isolated
1045 // processes which are not associated with any app). These are launched by
1046 // the framework and should not be emulated anyway.
1047 use_native_bridge = false;
1048 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
1049 }
1050
Sudheer Shankae73ae322019-04-29 10:46:26 -07001051 MountEmulatedStorage(uid, mount_external, use_native_bridge, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001052
1053 // If this zygote isn't root, it won't be able to create a process group,
1054 // since the directory is owned by root.
1055 if (!is_system_server && getuid() == 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001056 const int rc = createProcessGroup(uid, getpid());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001057 if (rc == -EROFS) {
1058 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
1059 } else if (rc != 0) {
1060 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
1061 }
1062 }
1063
Chris Wailesaa1c9622019-01-10 16:55:32 -08001064 SetGids(env, gids, fail_fn);
1065 SetRLimits(env, rlimits, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001066
1067 if (use_native_bridge) {
1068 // Due to the logic behind use_native_bridge we know that both app_data_dir
1069 // and instruction_set contain values.
1070 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
1071 instruction_set.value().c_str());
1072 }
1073
1074 if (setresgid(gid, gid, gid) == -1) {
1075 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
1076 }
1077
1078 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
1079 // before changing uid from 0, which clears capabilities. The other
1080 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
1081 // breaks SELinux domain transition (see b/71859146). As the result,
1082 // privileged syscalls used below still need to be accessible in app process.
Martijn Coenen86f08a52019-01-03 16:23:01 +01001083 SetUpSeccompFilter(uid, is_child_zygote);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001084
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001085 // Must be called before losing the permission to set scheduler policy.
1086 SetSchedulerPolicy(fail_fn, is_top_app);
1087
Chris Wailesaf594fc2018-11-02 11:00:07 -07001088 if (setresuid(uid, uid, uid) == -1) {
1089 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1090 }
1091
1092 // The "dumpable" flag of a process, which controls core dump generation, is
1093 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1094 // user or group ID changes. See proc(5) for possible values. In most cases,
1095 // the value is 0, so core dumps are disabled for zygote children. However,
1096 // when running in a Chrome OS container, the value is already set to 2,
1097 // which allows the external crash reporter to collect all core dumps. Since
1098 // only system crashes are interested, core dump is disabled for app
1099 // processes. This also ensures compliance with CTS.
1100 int dumpable = prctl(PR_GET_DUMPABLE);
1101 if (dumpable == -1) {
1102 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1103 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1104 }
1105
1106 if (dumpable == 2 && uid >= AID_APP) {
1107 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1108 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1109 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1110 }
1111 }
1112
Orion Hodson8d005a62018-12-05 12:28:53 +00001113 // Set process properties to enable debugging if required.
1114 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1115 EnableDebugger();
1116 }
Yabin Cui4d8546d2019-01-29 16:29:20 -08001117 if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
1118 // simpleperf needs the process to be dumpable to profile it.
1119 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
1120 ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
1121 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
1122 }
1123 }
Orion Hodson8d005a62018-12-05 12:28:53 +00001124
Chris Wailesaf594fc2018-11-02 11:00:07 -07001125 if (NeedsNoRandomizeWorkaround()) {
1126 // Work around ARM kernel ASLR lossage (http://b/5817320).
1127 int old_personality = personality(0xffffffff);
1128 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1129 if (new_personality == -1) {
1130 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1131 }
1132 }
1133
Chris Wailesaa1c9622019-01-10 16:55:32 -08001134 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001135
Mathieu Chartier0bccbf72019-01-30 15:56:17 -08001136 __android_log_close();
1137 stats_log_close();
1138
Chris Wailesaf594fc2018-11-02 11:00:07 -07001139 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1140 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1141
1142 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1143 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1144 uid, is_system_server, se_info_ptr, nice_name_ptr));
1145 }
1146
1147 // Make it easier to debug audit logs by setting the main thread's name to the
1148 // nice name rather than "app_process".
1149 if (nice_name.has_value()) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001150 SetThreadName(nice_name.value());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001151 } else if (is_system_server) {
1152 SetThreadName("system_server");
1153 }
1154
1155 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1156 UnsetChldSignalHandler();
1157
1158 if (is_system_server) {
Mathieu Chartier2cb0a4d2019-11-21 14:30:03 -08001159 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks, runtime_flags);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001160 if (env->ExceptionCheck()) {
1161 fail_fn("Error calling post fork system server hooks.");
1162 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001163
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07001164 // Prefetch the classloader for the system server. This is done early to
1165 // allow a tie-down of the proper system server selinux domain.
1166 env->CallStaticVoidMethod(gZygoteInitClass, gCreateSystemServerClassLoader);
1167 if (env->ExceptionCheck()) {
1168 // Be robust here. The Java code will attempt to create the classloader
1169 // at a later point (but may not have rights to use AoT artifacts).
1170 env->ExceptionClear();
1171 }
1172
Chris Wailesaf594fc2018-11-02 11:00:07 -07001173 // TODO(oth): Remove hardcoded label here (b/117874058).
1174 static const char* kSystemServerLabel = "u:r:system_server:s0";
1175 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1176 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1177 }
1178 }
1179
1180 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1181 is_system_server, is_child_zygote, managed_instruction_set);
1182
Chris Wailes3d748212019-05-09 17:11:00 -07001183 // Reset the process priority to the default value.
1184 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_DEFAULT);
1185
Chris Wailesaf594fc2018-11-02 11:00:07 -07001186 if (env->ExceptionCheck()) {
1187 fail_fn("Error calling post fork hooks.");
1188 }
1189}
1190
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001191static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1192 __user_cap_header_struct capheader;
1193 memset(&capheader, 0, sizeof(capheader));
1194 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1195 capheader.pid = 0;
1196
1197 __user_cap_data_struct capdata[2];
1198 if (capget(&capheader, &capdata[0]) == -1) {
1199 ALOGE("capget failed: %s", strerror(errno));
1200 RuntimeAbort(env, __LINE__, "capget failed");
1201 }
1202
Chris Wailesaf594fc2018-11-02 11:00:07 -07001203 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1204}
1205
1206static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1207 bool is_child_zygote) {
1208 jlong capabilities = 0;
1209
1210 /*
1211 * Grant the following capabilities to the Bluetooth user:
1212 * - CAP_WAKE_ALARM
Nitin Shivpure99cec9d2019-05-29 14:02:49 +05301213 * - CAP_NET_ADMIN
Chris Wailesaf594fc2018-11-02 11:00:07 -07001214 * - CAP_NET_RAW
1215 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1216 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1217 */
1218
1219 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1220 capabilities |= (1LL << CAP_WAKE_ALARM);
Nitin Shivpure99cec9d2019-05-29 14:02:49 +05301221 capabilities |= (1LL << CAP_NET_ADMIN);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001222 capabilities |= (1LL << CAP_NET_RAW);
1223 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1224 capabilities |= (1LL << CAP_SYS_NICE);
1225 }
1226
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001227 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1228 capabilities |= (1LL << CAP_NET_ADMIN);
1229 capabilities |= (1LL << CAP_NET_BROADCAST);
1230 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1231 capabilities |= (1LL << CAP_NET_RAW);
1232 }
1233
Chris Wailesaf594fc2018-11-02 11:00:07 -07001234 /*
1235 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1236 */
1237
1238 bool gid_wakelock_found = false;
1239 if (gid == AID_WAKELOCK) {
1240 gid_wakelock_found = true;
1241 } else if (gids != nullptr) {
1242 jsize gids_num = env->GetArrayLength(gids);
1243 ScopedIntArrayRO native_gid_proxy(env, gids);
1244
1245 if (native_gid_proxy.get() == nullptr) {
1246 RuntimeAbort(env, __LINE__, "Bad gids array");
1247 }
1248
Chris Wailes31c52c92019-02-14 11:20:02 -08001249 for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
1250 if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001251 gid_wakelock_found = true;
1252 break;
1253 }
1254 }
1255 }
1256
1257 if (gid_wakelock_found) {
1258 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1259 }
1260
1261 /*
1262 * Grant child Zygote processes the following capabilities:
1263 * - CAP_SETUID (change UID of child processes)
1264 * - CAP_SETGID (change GID of child processes)
1265 * - CAP_SETPCAP (change capabilities of child processes)
1266 */
1267
1268 if (is_child_zygote) {
1269 capabilities |= (1LL << CAP_SETUID);
1270 capabilities |= (1LL << CAP_SETGID);
1271 capabilities |= (1LL << CAP_SETPCAP);
1272 }
1273
1274 /*
1275 * Containers run without some capabilities, so drop any caps that are not
1276 * available.
1277 */
1278
1279 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001280}
Chris Wailesaa1c9622019-01-10 16:55:32 -08001281
1282/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001283 * Adds the given information about a newly created unspecialized app
1284 * processes to the Zygote's USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001285 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001286 * @param usap_pid Process ID of the newly created USAP
1287 * @param read_pipe_fd File descriptor for the read end of the USAP
1288 * reporting pipe. Used in the ZygoteServer poll loop to track USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001289 * specialization.
1290 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001291static void AddUsapTableEntry(pid_t usap_pid, int read_pipe_fd) {
1292 static int sUsapTableInsertIndex = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001293
Chris Wailes7e797b62019-02-22 18:29:22 -08001294 int search_index = sUsapTableInsertIndex;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001295
1296 do {
Chris Wailes7e797b62019-02-22 18:29:22 -08001297 if (gUsapTable[search_index].SetIfInvalid(usap_pid, read_pipe_fd)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001298 // Start our next search right after where we finished this one.
Chris Wailes7e797b62019-02-22 18:29:22 -08001299 sUsapTableInsertIndex = (search_index + 1) % gUsapTable.size();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001300
1301 return;
1302 }
1303
Chris Wailes7e797b62019-02-22 18:29:22 -08001304 search_index = (search_index + 1) % gUsapTable.size();
1305 } while (search_index != sUsapTableInsertIndex);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001306
1307 // Much like money in the banana stand, there should always be an entry
Chris Wailes7e797b62019-02-22 18:29:22 -08001308 // in the USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001309 __builtin_unreachable();
1310}
1311
1312/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001313 * Invalidates the entry in the USAPTable corresponding to the provided
1314 * process ID if it is present. If an entry was removed the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001315 * count is decremented.
1316 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001317 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001318 * @return True if an entry was invalidated; false otherwise
1319 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001320static bool RemoveUsapTableEntry(pid_t usap_pid) {
1321 for (UsapTableEntry& entry : gUsapTable) {
1322 if (entry.ClearForPID(usap_pid)) {
1323 --gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001324 return true;
1325 }
1326 }
1327
1328 return false;
1329}
1330
1331/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001332 * @return A vector of the read pipe FDs for each of the active USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001333 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001334std::vector<int> MakeUsapPipeReadFDVector() {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001335 std::vector<int> fd_vec;
Chris Wailes7e797b62019-02-22 18:29:22 -08001336 fd_vec.reserve(gUsapTable.size());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001337
Chris Wailes7e797b62019-02-22 18:29:22 -08001338 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001339 auto entry_values = entry.GetValues();
1340
1341 if (entry_values.has_value()) {
1342 fd_vec.push_back(entry_values.value().read_pipe_fd);
1343 }
1344 }
1345
1346 return fd_vec;
1347}
1348
Chris Wailes6d482d542019-04-03 13:00:52 -07001349static void UnmountStorageOnInit(JNIEnv* env) {
1350 // Zygote process unmount root storage space initially before every child processes are forked.
1351 // Every forked child processes (include SystemServer) only mount their own root storage space
1352 // and no need unmount storage operation in MountEmulatedStorage method.
1353 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1354
1355 // See storage config details at http://source.android.com/tech/storage/
1356 // Create private mount namespace shared by all children
1357 if (unshare(CLONE_NEWNS) == -1) {
1358 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1359 return;
1360 }
1361
1362 // Mark rootfs as being a slave so that changes from default
1363 // namespace only flow into our children.
1364 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1365 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1366 return;
1367 }
1368
1369 // Create a staging tmpfs that is shared by our children; they will
1370 // bind mount storage into their respective private namespaces, which
1371 // are isolated from each other.
1372 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1373 if (target_base != nullptr) {
1374#define STRINGIFY_UID(x) __STRING(x)
1375 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1376 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1377 ALOGE("Failed to mount tmpfs to %s", target_base);
1378 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1379 return;
1380 }
1381#undef STRINGIFY_UID
1382 }
1383
1384 UnmountTree("/storage");
1385}
1386
Chris Wailesff8d4e72019-04-10 17:49:24 -07001387static int DisableExecuteOnly(struct dl_phdr_info* info,
1388 size_t size [[maybe_unused]],
1389 void* data [[maybe_unused]]) {
1390 // Search for any execute-only segments and mark them read+execute.
1391 for (int i = 0; i < info->dlpi_phnum; i++) {
1392 if ((info->dlpi_phdr[i].p_type == PT_LOAD) && (info->dlpi_phdr[i].p_flags == PF_X)) {
1393 mprotect(reinterpret_cast<void*>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr),
1394 info->dlpi_phdr[i].p_memsz, PROT_READ | PROT_EXEC);
1395 }
1396 }
1397 // Return non-zero to exit dl_iterate_phdr.
1398 return 0;
1399}
1400
Narayan Kamath973b4662014-03-31 13:41:26 +01001401} // anonymous namespace
1402
1403namespace android {
1404
Christopher Ferris76de39e2017-06-20 16:13:40 -07001405static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1406 PreApplicationInit();
1407}
1408
Narayan Kamath973b4662014-03-31 13:41:26 +01001409static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1410 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001411 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001412 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001413 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001414 jstring instruction_set, jstring app_data_dir, jboolean is_top_app) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001415 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001416
Chris Wailesaa1c9622019-01-10 16:55:32 -08001417 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1418 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1419 }
1420
1421 std::vector<int> fds_to_close =
1422 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1423 std::vector<int> fds_to_ignore =
1424 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1425 .value_or(std::vector<int>());
1426
Chris Wailes7e797b62019-02-22 18:29:22 -08001427 std::vector<int> usap_pipes = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001428
Chris Wailes7e797b62019-02-22 18:29:22 -08001429 fds_to_close.insert(fds_to_close.end(), usap_pipes.begin(), usap_pipes.end());
1430 fds_to_ignore.insert(fds_to_ignore.end(), usap_pipes.begin(), usap_pipes.end());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001431
Chris Wailes7e797b62019-02-22 18:29:22 -08001432 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001433
Chris Wailes7e797b62019-02-22 18:29:22 -08001434 if (gUsapPoolEventFD != -1) {
1435 fds_to_close.push_back(gUsapPoolEventFD);
1436 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001437 }
1438
Chris Wailes3d748212019-05-09 17:11:00 -07001439 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore, true);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001440
David Sehrde8d0bd2018-06-22 10:45:36 -07001441 if (pid == 0) {
1442 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1443 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001444 mount_external, se_info, nice_name, false,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001445 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
1446 is_top_app == JNI_TRUE);
David Sehrde8d0bd2018-06-22 10:45:36 -07001447 }
1448 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001449}
1450
1451static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1452 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001453 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1454 jlong effective_capabilities) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001455 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001456 fds_to_ignore(fds_to_close);
1457
Chris Wailes7e797b62019-02-22 18:29:22 -08001458 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001459
Chris Wailes7e797b62019-02-22 18:29:22 -08001460 if (gUsapPoolEventFD != -1) {
1461 fds_to_close.push_back(gUsapPoolEventFD);
1462 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001463 }
1464
Chris Wailesaf594fc2018-11-02 11:00:07 -07001465 pid_t pid = ForkCommon(env, true,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001466 fds_to_close,
Chris Wailes3d748212019-05-09 17:11:00 -07001467 fds_to_ignore,
1468 true);
David Sehrde8d0bd2018-06-22 10:45:36 -07001469 if (pid == 0) {
1470 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001471 permitted_capabilities, effective_capabilities,
1472 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001473 false, nullptr, nullptr, /* is_top_app= */ false);
David Sehrde8d0bd2018-06-22 10:45:36 -07001474 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001475 // The zygote process checks whether the child process has died or not.
1476 ALOGI("System server process %d has been created", pid);
1477 gSystemServerPid = pid;
1478 // There is a slight window that the system server process has crashed
1479 // but it went unnoticed because we haven't published its pid yet. So
1480 // we recheck here just to make sure that all is well.
1481 int status;
1482 if (waitpid(pid, &status, WNOHANG) == pid) {
1483 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001484 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001485 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001486
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001487 if (UsePerAppMemcg()) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09001488 // Assign system_server to the correct memory cgroup.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001489 // Not all devices mount memcg so check if it is mounted first
Minchan Kim5fa8af22018-06-27 11:32:40 +09001490 // to avoid unnecessarily printing errors and denials in the logs.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08001491 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
1492 ALOGE("couldn't add process %d into system memcg group", pid);
Minchan Kim5fa8af22018-06-27 11:32:40 +09001493 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001494 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001495 }
1496 return pid;
1497}
1498
Chris Wailesaa1c9622019-01-10 16:55:32 -08001499/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001500 * A JNI function that forks an unspecialized app process from the Zygote while
1501 * ensuring proper file descriptor hygiene.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001502 *
1503 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001504 * @param read_pipe_fd The read FD for the USAP reporting pipe. Manually closed by blastlas
Chris Wailesaa1c9622019-01-10 16:55:32 -08001505 * in managed code.
Chris Wailes7e797b62019-02-22 18:29:22 -08001506 * @param write_pipe_fd The write FD for the USAP reporting pipe. Manually closed by the
Chris Wailesaa1c9622019-01-10 16:55:32 -08001507 * zygote in managed code.
1508 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
Chris Wailes7e797b62019-02-22 18:29:22 -08001509 * the FD hygiene code and automatically "closed" in the new USAP.
Chris Wailes3d748212019-05-09 17:11:00 -07001510 * @param is_priority_fork Controls the nice level assigned to the newly created process
Chris Wailesaa1c9622019-01-10 16:55:32 -08001511 * @return
1512 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001513static jint com_android_internal_os_Zygote_nativeForkUsap(JNIEnv* env,
1514 jclass,
1515 jint read_pipe_fd,
1516 jint write_pipe_fd,
Chris Wailes3d748212019-05-09 17:11:00 -07001517 jintArray managed_session_socket_fds,
1518 jboolean is_priority_fork) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001519 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001520 fds_to_ignore(fds_to_close);
1521
1522 std::vector<int> session_socket_fds =
Chris Wailes7e797b62019-02-22 18:29:22 -08001523 ExtractJIntArray(env, "USAP", nullptr, managed_session_socket_fds)
Chris Wailesaa1c9622019-01-10 16:55:32 -08001524 .value_or(std::vector<int>());
1525
Chris Wailes7e797b62019-02-22 18:29:22 -08001526 // The USAP Pool Event FD is created during the initialization of the
1527 // USAP pool and should always be valid here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001528
1529 fds_to_close.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08001530 fds_to_close.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001531 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
1532
1533 fds_to_ignore.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08001534 fds_to_ignore.push_back(gUsapPoolSocketFD);
1535 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001536 fds_to_ignore.push_back(read_pipe_fd);
1537 fds_to_ignore.push_back(write_pipe_fd);
1538 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
1539
Chris Wailes3d748212019-05-09 17:11:00 -07001540 pid_t usap_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore,
1541 is_priority_fork == JNI_TRUE);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001542
Chris Wailes7e797b62019-02-22 18:29:22 -08001543 if (usap_pid != 0) {
1544 ++gUsapPoolCount;
1545 AddUsapTableEntry(usap_pid, read_pipe_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001546 }
1547
Chris Wailes7e797b62019-02-22 18:29:22 -08001548 return usap_pid;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001549}
1550
Robert Sesek54e387d2016-12-02 17:27:50 -05001551static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1552 JNIEnv* env, jclass, jstring path) {
1553 ScopedUtfChars path_native(env, path);
1554 const char* path_cstr = path_native.c_str();
1555 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001556 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001557 }
1558 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1559}
1560
Martijn Coenen86f08a52019-01-03 16:23:01 +01001561static void com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(
1562 JNIEnv* env, jclass, jint uidGidMin, jint uidGidMax) {
Chris Wailes6d482d542019-04-03 13:00:52 -07001563 if (!gIsSecurityEnforced) {
Martijn Coenen86f08a52019-01-03 16:23:01 +01001564 ALOGI("seccomp disabled by setenforce 0");
1565 return;
1566 }
1567
Martijn Coenen86f08a52019-01-03 16:23:01 +01001568 bool installed = install_setuidgid_seccomp_filter(uidGidMin, uidGidMax);
1569 if (!installed) {
1570 RuntimeAbort(env, __LINE__, "Could not install setuid/setgid seccomp filter.");
1571 }
Martijn Coenen86f08a52019-01-03 16:23:01 +01001572}
1573
Chris Wailesaa1c9622019-01-10 16:55:32 -08001574/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001575 * Called from an unspecialized app process to specialize the process for a
1576 * given application.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001577 *
1578 * @param env Managed runtime environment
1579 * @param uid User ID of the new application
1580 * @param gid Group ID of the new application
1581 * @param gids Extra groups that the process belongs to
1582 * @param runtime_flags Flags for changing the behavior of the managed runtime
1583 * @param rlimits Resource limits
1584 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
1585 * @param se_info SELinux policy information
1586 * @param nice_name New name for this process
1587 * @param is_child_zygote If the process is to become a WebViewZygote
1588 * @param instruction_set The instruction set expected/requested by the new application
1589 * @param app_data_dir Path to the application's data directory
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001590 * @param is_top_app If the process is for top (high priority) application
Chris Wailesaa1c9622019-01-10 16:55:32 -08001591 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001592static void com_android_internal_os_Zygote_nativeSpecializeAppProcess(
Chris Wailesaa1c9622019-01-10 16:55:32 -08001593 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
1594 jint runtime_flags, jobjectArray rlimits,
1595 jint mount_external, jstring se_info, jstring nice_name,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001596 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001597 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
1598
1599 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1600 capabilities, capabilities,
1601 mount_external, se_info, nice_name, false,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001602 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
1603 is_top_app == JNI_TRUE);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001604}
1605
1606/**
1607 * A helper method for fetching socket file descriptors that were opened by init from the
1608 * environment.
1609 *
1610 * @param env Managed runtime environment
1611 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
1612 * of the environment variable storing the file descriptors.
1613 */
Chris Wailes6d482d542019-04-03 13:00:52 -07001614static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv* env, jclass,
1615 jboolean is_primary) {
1616 /*
1617 * Obtain file descriptors created by init from the environment.
1618 */
1619
Chris Wailesee1fd452019-04-10 18:05:25 -07001620 gZygoteSocketFD =
1621 android_get_control_socket(is_primary ? "zygote" : "zygote_secondary");
1622 if (gZygoteSocketFD >= 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001623 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
1624 } else {
1625 ALOGE("Unable to fetch Zygote socket file descriptor");
1626 }
1627
Chris Wailesee1fd452019-04-10 18:05:25 -07001628 gUsapPoolSocketFD =
1629 android_get_control_socket(is_primary ? "usap_pool_primary" : "usap_pool_secondary");
1630 if (gUsapPoolSocketFD >= 0) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001631 ALOGV("Zygote:usapPoolSocketFD = %d", gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001632 } else {
Chris Wailes7e797b62019-02-22 18:29:22 -08001633 ALOGE("Unable to fetch USAP pool socket file descriptor");
Chris Wailesaa1c9622019-01-10 16:55:32 -08001634 }
Chris Wailes6d482d542019-04-03 13:00:52 -07001635
1636 /*
1637 * Security Initialization
1638 */
1639
1640 // security_getenforce is not allowed on app process. Initialize and cache
1641 // the value before zygote forks.
1642 gIsSecurityEnforced = security_getenforce();
1643
1644 selinux_android_seapp_context_init();
1645
1646 /*
1647 * Storage Initialization
1648 */
1649
1650 UnmountStorageOnInit(env);
1651
1652 /*
1653 * Performance Initialization
1654 */
1655
1656 if (!SetTaskProfiles(0, {})) {
1657 ZygoteFailure(env, "zygote", nullptr, "Zygote SetTaskProfiles failed");
1658 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001659}
1660
1661/**
1662 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001663 * @return A managed array of raw file descriptors for the read ends of the USAP reporting
Chris Wailesaa1c9622019-01-10 16:55:32 -08001664 * pipes.
1665 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001666static jintArray com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv* env, jclass) {
1667 std::vector<int> usap_fds = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001668
Chris Wailes7e797b62019-02-22 18:29:22 -08001669 jintArray managed_usap_fds = env->NewIntArray(usap_fds.size());
1670 env->SetIntArrayRegion(managed_usap_fds, 0, usap_fds.size(), usap_fds.data());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001671
Chris Wailes7e797b62019-02-22 18:29:22 -08001672 return managed_usap_fds;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001673}
1674
1675/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001676 * A JNI wrapper around RemoveUsapTableEntry.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001677 *
1678 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001679 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001680 * @return True if an entry was invalidated; false otherwise.
1681 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001682static jboolean com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(JNIEnv* env, jclass,
1683 jint usap_pid) {
1684 return RemoveUsapTableEntry(usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001685}
1686
1687/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001688 * Creates the USAP pool event FD if it doesn't exist and returns it. This is used by the
1689 * ZygoteServer poll loop to know when to re-fill the USAP pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001690 *
1691 * @param env Managed runtime environment
1692 * @return A raw event file descriptor used to communicate (from the signal handler) when the
Chris Wailes7e797b62019-02-22 18:29:22 -08001693 * Zygote receives a SIGCHLD for a USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001694 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001695static jint com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv* env, jclass) {
1696 if (gUsapPoolEventFD == -1) {
1697 if ((gUsapPoolEventFD = eventfd(0, 0)) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001698 ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
1699 }
1700 }
1701
Chris Wailes7e797b62019-02-22 18:29:22 -08001702 return gUsapPoolEventFD;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001703}
1704
1705/**
1706 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08001707 * @return The number of USAPs currently in the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001708 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001709static jint com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv* env, jclass) {
1710 return gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001711}
1712
Chris Wailesae937142019-01-24 12:57:33 -08001713/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001714 * Kills all processes currently in the USAP pool and closes their read pipe
1715 * FDs.
Chris Wailesae937142019-01-24 12:57:33 -08001716 *
1717 * @param env Managed runtime environment
Chris Wailesae937142019-01-24 12:57:33 -08001718 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001719static void com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv* env, jclass) {
1720 for (auto& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -08001721 auto entry_storage = entry.GetValues();
1722
1723 if (entry_storage.has_value()) {
Chris Wailesfb329ba2019-06-05 16:07:50 -07001724 kill(entry_storage.value().pid, SIGTERM);
1725
1726 // Clean up the USAP table entry here. This avoids a potential race
1727 // where a newly created USAP might not be able to find a valid table
1728 // entry if signal handler (which would normally do the cleanup) doesn't
1729 // run between now and when the new process is created.
1730
Chris Wailesdb132a32019-02-20 10:49:27 -08001731 close(entry_storage.value().read_pipe_fd);
1732
1733 // Avoid a second atomic load by invalidating instead of clearing.
1734 entry.Invalidate();
Chris Wailes7e797b62019-02-22 18:29:22 -08001735 --gUsapPoolCount;
Chris Wailesae937142019-01-24 12:57:33 -08001736 }
1737 }
1738}
1739
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07001740/**
1741 * @param env Managed runtime environment
1742 * @return True if disable was successful.
1743 */
1744static jboolean com_android_internal_os_Zygote_nativeDisableExecuteOnly(JNIEnv* env, jclass) {
Chris Wailesff8d4e72019-04-10 17:49:24 -07001745 return dl_iterate_phdr(DisableExecuteOnly, nullptr) == 0;
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07001746}
1747
Chris Wailesfb329ba2019-06-05 16:07:50 -07001748static void com_android_internal_os_Zygote_nativeBlockSigTerm(JNIEnv* env, jclass) {
1749 auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
1750 BlockSignal(SIGTERM, fail_fn);
1751}
1752
1753static void com_android_internal_os_Zygote_nativeUnblockSigTerm(JNIEnv* env, jclass) {
1754 auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
1755 UnblockSignal(SIGTERM, fail_fn);
1756}
1757
Chris Wailes3d748212019-05-09 17:11:00 -07001758static void com_android_internal_os_Zygote_nativeBoostUsapPriority(JNIEnv* env, jclass) {
1759 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
1760}
1761
Daniel Micay76f6a862015-09-19 17:31:01 -04001762static const JNINativeMethod gMethods[] = {
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001763 { "nativeForkAndSpecialize",
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001764 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Z)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001765 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1766 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001767 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001768 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1769 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
Christopher Ferris76de39e2017-06-20 16:13:40 -07001770 { "nativePreApplicationInit", "()V",
Martijn Coenen86f08a52019-01-03 16:23:01 +01001771 (void *) com_android_internal_os_Zygote_nativePreApplicationInit },
1772 { "nativeInstallSeccompUidGidFilter", "(II)V",
Chris Wailesaa1c9622019-01-10 16:55:32 -08001773 (void *) com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter },
Chris Wailes3d748212019-05-09 17:11:00 -07001774 { "nativeForkUsap", "(II[IZ)I",
Chris Wailes7e797b62019-02-22 18:29:22 -08001775 (void *) com_android_internal_os_Zygote_nativeForkUsap },
1776 { "nativeSpecializeAppProcess",
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001777 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z)V",
Chris Wailes7e797b62019-02-22 18:29:22 -08001778 (void *) com_android_internal_os_Zygote_nativeSpecializeAppProcess },
Chris Wailes6d482d542019-04-03 13:00:52 -07001779 { "nativeInitNativeState", "(Z)V",
1780 (void *) com_android_internal_os_Zygote_nativeInitNativeState },
Chris Wailes7e797b62019-02-22 18:29:22 -08001781 { "nativeGetUsapPipeFDs", "()[I",
1782 (void *) com_android_internal_os_Zygote_nativeGetUsapPipeFDs },
1783 { "nativeRemoveUsapTableEntry", "(I)Z",
1784 (void *) com_android_internal_os_Zygote_nativeRemoveUsapTableEntry },
1785 { "nativeGetUsapPoolEventFD", "()I",
1786 (void *) com_android_internal_os_Zygote_nativeGetUsapPoolEventFD },
1787 { "nativeGetUsapPoolCount", "()I",
1788 (void *) com_android_internal_os_Zygote_nativeGetUsapPoolCount },
1789 { "nativeEmptyUsapPool", "()V",
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07001790 (void *) com_android_internal_os_Zygote_nativeEmptyUsapPool },
1791 { "nativeDisableExecuteOnly", "()Z",
Chris Wailesfb329ba2019-06-05 16:07:50 -07001792 (void *) com_android_internal_os_Zygote_nativeDisableExecuteOnly },
1793 { "nativeBlockSigTerm", "()V",
1794 (void* ) com_android_internal_os_Zygote_nativeBlockSigTerm },
1795 { "nativeUnblockSigTerm", "()V",
Chris Wailes3d748212019-05-09 17:11:00 -07001796 (void* ) com_android_internal_os_Zygote_nativeUnblockSigTerm },
1797 { "nativeBoostUsapPriority", "()V",
1798 (void* ) com_android_internal_os_Zygote_nativeBoostUsapPriority }
Narayan Kamath973b4662014-03-31 13:41:26 +01001799};
1800
1801int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001802 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001803 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1804 "callPostForkSystemServerHooks",
Mathieu Chartier2cb0a4d2019-11-21 14:30:03 -08001805 "(I)V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001806 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001807 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001808
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07001809 gZygoteInitClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteInitClassName));
1810 gCreateSystemServerClassLoader = GetStaticMethodIDOrDie(env, gZygoteInitClass,
1811 "createSystemServerClassLoader",
1812 "()V");
1813
1814 RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
1815
1816 return JNI_OK;
Narayan Kamath973b4662014-03-31 13:41:26 +01001817}
1818} // namespace android