blob: 92941b8cb22b89e821d449da5820b39f1cc3c85c [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>
Ricky Wai4482ab52019-12-10 19:08:18 +000034#include <sys/types.h>
35#include <dirent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010036
Chris Wailesaa1c9622019-01-10 16:55:32 -080037#include <array>
38#include <atomic>
Chris Wailesaf594fc2018-11-02 11:00:07 -070039#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070040#include <list>
Chris Wailesaf594fc2018-11-02 11:00:07 -070041#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080042#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070043#include <string>
Chris Wailesaa1c9622019-01-10 16:55:32 -080044#include <string_view>
Ricky Wai4482ab52019-12-10 19:08:18 +000045#include <unordered_set>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070046
Josh Gaod7951102018-06-26 16:05:12 -070047#include <android/fdsan.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080048#include <arpa/inet.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070049#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080050#include <grp.h>
51#include <inttypes.h>
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -070052#include <link.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070053#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070054#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010055#include <paths.h>
56#include <signal.h>
Ricky Wai4482ab52019-12-10 19:08:18 +000057#include <stdio.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010058#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070059#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040060#include <sys/cdefs.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080061#include <sys/eventfd.h>
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -070062#include <sys/mman.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070063#include <sys/personality.h>
64#include <sys/prctl.h>
65#include <sys/resource.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080066#include <sys/socket.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070067#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070068#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070069#include <sys/types.h>
Jing Jie29afc92019-10-29 18:14:49 -070070#include <sys/un.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070071#include <sys/utsname.h>
72#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080073#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070074
Chris Wailesaa1c9622019-01-10 16:55:32 -080075#include <android-base/logging.h>
Minchan Kim5fa8af22018-06-27 11:32:40 +090076#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080077#include <android-base/file.h>
78#include <android-base/stringprintf.h>
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -070079#include <android-base/strings.h>
Chris Wailesaa1c9622019-01-10 16:55:32 -080080#include <android-base/unique_fd.h>
Christopher Ferris8269f3a32019-09-11 19:08:52 -070081#include <bionic/malloc.h>
Nick Desaulniersa9940c22019-12-11 15:33:39 -080082#include <bionic/page.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070083#include <cutils/fs.h>
84#include <cutils/multiuser.h>
Chris Wailesee1fd452019-04-10 18:05:25 -070085#include <cutils/sockets.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070086#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070087#include <utils/String8.h>
Jeff Sharkey853e53e2019-03-18 14:35:08 -060088#include <utils/Trace.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070089#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080090#include <seccomp_policy.h>
Howard Ro27330412018-10-02 12:08:28 -070091#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070092#include <processgroup/processgroup.h>
Suren Baghdasaryane4433262019-01-04 12:16:57 -080093#include <processgroup/sched_policy.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070094
Andreas Gampeed6b9df2014-11-20 22:02:20 -080095#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070096#include <nativehelper/JNIHelp.h>
97#include <nativehelper/ScopedLocalRef.h>
98#include <nativehelper/ScopedPrimitiveArray.h>
99#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -0500100#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +0100101
jgu212eacd062014-09-10 06:55:07 -0400102#include "nativebridge/native_bridge.h"
103
Narayan Kamath973b4662014-03-31 13:41:26 +0100104namespace {
105
Chris Wailesaa1c9622019-01-10 16:55:32 -0800106// TODO (chriswailes): Add a function to initialize native Zygote data.
107// TODO (chriswailes): Fix mixed indentation style (2 and 4 spaces).
108
Chris Wailesaf594fc2018-11-02 11:00:07 -0700109using namespace std::placeholders;
110
Narayan Kamath973b4662014-03-31 13:41:26 +0100111using android::String8;
Sudheer Shanka663b1042018-07-30 17:34:21 -0700112using android::base::StringAppendF;
Carmen Jacksondd401252017-02-23 15:21:10 -0800113using android::base::StringPrintf;
114using android::base::WriteStringToFile;
Minchan Kim5fa8af22018-06-27 11:32:40 +0900115using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +0100116
Andreas Gamped5758f62018-03-12 12:08:55 -0700117#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
118 append(StringPrintf(__VA_ARGS__))
119
Chris Wailesaa1c9622019-01-10 16:55:32 -0800120// This type is duplicated in fd_utils.h
121typedef const std::function<void(std::string)>& fail_fn_t;
122
Narayan Kamath973b4662014-03-31 13:41:26 +0100123static pid_t gSystemServerPid = 0;
124
Zima11d9102019-08-15 16:50:23 +0100125static constexpr const char* kPropFuse = "persist.sys.fuse";
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700126static constexpr const char* kZygoteClassName = "com/android/internal/os/Zygote";
Zima11d9102019-08-15 16:50:23 +0100127
Narayan Kamath973b4662014-03-31 13:41:26 +0100128static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +0100129static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +0100130static jmethodID gCallPostForkChildHooks;
131
Andreas Gampe76b4b2c2019-03-15 11:56:48 -0700132static constexpr const char* kZygoteInitClassName = "com/android/internal/os/ZygoteInit";
133static jclass gZygoteInitClass;
134static jmethodID gCreateSystemServerClassLoader;
135
Chris Wailes6d482d542019-04-03 13:00:52 -0700136static bool gIsSecurityEnforced = true;
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800137
Chris Wailesaa1c9622019-01-10 16:55:32 -0800138/**
139 * The maximum number of characters (not including a null terminator) that a
140 * process name may contain.
141 */
142static constexpr size_t MAX_NAME_LENGTH = 15;
143
144/**
Chris Wailesaa1c9622019-01-10 16:55:32 -0800145 * The file descriptor for the Zygote socket opened by init.
146 */
147
148static int gZygoteSocketFD = -1;
149
150/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800151 * The file descriptor for the unspecialized app process (USAP) pool socket opened by init.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800152 */
153
Chris Wailes7e797b62019-02-22 18:29:22 -0800154static int gUsapPoolSocketFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800155
156/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800157 * The number of USAPs currently in this Zygote's pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800158 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800159static std::atomic_uint32_t gUsapPoolCount = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800160
161/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800162 * Event file descriptor used to communicate reaped USAPs to the
Chris Wailesaa1c9622019-01-10 16:55:32 -0800163 * ZygoteServer.
164 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800165static int gUsapPoolEventFD = -1;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800166
Jing Jie29afc92019-10-29 18:14:49 -0700167/**
168 * The socket file descriptor used to send notifications to the
169 * system_server.
170 */
171static int gSystemServerSocketFd = -1;
172
Ricky Wai4482ab52019-12-10 19:08:18 +0000173static constexpr int DEFAULT_DATA_DIR_PERMISSION = 0751;
174
175/**
176 * Property to control if app data isolation is enabled.
177 */
178static const std::string ANDROID_APP_DATA_ISOLATION_ENABLED_PROPERTY =
179 "persist.zygote.app_data_isolation";
180
181static constexpr const uint64_t UPPER_HALF_WORD_MASK = 0xFFFF'FFFF'0000'0000;
182static constexpr const uint64_t LOWER_HALF_WORD_MASK = 0x0000'0000'FFFF'FFFF;
183
Ricky Waiba4325f2019-12-02 16:32:58 +0000184static constexpr const char* kCurProfileDirPath = "/data/misc/profiles/cur";
185
Chris Wailesaa1c9622019-01-10 16:55:32 -0800186/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800187 * The maximum value that the gUSAPPoolSizeMax variable may take. This value
188 * is a mirror of ZygoteServer.USAP_POOL_SIZE_MAX_LIMIT
Chris Wailesaa1c9622019-01-10 16:55:32 -0800189 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800190static constexpr int USAP_POOL_SIZE_MAX_LIMIT = 100;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800191
Chris Wailes3d748212019-05-09 17:11:00 -0700192/** The numeric value for the maximum priority a process may possess. */
193static constexpr int PROCESS_PRIORITY_MAX = -20;
194
195/** The numeric value for the minimum priority a process may possess. */
196static constexpr int PROCESS_PRIORITY_MIN = 19;
197
198/** The numeric value for the normal priority a process should have. */
199static constexpr int PROCESS_PRIORITY_DEFAULT = 0;
200
Chris Wailesaa1c9622019-01-10 16:55:32 -0800201/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800202 * A helper class containing accounting information for USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800203 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800204class UsapTableEntry {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800205 public:
206 struct EntryStorage {
207 int32_t pid;
208 int32_t read_pipe_fd;
209
210 bool operator!=(const EntryStorage& other) {
211 return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
212 }
213 };
214
215 private:
216 static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
217
218 std::atomic<EntryStorage> mStorage;
219 static_assert(decltype(mStorage)::is_always_lock_free);
220
221 public:
Chris Wailes7e797b62019-02-22 18:29:22 -0800222 constexpr UsapTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
Chris Wailesaa1c9622019-01-10 16:55:32 -0800223
224 /**
225 * If the provided PID matches the one stored in this entry, the entry will
226 * be invalidated and the associated file descriptor will be closed. If the
227 * PIDs don't match nothing will happen.
228 *
229 * @param pid The ID of the process who's entry we want to clear.
Chris Wailesfb329ba2019-06-05 16:07:50 -0700230 * @return True if the entry was cleared by this call; false otherwise
Chris Wailesaa1c9622019-01-10 16:55:32 -0800231 */
232 bool ClearForPID(int32_t pid) {
233 EntryStorage storage = mStorage.load();
234
235 if (storage.pid == pid) {
236 /*
237 * There are three possible outcomes from this compare-and-exchange:
238 * 1) It succeeds, in which case we close the FD
239 * 2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
240 * the entry has already been cleared.
241 * 3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
242 * case the entry has already been cleared and re-used.
243 *
Chris Wailesfb329ba2019-06-05 16:07:50 -0700244 * In all three cases the goal of the caller has been met, but only in
245 * the first case do we need to decrement the pool count.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800246 */
247 if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
248 close(storage.read_pipe_fd);
Chris Wailesfb329ba2019-06-05 16:07:50 -0700249 return true;
250 } else {
251 return false;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800252 }
253
Chris Wailesaa1c9622019-01-10 16:55:32 -0800254 } else {
255 return false;
256 }
257 }
258
Chris Wailesae937142019-01-24 12:57:33 -0800259 void Clear() {
Chris Wailesdb132a32019-02-20 10:49:27 -0800260 EntryStorage storage = mStorage.load();
261
262 if (storage != INVALID_ENTRY_VALUE) {
263 close(storage.read_pipe_fd);
264 mStorage.store(INVALID_ENTRY_VALUE);
265 }
266 }
267
268 void Invalidate() {
Chris Wailesae937142019-01-24 12:57:33 -0800269 mStorage.store(INVALID_ENTRY_VALUE);
270 }
271
Chris Wailesaa1c9622019-01-10 16:55:32 -0800272 /**
273 * @return A copy of the data stored in this entry.
274 */
275 std::optional<EntryStorage> GetValues() {
276 EntryStorage storage = mStorage.load();
277
278 if (storage != INVALID_ENTRY_VALUE) {
279 return storage;
280 } else {
281 return std::nullopt;
282 }
283 }
284
285 /**
286 * Sets the entry to the given values if it is currently invalid.
287 *
288 * @param pid The process ID for the new entry.
Chris Wailes7e797b62019-02-22 18:29:22 -0800289 * @param read_pipe_fd The read end of the USAP control pipe for this
Chris Wailesaa1c9622019-01-10 16:55:32 -0800290 * process.
291 * @return True if the entry was set; false otherwise.
292 */
293 bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
294 EntryStorage new_value_storage;
295
296 new_value_storage.pid = pid;
297 new_value_storage.read_pipe_fd = read_pipe_fd;
298
299 EntryStorage expected = INVALID_ENTRY_VALUE;
300
301 return mStorage.compare_exchange_strong(expected, new_value_storage);
302 }
303};
304
305/**
Chris Wailes7e797b62019-02-22 18:29:22 -0800306 * A table containing information about the USAPs currently in the pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800307 *
308 * Multiple threads may be attempting to modify the table, either from the
309 * signal handler or from the ZygoteServer poll loop. Atomic loads/stores in
Chris Wailes7e797b62019-02-22 18:29:22 -0800310 * the USAPTableEntry class prevent data races during these concurrent
Chris Wailesaa1c9622019-01-10 16:55:32 -0800311 * operations.
312 */
Chris Wailes7e797b62019-02-22 18:29:22 -0800313static std::array<UsapTableEntry, USAP_POOL_SIZE_MAX_LIMIT> gUsapTable;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800314
315/**
316 * The list of open zygote file descriptors.
317 */
318static FileDescriptorTable* gOpenFdTable = nullptr;
319
Narayan Kamath973b4662014-03-31 13:41:26 +0100320// Must match values in com.android.internal.os.Zygote.
Sudheer Shankac31097d2019-06-09 23:26:41 -0700321// The order of entries here must be kept in sync with ExternalStorageViews array values.
Narayan Kamath973b4662014-03-31 13:41:26 +0100322enum MountExternalKind {
323 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700324 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700325 MOUNT_EXTERNAL_READ = 2,
326 MOUNT_EXTERNAL_WRITE = 3,
Sudheer Shanka0b6da532019-01-09 12:06:51 -0800327 MOUNT_EXTERNAL_LEGACY = 4,
328 MOUNT_EXTERNAL_INSTALLER = 5,
329 MOUNT_EXTERNAL_FULL = 6,
Zim74a9bba2019-09-03 20:49:13 +0100330 MOUNT_EXTERNAL_PASS_THROUGH = 7,
Martijn Coenen496ac002020-01-08 14:55:53 +0100331 MOUNT_EXTERNAL_ANDROID_WRITABLE = 8,
332 MOUNT_EXTERNAL_COUNT = 9
Sudheer Shankac31097d2019-06-09 23:26:41 -0700333};
334
335// The order of entries here must be kept in sync with MountExternalKind enum values.
336static const std::array<const std::string, MOUNT_EXTERNAL_COUNT> ExternalStorageViews = {
337 "", // MOUNT_EXTERNAL_NONE
338 "/mnt/runtime/default", // MOUNT_EXTERNAL_DEFAULT
339 "/mnt/runtime/read", // MOUNT_EXTERNAL_READ
340 "/mnt/runtime/write", // MOUNT_EXTERNAL_WRITE
341 "/mnt/runtime/write", // MOUNT_EXTERNAL_LEGACY
342 "/mnt/runtime/write", // MOUNT_EXTERNAL_INSTALLER
343 "/mnt/runtime/full", // MOUNT_EXTERNAL_FULL
Martijn Coenen496ac002020-01-08 14:55:53 +0100344 "/mnt/runtime/full", // MOUNT_EXTERNAL_PASS_THROUGH (only used w/ FUSE)
345 "/mnt/runtime/full", // MOUNT_EXTERNAL_ANDROID_WRITABLE (only used w/ FUSE)
Narayan Kamath973b4662014-03-31 13:41:26 +0100346};
347
Orion Hodson8d005a62018-12-05 12:28:53 +0000348// Must match values in com.android.internal.os.Zygote.
349enum RuntimeFlags : uint32_t {
350 DEBUG_ENABLE_JDWP = 1,
Yabin Cui4d8546d2019-01-29 16:29:20 -0800351 PROFILE_FROM_SHELL = 1 << 15,
Orion Hodson8d005a62018-12-05 12:28:53 +0000352};
353
Jing Jie29afc92019-10-29 18:14:49 -0700354enum UnsolicitedZygoteMessageTypes : uint32_t {
355 UNSOLICITED_ZYGOTE_MESSAGE_TYPE_RESERVED = 0,
356 UNSOLICITED_ZYGOTE_MESSAGE_TYPE_SIGCHLD = 1,
357};
358
359struct UnsolicitedZygoteMessageSigChld {
360 struct {
361 UnsolicitedZygoteMessageTypes type;
362 } header;
363 struct {
364 pid_t pid;
365 uid_t uid;
366 int status;
367 } payload;
368};
369
370// Keep sync with services/core/java/com/android/server/am/ProcessList.java
371static constexpr struct sockaddr_un kSystemServerSockAddr =
372 {.sun_family = AF_LOCAL, .sun_path = "/data/system/unsolzygotesocket"};
373
Chris Wailesaa1c9622019-01-10 16:55:32 -0800374// Forward declaration so we don't have to move the signal handler.
Chris Wailes7e797b62019-02-22 18:29:22 -0800375static bool RemoveUsapTableEntry(pid_t usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -0800376
Andreas Gampeb053cce2015-11-17 16:38:59 -0800377static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
378 std::ostringstream oss;
379 oss << __FILE__ << ":" << line << ": " << msg;
380 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100381}
382
Jing Jie29afc92019-10-29 18:14:49 -0700383// Create the socket which is going to be used to send unsolicited message
384// to system_server, the socket will be closed post forking a child process.
385// It's expected to be called at each zygote's initialization.
386static void initUnsolSocketToSystemServer() {
387 gSystemServerSocketFd = socket(AF_LOCAL, SOCK_DGRAM | SOCK_NONBLOCK, 0);
388 if (gSystemServerSocketFd >= 0) {
389 ALOGV("Zygote:systemServerSocketFD = %d", gSystemServerSocketFd);
390 } else {
391 ALOGE("Unable to create socket file descriptor to connect to system_server");
392 }
393}
394
395static void sendSigChildStatus(const pid_t pid, const uid_t uid, const int status) {
396 int socketFd = gSystemServerSocketFd;
397 if (socketFd >= 0) {
398 // fill the message buffer
399 struct UnsolicitedZygoteMessageSigChld data =
400 {.header = {.type = UNSOLICITED_ZYGOTE_MESSAGE_TYPE_SIGCHLD},
401 .payload = {.pid = pid, .uid = uid, .status = status}};
402 if (TEMP_FAILURE_RETRY(
403 sendto(socketFd, &data, sizeof(data), 0,
404 reinterpret_cast<const struct sockaddr*>(&kSystemServerSockAddr),
405 sizeof(kSystemServerSockAddr))) == -1) {
406 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
407 "Zygote failed to write to system_server FD: %s",
408 strerror(errno));
409 }
410 }
411}
412
Narayan Kamath973b4662014-03-31 13:41:26 +0100413// This signal handler is for zygote mode, since the zygote must reap its children
Jing Jie29afc92019-10-29 18:14:49 -0700414static void SigChldHandler(int /*signal_number*/, siginfo_t* info, void* /*ucontext*/) {
415 pid_t pid;
416 int status;
417 int64_t usaps_removed = 0;
Narayan Kamath973b4662014-03-31 13:41:26 +0100418
Jing Jie29afc92019-10-29 18:14:49 -0700419 // It's necessary to save and restore the errno during this function.
420 // Since errno is stored per thread, changing it here modifies the errno
421 // on the thread on which this signal handler executes. If a signal occurs
422 // between a call and an errno check, it's possible to get the errno set
423 // here.
424 // See b/23572286 for extra information.
425 int saved_errno = errno;
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700426
Jing Jie29afc92019-10-29 18:14:49 -0700427 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
428 // Notify system_server that we received a SIGCHLD
429 sendSigChildStatus(pid, info->si_uid, status);
430 // Log process-death status that we care about.
431 if (WIFEXITED(status)) {
432 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG, "Process %d exited cleanly (%d)", pid,
433 WEXITSTATUS(status));
Chris Wailesfb329ba2019-06-05 16:07:50 -0700434
Jing Jie29afc92019-10-29 18:14:49 -0700435 // Check to see if the PID is in the USAP pool and remove it if it is.
436 if (RemoveUsapTableEntry(pid)) {
437 ++usaps_removed;
438 }
439 } else if (WIFSIGNALED(status)) {
440 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
441 "Process %d exited due to signal %d (%s)%s", pid,
442 WTERMSIG(status), strsignal(WTERMSIG(status)),
443 WCOREDUMP(status) ? "; core dumped" : "");
Chris Wailesfb329ba2019-06-05 16:07:50 -0700444
Jing Jie29afc92019-10-29 18:14:49 -0700445 // If the process exited due to a signal other than SIGTERM, check to see
446 // if the PID is in the USAP pool and remove it if it is. If the process
447 // was closed by the Zygote using SIGTERM then the USAP pool entry will
448 // have already been removed (see nativeEmptyUsapPool()).
449 if (WTERMSIG(status) != SIGTERM && RemoveUsapTableEntry(pid)) {
450 ++usaps_removed;
451 }
452 }
453
454 // If the just-crashed process is the system_server, bring down zygote
455 // so that it is restarted by init and system server will be restarted
456 // from there.
457 if (pid == gSystemServerPid) {
458 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
459 "Exit zygote because system server (pid %d) has terminated", pid);
460 kill(getpid(), SIGKILL);
461 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100462 }
463
Jing Jie29afc92019-10-29 18:14:49 -0700464 // Note that we shouldn't consider ECHILD an error because
465 // the secondary zygote might have no children left to wait for.
466 if (pid < 0 && errno != ECHILD) {
467 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Zygote SIGCHLD error in waitpid: %s",
468 strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100469 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100470
Jing Jie29afc92019-10-29 18:14:49 -0700471 if (usaps_removed > 0) {
472 if (TEMP_FAILURE_RETRY(write(gUsapPoolEventFD, &usaps_removed, sizeof(usaps_removed))) ==
473 -1) {
474 // If this write fails something went terribly wrong. We will now kill
475 // the zygote and let the system bring it back up.
476 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
477 "Zygote failed to write to USAP pool event FD: %s",
478 strerror(errno));
479 kill(getpid(), SIGKILL);
480 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800481 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800482
Jing Jie29afc92019-10-29 18:14:49 -0700483 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100484}
485
yuanhao435e84b2018-01-15 15:37:02 +0800486// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
487// configured very late, because earlier in the runtime we may fork() and
488// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100489// have them be harvested immediately.
490//
yuanhao435e84b2018-01-15 15:37:02 +0800491// Ignore SIGHUP because all processes forked by the zygote are in the same
492// process group as the zygote and we don't want to be notified if we become
493// an orphaned group and have one or more stopped processes. This is not a
494// theoretical concern :
495// - we can become an orphaned group if one of our direct descendants forks
496// and is subsequently killed before its children.
497// - crash_dump routinely STOPs the process it's tracing.
498//
499// See issues b/71965619 and b/25567761 for further details.
500//
Narayan Kamath973b4662014-03-31 13:41:26 +0100501// This ends up being called repeatedly before each fork(), but there's
502// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800503static void SetSignalHandlers() {
Jing Jie29afc92019-10-29 18:14:49 -0700504 struct sigaction sig_chld = {.sa_flags = SA_SIGINFO, .sa_sigaction = SigChldHandler};
Narayan Kamath973b4662014-03-31 13:41:26 +0100505
Jing Jie29afc92019-10-29 18:14:49 -0700506 if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
507 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
508 }
yuanhao435e84b2018-01-15 15:37:02 +0800509
510 struct sigaction sig_hup = {};
511 sig_hup.sa_handler = SIG_IGN;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800512 if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
yuanhao435e84b2018-01-15 15:37:02 +0800513 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
514 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100515}
516
517// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800518static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100519 struct sigaction sa;
520 memset(&sa, 0, sizeof(sa));
521 sa.sa_handler = SIG_DFL;
522
Chris Wailesaa1c9622019-01-10 16:55:32 -0800523 if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700524 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100525 }
526}
527
528// Calls POSIX setgroups() using the int[] object as an argument.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800529// A nullptr argument is tolerated.
530static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) {
531 if (managed_gids == nullptr) {
532 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100533 }
534
Chris Wailesaa1c9622019-01-10 16:55:32 -0800535 ScopedIntArrayRO gids(env, managed_gids);
536 if (gids.get() == nullptr) {
537 fail_fn(CREATE_ERROR("Getting gids int array failed"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100538 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700539
Chris Wailesaa1c9622019-01-10 16:55:32 -0800540 if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
541 fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
542 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100543}
544
545// Sets the resource limits via setrlimit(2) for the values in the
546// two-dimensional array of integers that's passed in. The second dimension
Chris Wailesaa1c9622019-01-10 16:55:32 -0800547// contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
Narayan Kamath973b4662014-03-31 13:41:26 +0100548// treated as an empty array.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800549static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
550 if (managed_rlimits == nullptr) {
551 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100552 }
553
554 rlimit rlim;
555 memset(&rlim, 0, sizeof(rlim));
556
Chris Wailesaa1c9622019-01-10 16:55:32 -0800557 for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
558 ScopedLocalRef<jobject>
559 managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
560 ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
561
562 if (rlimit_handle.size() != 3) {
563 fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100564 }
565
Chris Wailesaa1c9622019-01-10 16:55:32 -0800566 rlim.rlim_cur = rlimit_handle[1];
567 rlim.rlim_max = rlimit_handle[2];
Narayan Kamath973b4662014-03-31 13:41:26 +0100568
Chris Wailesaa1c9622019-01-10 16:55:32 -0800569 if (setrlimit(rlimit_handle[0], &rlim) == -1) {
570 fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
571 rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
Narayan Kamath973b4662014-03-31 13:41:26 +0100572 }
573 }
574}
575
Orion Hodson8d005a62018-12-05 12:28:53 +0000576static void EnableDebugger() {
577 // To let a non-privileged gdbserver attach to this
578 // process, we must set our dumpable flag.
579 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
580 ALOGE("prctl(PR_SET_DUMPABLE) failed");
581 }
582
583 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
584 // is enabled (see kernel/Documentation/security/Yama.txt).
585 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
586 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
587 // case since it's expected behaviour.
588 if (errno != EINVAL) {
589 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
590 }
591 }
592
Orion Hodson2b71ad02018-12-07 16:44:33 +0000593 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
594 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
595 // Set the soft limit on core dump size to 0 without changing the hard limit.
596 rlimit rl;
597 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
598 ALOGE("getrlimit(RLIMIT_CORE) failed");
599 } else {
600 rl.rlim_cur = 0;
601 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
602 ALOGE("setrlimit(RLIMIT_CORE) failed");
603 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000604 }
605 }
606}
607
Christopher Ferris76de39e2017-06-20 16:13:40 -0700608static void PreApplicationInit() {
609 // The child process sets this to indicate it's not the zygote.
Christopher Ferrised364d62019-04-09 16:42:32 -0700610 android_mallopt(M_SET_ZYGOTE_CHILD, nullptr, 0);
Christopher Ferris76de39e2017-06-20 16:13:40 -0700611
612 // Set the jemalloc decay time to 1.
613 mallopt(M_DECAY_TIME, 1);
614}
615
Martijn Coenen86f08a52019-01-03 16:23:01 +0100616static void SetUpSeccompFilter(uid_t uid, bool is_child_zygote) {
Chris Wailes6d482d542019-04-03 13:00:52 -0700617 if (!gIsSecurityEnforced) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800618 ALOGI("seccomp disabled by setenforce 0");
619 return;
620 }
621
622 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700623 if (uid >= AID_APP_START) {
Martijn Coenen86f08a52019-01-03 16:23:01 +0100624 if (is_child_zygote) {
Martijn Coenen6ef16802019-01-18 16:40:01 +0100625 set_app_zygote_seccomp_filter();
Martijn Coenen86f08a52019-01-03 16:23:01 +0100626 } else {
627 set_app_seccomp_filter();
628 }
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800629 } else {
630 set_system_seccomp_filter();
631 }
632}
633
Chris Wailesaa1c9622019-01-10 16:55:32 -0800634static void EnableKeepCapabilities(fail_fn_t fail_fn) {
635 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
636 fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100637 }
638}
639
Chris Wailesaa1c9622019-01-10 16:55:32 -0800640static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
641 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
642 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100643 if (errno == EINVAL) {
644 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
645 "your kernel is compiled with file capabilities support");
646 } else {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800647 fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100648 }
649 }
650 }
651}
652
Chris Wailesaa1c9622019-01-10 16:55:32 -0800653static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
Josh Gao45dab782017-02-01 14:56:09 -0800654 __user_cap_header_struct capheader;
655 memset(&capheader, 0, sizeof(capheader));
656 capheader.version = _LINUX_CAPABILITY_VERSION_3;
657 capheader.pid = 0;
658
659 __user_cap_data_struct capdata[2];
660 if (capget(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800661 fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800662 }
663
664 capdata[0].inheritable = inheritable;
665 capdata[1].inheritable = inheritable >> 32;
666
667 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800668 fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800669 }
670}
671
Chris Wailesaa1c9622019-01-10 16:55:32 -0800672static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
673 fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100674 __user_cap_header_struct capheader;
675 memset(&capheader, 0, sizeof(capheader));
676 capheader.version = _LINUX_CAPABILITY_VERSION_3;
677 capheader.pid = 0;
678
679 __user_cap_data_struct capdata[2];
680 memset(&capdata, 0, sizeof(capdata));
681 capdata[0].effective = effective;
682 capdata[1].effective = effective >> 32;
683 capdata[0].permitted = permitted;
684 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800685 capdata[0].inheritable = inheritable;
686 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100687
688 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800689 fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
690 "failed: %s", permitted, effective, inheritable, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100691 }
692}
693
Riddle Hsu32dbdca2019-05-17 23:10:16 -0600694static void SetSchedulerPolicy(fail_fn_t fail_fn, bool is_top_app) {
695 SchedPolicy policy = is_top_app ? SP_TOP_APP : SP_DEFAULT;
696
697 if (is_top_app && cpusets_enabled()) {
698 errno = -set_cpuset_policy(0, policy);
699 if (errno != 0) {
700 fail_fn(CREATE_ERROR("set_cpuset_policy(0, %d) failed: %s", policy, strerror(errno)));
701 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100702 }
Riddle Hsu32dbdca2019-05-17 23:10:16 -0600703
704 errno = -set_sched_policy(0, policy);
705 if (errno != 0) {
706 fail_fn(CREATE_ERROR("set_sched_policy(0, %d) failed: %s", policy, strerror(errno)));
707 }
708
709 // We are going to lose the permission to set scheduler policy during the specialization, so make
710 // sure that we don't cache the fd of cgroup path that may cause sepolicy violation by writing
711 // value to the cached fd directly when creating new thread.
712 DropTaskProfilesResourceCaching();
Narayan Kamath973b4662014-03-31 13:41:26 +0100713}
714
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700715static int UnmountTree(const char* path) {
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600716 ATRACE_CALL();
717
Sudheer Shanka74584a52019-02-22 13:04:41 -0800718 size_t path_len = strlen(path);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700719
Sudheer Shanka74584a52019-02-22 13:04:41 -0800720 FILE* fp = setmntent("/proc/mounts", "r");
721 if (fp == nullptr) {
722 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
723 return -errno;
724 }
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700725
Sudheer Shanka74584a52019-02-22 13:04:41 -0800726 // Some volumes can be stacked on each other, so force unmount in
727 // reverse order to give us the best chance of success.
728 std::list<std::string> to_unmount;
729 mntent* mentry;
730 while ((mentry = getmntent(fp)) != nullptr) {
731 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
732 to_unmount.push_front(std::string(mentry->mnt_dir));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700733 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800734 }
735 endmntent(fp);
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700736
Sudheer Shanka74584a52019-02-22 13:04:41 -0800737 for (const auto& path : to_unmount) {
738 if (umount2(path.c_str(), MNT_DETACH)) {
739 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700740 }
Sudheer Shanka74584a52019-02-22 13:04:41 -0800741 }
742 return 0;
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700743}
744
Ricky Wai4482ab52019-12-10 19:08:18 +0000745static void PrepareDir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
Sudheer Shankac31097d2019-06-09 23:26:41 -0700746 fail_fn_t fail_fn) {
747 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
748 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s: %s",
749 dir.c_str(), strerror(errno)));
750 }
751}
752
Ricky Wai4482ab52019-12-10 19:08:18 +0000753static void PrepareDirIfNotPresent(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
754 fail_fn_t fail_fn) {
755 struct stat sb;
756 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) != -1) {
757 // Directory exists already
758 return;
759 }
760 PrepareDir(dir, mode, uid, gid, fail_fn);
761}
762
Sudheer Shankac31097d2019-06-09 23:26:41 -0700763static void BindMount(const std::string& source_dir, const std::string& target_dir,
764 fail_fn_t fail_fn) {
765 if (TEMP_FAILURE_RETRY(mount(source_dir.c_str(), target_dir.c_str(), nullptr,
766 MS_BIND | MS_REC, nullptr)) == -1) {
767 fail_fn(CREATE_ERROR("Failed to mount %s to %s: %s",
768 source_dir.c_str(), target_dir.c_str(), strerror(errno)));
769 }
770}
771
Ricky Wai4482ab52019-12-10 19:08:18 +0000772static void MountAppDataTmpFs(const std::string& target_dir,
773 fail_fn_t fail_fn) {
774 if (TEMP_FAILURE_RETRY(mount("tmpfs", target_dir.c_str(), "tmpfs",
775 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
776 fail_fn(CREATE_ERROR("Failed to mount tmpfs to %s: %s",
777 target_dir.c_str(), strerror(errno)));
778 }
779}
780
Narayan Kamath973b4662014-03-31 13:41:26 +0100781// Create a private mount namespace and bind mount appropriate emulated
782// storage for the given user.
Chris Wailesaa1c9622019-01-10 16:55:32 -0800783static void MountEmulatedStorage(uid_t uid, jint mount_mode,
Sudheer Shankae73ae322019-04-29 10:46:26 -0700784 bool force_mount_namespace,
Sudheer Shanka03fd40b2019-02-06 12:39:14 -0800785 fail_fn_t fail_fn) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800786 // See storage config details at http://source.android.com/tech/storage/
Jeff Sharkey853e53e2019-03-18 14:35:08 -0600787 ATRACE_CALL();
Jeff Sharkey9527b222015-06-24 15:24:48 -0700788
Sudheer Shankac31097d2019-06-09 23:26:41 -0700789 if (mount_mode < 0 || mount_mode >= MOUNT_EXTERNAL_COUNT) {
790 fail_fn(CREATE_ERROR("Unknown mount_mode: %d", mount_mode));
791 }
792
793 if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
Sudheer Shanka74584a52019-02-22 13:04:41 -0800794 // Sane default of no storage visible
795 return;
796 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400797
Sudheer Shanka74584a52019-02-22 13:04:41 -0800798 // Create a second private mount namespace for our process
799 if (unshare(CLONE_NEWNS) == -1) {
800 fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
801 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400802
Sudheer Shanka74584a52019-02-22 13:04:41 -0800803 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
804 if (mount_mode == MOUNT_EXTERNAL_NONE) {
805 return;
806 }
Robert Sesek06f39302017-03-20 17:30:05 -0400807
Zima11d9102019-08-15 16:50:23 +0100808 const userid_t user_id = multiuser_get_user_id(uid);
Sudheer Shankac31097d2019-06-09 23:26:41 -0700809 const std::string user_source = StringPrintf("/mnt/user/%d", user_id);
Zim1fc33552020-01-05 03:22:34 +0000810 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
811 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
812 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
813 // These bits should be consistent with what is set in vold in
814 // Utils#MountUserFuse on FUSE volume mount
815 PrepareDir(user_source, 0710, user_id ? AID_ROOT : AID_SHELL,
816 multiuser_get_uid(user_id, AID_EVERYBODY), fail_fn);
Zima11d9102019-08-15 16:50:23 +0100817
Martijn Coenen7d60e162020-01-11 19:45:08 +0100818 bool isFuse = GetBoolProperty(kPropFuse, false);
819
Zima11d9102019-08-15 16:50:23 +0100820 if (isFuse) {
Martijn Coenen496ac002020-01-08 14:55:53 +0100821 if (mount_mode == MOUNT_EXTERNAL_PASS_THROUGH) {
Martijn Coenen7d60e162020-01-11 19:45:08 +0100822 const std::string pass_through_source = StringPrintf("/mnt/pass_through/%d", user_id);
Zim6b06fc52020-01-31 16:11:48 +0000823 PrepareDir(pass_through_source, 0710, AID_ROOT, AID_MEDIA_RW, fail_fn);
Martijn Coenen6a01fae2019-12-13 16:44:32 +0100824 BindMount(pass_through_source, "/storage", fail_fn);
Martijn Coenen7d60e162020-01-11 19:45:08 +0100825 } else if (mount_mode == MOUNT_EXTERNAL_INSTALLER) {
826 const std::string installer_source = StringPrintf("/mnt/installer/%d", user_id);
827 BindMount(installer_source, "/storage", fail_fn);
Martijn Coenen6a01fae2019-12-13 16:44:32 +0100828 } else {
829 BindMount(user_source, "/storage", fail_fn);
830 }
Zima11d9102019-08-15 16:50:23 +0100831 } else {
832 const std::string& storage_source = ExternalStorageViews[mount_mode];
833 BindMount(storage_source, "/storage", fail_fn);
834
835 // Mount user-specific symlink helper into place
836 BindMount(user_source, "/storage/self", fail_fn);
837 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100838}
839
Narayan Kamath973b4662014-03-31 13:41:26 +0100840static bool NeedsNoRandomizeWorkaround() {
841#if !defined(__arm__)
842 return false;
843#else
844 int major;
845 int minor;
846 struct utsname uts;
847 if (uname(&uts) == -1) {
848 return false;
849 }
850
851 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
852 return false;
853 }
854
855 // Kernels before 3.4.* need the workaround.
856 return (major < 3) || ((major == 3) && (minor < 4));
857#endif
858}
Narayan Kamath973b4662014-03-31 13:41:26 +0100859
860// Utility to close down the Zygote socket file descriptors while
861// the child is still running as root with Zygote's privileges. Each
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800862// descriptor (if any) is closed via dup3(), replacing it with a valid
Narayan Kamath973b4662014-03-31 13:41:26 +0100863// (open) descriptor to /dev/null.
864
Chris Wailesaa1c9622019-01-10 16:55:32 -0800865static void DetachDescriptors(JNIEnv* env,
866 const std::vector<int>& fds_to_close,
867 fail_fn_t fail_fn) {
868
869 if (fds_to_close.size() > 0) {
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800870 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800871 if (devnull_fd == -1) {
872 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100873 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800874
875 for (int fd : fds_to_close) {
876 ALOGV("Switching descriptor %d to /dev/null", fd);
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800877 if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
878 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800879 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100880 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100881 }
882}
883
Chris Wailesaa1c9622019-01-10 16:55:32 -0800884void SetThreadName(const std::string& thread_name) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100885 bool hasAt = false;
886 bool hasDot = false;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800887
888 for (const char str_el : thread_name) {
889 if (str_el == '.') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100890 hasDot = true;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800891 } else if (str_el == '@') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100892 hasAt = true;
893 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100894 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800895
896 const char* name_start_ptr = thread_name.c_str();
897 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
898 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
Narayan Kamath973b4662014-03-31 13:41:26 +0100899 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800900
Narayan Kamath973b4662014-03-31 13:41:26 +0100901 // pthread_setname_np fails rather than truncating long strings.
902 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
Chris Wailesaa1c9622019-01-10 16:55:32 -0800903 strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
Narayan Kamath973b4662014-03-31 13:41:26 +0100904 errno = pthread_setname_np(pthread_self(), buf);
905 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700906 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100907 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800908 // Update base::logging default tag.
909 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100910}
911
Chris Wailesaa1c9622019-01-10 16:55:32 -0800912/**
913 * A failure function used to report fatal errors to the managed runtime. This
914 * function is often curried with the process name information and then passed
915 * to called functions.
916 *
917 * @param env Managed runtime environment
918 * @param process_name A native representation of the process name
919 * @param managed_process_name A managed representation of the process name
920 * @param msg The error message to be reported
921 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700922[[noreturn]]
923static void ZygoteFailure(JNIEnv* env,
924 const char* process_name,
925 jstring managed_process_name,
926 const std::string& msg) {
927 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
928 if (managed_process_name != nullptr) {
929 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
930 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
931 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -0700932 }
933 }
934
Chris Wailesaf594fc2018-11-02 11:00:07 -0700935 const std::string& error_msg =
936 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700937
Chris Wailesaf594fc2018-11-02 11:00:07 -0700938 env->FatalError(error_msg.c_str());
939 __builtin_unreachable();
940}
David Sehrde8d0bd2018-06-22 10:45:36 -0700941
Chris Wailesaa1c9622019-01-10 16:55:32 -0800942/**
943 * A helper method for converting managed strings to native strings. A fatal
944 * error is generated if a problem is encountered in extracting a non-null
945 * string.
946 *
947 * @param env Managed runtime environment
948 * @param process_name A native representation of the process name
949 * @param managed_process_name A managed representation of the process name
950 * @param managed_string The managed string to extract
951 *
952 * @return An empty option if the managed string is null. A optional-wrapped
953 * string otherwise.
954 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700955static std::optional<std::string> ExtractJString(JNIEnv* env,
956 const char* process_name,
957 jstring managed_process_name,
958 jstring managed_string) {
959 if (managed_string == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800960 return std::nullopt;
Chris Wailesaf594fc2018-11-02 11:00:07 -0700961 } else {
962 ScopedUtfChars scoped_string_chars(env, managed_string);
963
964 if (scoped_string_chars.c_str() != nullptr) {
965 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700966 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -0700967 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700968 }
969 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700970}
971
Chris Wailesaa1c9622019-01-10 16:55:32 -0800972/**
973 * A helper method for converting managed string arrays to native vectors. A
974 * fatal error is generated if a problem is encountered in extracting a non-null array.
975 *
976 * @param env Managed runtime environment
977 * @param process_name A native representation of the process name
978 * @param managed_process_name A managed representation of the process name
979 * @param managed_array The managed integer array to extract
980 *
981 * @return An empty option if the managed array is null. A optional-wrapped
982 * vector otherwise.
983 */
984static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
985 const char* process_name,
986 jstring managed_process_name,
987 jintArray managed_array) {
988 if (managed_array == nullptr) {
989 return std::nullopt;
990 } else {
991 ScopedIntArrayRO managed_array_handle(env, managed_array);
Narayan Kamath973b4662014-03-31 13:41:26 +0100992
Chris Wailesaa1c9622019-01-10 16:55:32 -0800993 if (managed_array_handle.get() != nullptr) {
994 std::vector<int> native_array;
995 native_array.reserve(managed_array_handle.size());
996
997 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
998 native_array.push_back(managed_array_handle[array_index]);
999 }
1000
1001 return std::move(native_array);
1002
1003 } else {
1004 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
1005 }
1006 }
1007}
1008
1009/**
Chris Wailesaa1c9622019-01-10 16:55:32 -08001010 * A utility function for blocking signals.
1011 *
1012 * @param signum Signal number to block
1013 * @param fail_fn Fatal error reporting function
1014 *
1015 * @see ZygoteFailure
1016 */
1017static void BlockSignal(int signum, fail_fn_t fail_fn) {
1018 sigset_t sigs;
1019 sigemptyset(&sigs);
1020 sigaddset(&sigs, signum);
1021
1022 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
1023 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
1024 }
1025}
1026
1027
1028/**
1029 * A utility function for unblocking signals.
1030 *
1031 * @param signum Signal number to unblock
1032 * @param fail_fn Fatal error reporting function
1033 *
1034 * @see ZygoteFailure
1035 */
1036static void UnblockSignal(int signum, fail_fn_t fail_fn) {
1037 sigset_t sigs;
1038 sigemptyset(&sigs);
1039 sigaddset(&sigs, signum);
1040
1041 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
1042 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
1043 }
1044}
1045
Chris Wailes7e797b62019-02-22 18:29:22 -08001046static void ClearUsapTable() {
1047 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -08001048 entry.Clear();
1049 }
1050
Chris Wailes7e797b62019-02-22 18:29:22 -08001051 gUsapPoolCount = 0;
Chris Wailesae937142019-01-24 12:57:33 -08001052}
1053
Chris Wailesaa1c9622019-01-10 16:55:32 -08001054// Utility routine to fork a process from the zygote.
1055static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
1056 const std::vector<int>& fds_to_close,
Chris Wailes3d748212019-05-09 17:11:00 -07001057 const std::vector<int>& fds_to_ignore,
1058 bool is_priority_fork) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001059 SetSignalHandlers();
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001060
Chris Wailesaf594fc2018-11-02 11:00:07 -07001061 // Curry a failure function.
1062 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
1063 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -07001064
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001065 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
1066 // log, which would result in the logging FDs we close being reopened.
1067 // This would cause failures because the FDs are not whitelisted.
1068 //
1069 // Note that the zygote process is single threaded at this point.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001070 BlockSignal(SIGCHLD, fail_fn);
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001071
Narayan Kamath3764a262016-08-30 15:36:19 +01001072 // Close any logging related FDs before we start evaluating the list of
1073 // file descriptors.
1074 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -07001075 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +01001076
Chris Wailesaf594fc2018-11-02 11:00:07 -07001077 // If this is the first fork for this zygote, create the open FD table. If
1078 // it isn't, we just need to check whether the list of open files has changed
1079 // (and it shouldn't in the normal case).
Chris Wailesaf594fc2018-11-02 11:00:07 -07001080 if (gOpenFdTable == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001081 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
1082 } else {
1083 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001084 }
1085
Josh Gaod7951102018-06-26 16:05:12 -07001086 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
1087
Chris Wailes7699d612020-01-28 17:26:56 -08001088 // Purge unused native memory in an attempt to reduce the amount of false
1089 // sharing with the child process. By reducing the size of the libc_malloc
1090 // region shared with the child process we reduce the number of pages that
1091 // transition to the private-dirty state when malloc adjusts the meta-data
1092 // on each of the pages it is managing after the fork.
1093 mallopt(M_PURGE, 0);
1094
Narayan Kamath973b4662014-03-31 13:41:26 +01001095 pid_t pid = fork();
1096
1097 if (pid == 0) {
Chris Wailes3d748212019-05-09 17:11:00 -07001098 if (is_priority_fork) {
1099 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
1100 } else {
1101 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MIN);
1102 }
1103
David Sehrde8d0bd2018-06-22 10:45:36 -07001104 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -07001105 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -07001106
Narayan Kamath973b4662014-03-31 13:41:26 +01001107 // Clean up any descriptors which must be closed immediately
Chris Wailesaa1c9622019-01-10 16:55:32 -08001108 DetachDescriptors(env, fds_to_close, fail_fn);
Narayan Kamath973b4662014-03-31 13:41:26 +01001109
Chris Wailes7e797b62019-02-22 18:29:22 -08001110 // Invalidate the entries in the USAP table.
1111 ClearUsapTable();
Chris Wailesae937142019-01-24 12:57:33 -08001112
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001113 // Re-open all remaining open file descriptors so that they aren't shared
1114 // with the zygote across a fork.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001115 gOpenFdTable->ReopenOrDetach(fail_fn);
Josh Gaod7951102018-06-26 16:05:12 -07001116
1117 // Turn fdsan back on.
1118 android_fdsan_set_error_level(fdsan_error_level);
Jing Jie29afc92019-10-29 18:14:49 -07001119
1120 // Reset the fd to the unsolicited zygote socket
1121 gSystemServerSocketFd = -1;
Martin Stjernholma9bd8c32019-02-23 02:35:07 +00001122 } else {
1123 ALOGD("Forked child process %d", pid);
David Sehrde8d0bd2018-06-22 10:45:36 -07001124 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001125
David Sehrde8d0bd2018-06-22 10:45:36 -07001126 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001127 UnblockSignal(SIGCHLD, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001128
Narayan Kamath973b4662014-03-31 13:41:26 +01001129 return pid;
1130}
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001131
Ricky Wai4482ab52019-12-10 19:08:18 +00001132// Create an app data directory over tmpfs overlayed CE / DE storage, and bind mount it
1133// from the actual app data directory in data mirror.
1134static void createAndMountAppData(std::string_view package_name,
1135 std::string_view mirror_pkg_dir_name, std::string_view mirror_data_path,
1136 std::string_view actual_data_path, fail_fn_t fail_fn) {
1137
1138 char mirrorAppDataPath[PATH_MAX];
1139 char actualAppDataPath[PATH_MAX];
1140 snprintf(mirrorAppDataPath, PATH_MAX, "%s/%s", mirror_data_path.data(),
1141 mirror_pkg_dir_name.data());
1142 snprintf(actualAppDataPath, PATH_MAX, "%s/%s", actual_data_path.data(), package_name.data());
1143
1144 PrepareDir(actualAppDataPath, 0700, AID_ROOT, AID_ROOT, fail_fn);
1145
1146 // Bind mount from original app data directory in mirror.
1147 BindMount(mirrorAppDataPath, actualAppDataPath, fail_fn);
1148}
1149
1150// Get the directory name stored in /data/data. If device is unlocked it should be the same as
1151// package name, otherwise it will be an encrypted name but with same inode number.
1152static std::string getAppDataDirName(std::string_view parent_path, std::string_view package_name,
1153 long long ce_data_inode, fail_fn_t fail_fn) {
1154 // Check if directory exists
1155 char tmpPath[PATH_MAX];
1156 snprintf(tmpPath, PATH_MAX, "%s/%s", parent_path.data(), package_name.data());
1157 struct stat s;
1158 int err = stat(tmpPath, &s);
1159 if (err == 0) {
1160 // Directory exists, so return the directory name
1161 return package_name.data();
1162 } else {
1163 if (errno != ENOENT) {
1164 fail_fn(CREATE_ERROR("Unexpected error in getAppDataDirName: %s", strerror(errno)));
1165 return nullptr;
1166 }
Ricky Waiffedc572020-01-20 17:07:58 +00001167 {
1168 // Directory doesn't exist, try to search the name from inode
1169 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(parent_path.data()), closedir);
1170 if (dir == nullptr) {
1171 fail_fn(CREATE_ERROR("Failed to opendir %s", parent_path.data()));
1172 }
1173 struct dirent* ent;
1174 while ((ent = readdir(dir.get()))) {
1175 if (ent->d_ino == ce_data_inode) {
1176 return ent->d_name;
1177 }
Ricky Wai4482ab52019-12-10 19:08:18 +00001178 }
1179 }
Ricky Wai4482ab52019-12-10 19:08:18 +00001180
1181 // Fallback due to b/145989852, ce_data_inode stored in package manager may be corrupted
1182 // if ino_t is 32 bits.
1183 ino_t fixed_ce_data_inode = 0;
1184 if ((ce_data_inode & UPPER_HALF_WORD_MASK) == UPPER_HALF_WORD_MASK) {
1185 fixed_ce_data_inode = ce_data_inode & LOWER_HALF_WORD_MASK;
1186 } else if ((ce_data_inode & LOWER_HALF_WORD_MASK) == LOWER_HALF_WORD_MASK) {
1187 fixed_ce_data_inode = ((ce_data_inode >> 32) & LOWER_HALF_WORD_MASK);
1188 }
1189 if (fixed_ce_data_inode != 0) {
Ricky Waiffedc572020-01-20 17:07:58 +00001190 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(parent_path.data()), closedir);
Ricky Wai4482ab52019-12-10 19:08:18 +00001191 if (dir == nullptr) {
1192 fail_fn(CREATE_ERROR("Failed to opendir %s", parent_path.data()));
1193 }
Ricky Waiffedc572020-01-20 17:07:58 +00001194 struct dirent* ent;
1195 while ((ent = readdir(dir.get()))) {
Ricky Wai4482ab52019-12-10 19:08:18 +00001196 if (ent->d_ino == fixed_ce_data_inode) {
1197 long long d_ino = ent->d_ino;
1198 ALOGW("Fallback success inode %lld -> %lld", ce_data_inode, d_ino);
Ricky Wai4482ab52019-12-10 19:08:18 +00001199 return ent->d_name;
1200 }
1201 }
Ricky Wai4482ab52019-12-10 19:08:18 +00001202 }
1203 // Fallback done
1204
1205 fail_fn(CREATE_ERROR("Unable to find %s:%lld in %s", package_name.data(),
1206 ce_data_inode, parent_path.data()));
1207 return nullptr;
1208 }
1209}
1210
1211// Isolate app's data directory, by mounting a tmpfs on CE DE storage,
1212// and create and bind mount app data in related_packages.
1213static void isolateAppDataPerPackage(int userId, std::string_view package_name,
1214 std::string_view volume_uuid, long long ce_data_inode, std::string_view actualCePath,
1215 std::string_view actualDePath, fail_fn_t fail_fn) {
1216
1217 char mirrorCePath[PATH_MAX];
1218 char mirrorDePath[PATH_MAX];
1219 char mirrorCeParent[PATH_MAX];
1220 snprintf(mirrorCeParent, PATH_MAX, "/data_mirror/data_ce/%s", volume_uuid.data());
1221 snprintf(mirrorCePath, PATH_MAX, "%s/%d", mirrorCeParent, userId);
1222 snprintf(mirrorDePath, PATH_MAX, "/data_mirror/data_de/%s/%d", volume_uuid.data(), userId);
1223
1224 createAndMountAppData(package_name, package_name, mirrorDePath, actualDePath, fail_fn);
1225
1226 std::string ce_data_path = getAppDataDirName(mirrorCePath, package_name, ce_data_inode, fail_fn);
1227 createAndMountAppData(package_name, ce_data_path, mirrorCePath, actualCePath, fail_fn);
1228}
1229
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001230// Relabel directory
1231static void relabelDir(const char* path, security_context_t context, fail_fn_t fail_fn) {
1232 if (setfilecon(path, context) != 0) {
1233 fail_fn(CREATE_ERROR("Failed to setfilecon %s %s", path, strerror(errno)));
1234 }
1235}
1236
1237// Relabel all directories under a path non-recursively.
1238static void relabelAllDirs(const char* path, security_context_t context, fail_fn_t fail_fn) {
1239 DIR* dir = opendir(path);
1240 if (dir == nullptr) {
1241 fail_fn(CREATE_ERROR("Failed to opendir %s", path));
1242 }
1243 struct dirent* ent;
1244 while ((ent = readdir(dir))) {
1245 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1246 auto filePath = StringPrintf("%s/%s", path, ent->d_name);
1247 if (ent->d_type == DT_DIR) {
1248 relabelDir(filePath.c_str(), context, fail_fn);
1249 } else if (ent->d_type == DT_LNK) {
1250 if (lsetfilecon(filePath.c_str(), context) != 0) {
1251 fail_fn(CREATE_ERROR("Failed to lsetfilecon %s %s", filePath.c_str(), strerror(errno)));
1252 }
1253 } else {
1254 fail_fn(CREATE_ERROR("Unexpected type: %d %s", ent->d_type, filePath.c_str()));
1255 }
1256 }
1257 closedir(dir);
1258}
1259
Ricky Wai4482ab52019-12-10 19:08:18 +00001260/**
1261 * Make other apps data directory not visible in CE, DE storage.
1262 *
1263 * Apps without app data isolation can detect if another app is installed on system,
1264 * by "touching" other apps data directory like /data/data/com.whatsapp, if it returns
1265 * "Permission denied" it means apps installed, otherwise it returns "File not found".
1266 * Traditional file permissions or SELinux can only block accessing those directories but
1267 * can't fix fingerprinting like this.
1268 * We fix it by "overlaying" data directory, and only relevant app data packages exists
1269 * in data directories.
1270 *
1271 * Steps:
1272 * 1). Collect a list of all related apps (apps with same uid and whitelisted apps) data info
1273 * (package name, data stored volume uuid, and inode number of its CE data directory)
1274 * 2). Mount tmpfs on /data/data, /data/user(_de) and /mnt/expand, so apps no longer
1275 * able to access apps data directly.
1276 * 3). For each related app, create its app data directory and bind mount the actual content
1277 * from apps data mirror directory. This works on both CE and DE storage, as DE storage
1278 * is always available even storage is FBE locked, while we use inode number to find
1279 * the encrypted DE directory in mirror so we can still bind mount it successfully.
1280 *
1281 * Example:
1282 * 0). Assuming com.android.foo CE data is stored in /data/data and no shared uid
1283 * 1). Mount a tmpfs on /data/data, /data/user, /data/user_de, /mnt/expand
1284 * List = ["com.android.foo", "null" (volume uuid "null"=default),
1285 * 123456 (inode number)]
1286 * 2). On DE storage, we create a directory /data/user_de/0/com.com.android.foo, and bind
1287 * mount (in the app's mount namespace) it from /data_mirror/data_de/0/com.android.foo.
1288 * 3). We do similar for CE storage. But in direct boot mode, as /data_mirror/data_ce/0/ is
1289 * encrypted, we can't find a directory with name com.android.foo on it, so we will
1290 * use the inode number to find the right directory instead, which that directory content will
1291 * be decrypted after storage is decrypted.
1292 *
1293 */
1294static void isolateAppData(JNIEnv* env, jobjectArray pkg_data_info_list,
1295 uid_t uid, const char* process_name, jstring managed_nice_name,
1296 fail_fn_t fail_fn) {
1297
1298 const userid_t userId = multiuser_get_user_id(uid);
1299
1300 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
1301
1302 int size = (pkg_data_info_list != nullptr) ? env->GetArrayLength(pkg_data_info_list) : 0;
1303 // Size should be a multiple of 3, as it contains list of <package_name, volume_uuid, inode>
1304 if ((size % 3) != 0) {
1305 fail_fn(CREATE_ERROR("Wrong pkg_inode_list size %d", size));
1306 }
1307
1308 // Mount tmpfs on all possible data directories, so app no longer see the original apps data.
1309 char internalCePath[PATH_MAX];
1310 char internalLegacyCePath[PATH_MAX];
1311 char internalDePath[PATH_MAX];
1312 char externalPrivateMountPath[PATH_MAX];
1313
1314 snprintf(internalCePath, PATH_MAX, "/data/user");
1315 snprintf(internalLegacyCePath, PATH_MAX, "/data/data");
1316 snprintf(internalDePath, PATH_MAX, "/data/user_de");
1317 snprintf(externalPrivateMountPath, PATH_MAX, "/mnt/expand");
1318
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001319 security_context_t dataDataContext = nullptr;
1320 if (getfilecon(internalDePath, &dataDataContext) < 0) {
1321 fail_fn(CREATE_ERROR("Unable to getfilecon on %s %s", internalDePath,
1322 strerror(errno)));
1323 }
1324
Ricky Wai4482ab52019-12-10 19:08:18 +00001325 MountAppDataTmpFs(internalLegacyCePath, fail_fn);
1326 MountAppDataTmpFs(internalCePath, fail_fn);
1327 MountAppDataTmpFs(internalDePath, fail_fn);
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001328
1329 // Mount tmpfs on all external vols DE and CE storage
1330 DIR* dir = opendir(externalPrivateMountPath);
1331 if (dir == nullptr) {
1332 fail_fn(CREATE_ERROR("Failed to opendir %s", externalPrivateMountPath));
1333 }
1334 struct dirent* ent;
1335 while ((ent = readdir(dir))) {
1336 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1337 if (ent->d_type != DT_DIR) {
1338 fail_fn(CREATE_ERROR("Unexpected type: %d %s", ent->d_type, ent->d_name));
1339 }
1340 auto volPath = StringPrintf("%s/%s", externalPrivateMountPath, ent->d_name);
1341 auto cePath = StringPrintf("%s/user", volPath.c_str());
1342 auto dePath = StringPrintf("%s/user_de", volPath.c_str());
1343 MountAppDataTmpFs(cePath.c_str(), fail_fn);
1344 MountAppDataTmpFs(dePath.c_str(), fail_fn);
1345 }
1346 closedir(dir);
1347
1348 bool legacySymlinkCreated = false;
Ricky Wai4482ab52019-12-10 19:08:18 +00001349
1350 for (int i = 0; i < size; i += 3) {
1351 jstring package_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i));
1352 std::string packageName = extract_fn(package_str).value();
1353
1354 jstring vol_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i + 1));
1355 std::string volUuid = extract_fn(vol_str).value();
1356
1357 jstring inode_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i + 2));
1358 std::string inode = extract_fn(inode_str).value();
1359 std::string::size_type sz;
1360 long long ceDataInode = std::stoll(inode, &sz);
1361
1362 std::string actualCePath, actualDePath;
1363 if (volUuid.compare("null") != 0) {
1364 // Volume that is stored in /mnt/expand
1365 char volPath[PATH_MAX];
1366 char volCePath[PATH_MAX];
1367 char volDePath[PATH_MAX];
1368 char volCeUserPath[PATH_MAX];
1369 char volDeUserPath[PATH_MAX];
1370
1371 snprintf(volPath, PATH_MAX, "/mnt/expand/%s", volUuid.c_str());
1372 snprintf(volCePath, PATH_MAX, "%s/user", volPath);
1373 snprintf(volDePath, PATH_MAX, "%s/user_de", volPath);
1374 snprintf(volCeUserPath, PATH_MAX, "%s/%d", volCePath, userId);
1375 snprintf(volDeUserPath, PATH_MAX, "%s/%d", volDePath, userId);
1376
1377 PrepareDirIfNotPresent(volPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1378 PrepareDirIfNotPresent(volCePath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1379 PrepareDirIfNotPresent(volDePath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1380 PrepareDirIfNotPresent(volCeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1381 fail_fn);
1382 PrepareDirIfNotPresent(volDeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1383 fail_fn);
1384
1385 actualCePath = volCeUserPath;
1386 actualDePath = volDeUserPath;
1387 } else {
1388 // Internal volume that stored in /data
1389 char internalCeUserPath[PATH_MAX];
1390 char internalDeUserPath[PATH_MAX];
1391 snprintf(internalCeUserPath, PATH_MAX, "/data/user/%d", userId);
1392 snprintf(internalDeUserPath, PATH_MAX, "/data/user_de/%d", userId);
1393 // If it's user 0, create a symlink /data/user/0 -> /data/data,
1394 // otherwise create /data/user/$USER
1395 if (userId == 0) {
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001396 if (!legacySymlinkCreated) {
1397 legacySymlinkCreated = true;
1398 int result = symlink(internalLegacyCePath, internalCeUserPath);
1399 if (result != 0) {
1400 fail_fn(CREATE_ERROR("Failed to create symlink %s %s", internalCeUserPath,
1401 strerror(errno)));
1402 }
1403 }
Ricky Wai4482ab52019-12-10 19:08:18 +00001404 actualCePath = internalLegacyCePath;
1405 } else {
1406 PrepareDirIfNotPresent(internalCeUserPath, DEFAULT_DATA_DIR_PERMISSION,
1407 AID_ROOT, AID_ROOT, fail_fn);
1408 actualCePath = internalCeUserPath;
1409 }
1410 PrepareDirIfNotPresent(internalDeUserPath, DEFAULT_DATA_DIR_PERMISSION,
1411 AID_ROOT, AID_ROOT, fail_fn);
1412 actualDePath = internalDeUserPath;
1413 }
1414 isolateAppDataPerPackage(userId, packageName, volUuid, ceDataInode,
1415 actualCePath, actualDePath, fail_fn);
1416 }
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001417 // We set the label AFTER everything is done, as we are applying
1418 // the file operations on tmpfs. If we set the label when we mount
1419 // tmpfs, SELinux will not happy as we are changing system_data_files.
1420 // Relabel dir under /data/user, including /data/user/0
1421 relabelAllDirs(internalCePath, dataDataContext, fail_fn);
1422
1423 // Relabel /data/user
1424 relabelDir(internalCePath, dataDataContext, fail_fn);
1425
1426 // Relabel /data/data
1427 relabelDir(internalLegacyCePath, dataDataContext, fail_fn);
1428
1429 // Relabel dir under /data/user_de
1430 relabelAllDirs(internalDePath, dataDataContext, fail_fn);
1431
1432 // Relabel /data/user_de
1433 relabelDir(internalDePath, dataDataContext, fail_fn);
1434
1435 // Relabel CE and DE dirs under /mnt/expand
1436 dir = opendir(externalPrivateMountPath);
1437 if (dir == nullptr) {
1438 fail_fn(CREATE_ERROR("Failed to opendir %s", externalPrivateMountPath));
1439 }
1440 while ((ent = readdir(dir))) {
1441 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1442 auto volPath = StringPrintf("%s/%s", externalPrivateMountPath, ent->d_name);
1443 auto cePath = StringPrintf("%s/user", volPath.c_str());
1444 auto dePath = StringPrintf("%s/user_de", volPath.c_str());
1445
1446 relabelAllDirs(cePath.c_str(), dataDataContext, fail_fn);
1447 relabelDir(cePath.c_str(), dataDataContext, fail_fn);
1448 relabelAllDirs(dePath.c_str(), dataDataContext, fail_fn);
1449 relabelDir(dePath.c_str(), dataDataContext, fail_fn);
1450 }
1451 closedir(dir);
1452
1453 freecon(dataDataContext);
Ricky Wai4482ab52019-12-10 19:08:18 +00001454}
1455
Ricky Waiba4325f2019-12-02 16:32:58 +00001456/**
1457 * Like isolateAppData(), isolate jit profile directories, so apps don't see what
1458 * other apps are installed by reading content inside /data/misc/profiles/cur.
1459 *
1460 * The implementation is similar to isolateAppData(), it creates a tmpfs
1461 * on /data/misc/profiles/cur, and bind mounts related package profiles to it.
1462 */
1463static void isolateJitProfile(JNIEnv* env, jobjectArray pkg_data_info_list,
1464 uid_t uid, const char* process_name, jstring managed_nice_name,
1465 fail_fn_t fail_fn) {
1466
1467 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
1468 const userid_t user_id = multiuser_get_user_id(uid);
1469
1470 int size = (pkg_data_info_list != nullptr) ? env->GetArrayLength(pkg_data_info_list) : 0;
1471 // Size should be a multiple of 3, as it contains list of <package_name, volume_uuid, inode>
1472 if ((size % 3) != 0) {
1473 fail_fn(CREATE_ERROR("Wrong pkg_inode_list size %d", size));
1474 }
1475
1476 // Mount (namespace) tmpfs on profile directory, so apps no longer access
1477 // the original profile directory anymore.
1478 MountAppDataTmpFs(kCurProfileDirPath, fail_fn);
1479
1480 // Create profile directory for this user.
1481 std::string actualCurUserProfile = StringPrintf("%s/%d", kCurProfileDirPath, user_id);
Greg Kaiser4a966702020-01-21 06:41:29 -08001482 PrepareDir(actualCurUserProfile, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
Ricky Waiba4325f2019-12-02 16:32:58 +00001483
1484 for (int i = 0; i < size; i += 3) {
1485 jstring package_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i));
1486 std::string packageName = extract_fn(package_str).value();
1487
1488 std::string actualCurPackageProfile = StringPrintf("%s/%s", actualCurUserProfile.c_str(),
1489 packageName.c_str());
1490 std::string mirrorCurPackageProfile = StringPrintf("/data_mirror/cur_profiles/%d/%s",
1491 user_id, packageName.c_str());
1492
1493 PrepareDir(actualCurPackageProfile, DEFAULT_DATA_DIR_PERMISSION, uid, uid, fail_fn);
1494 BindMount(mirrorCurPackageProfile, actualCurPackageProfile, fail_fn);
1495 }
1496}
1497
Chris Wailesaf594fc2018-11-02 11:00:07 -07001498// Utility routine to specialize a zygote child process.
1499static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
1500 jint runtime_flags, jobjectArray rlimits,
1501 jlong permitted_capabilities, jlong effective_capabilities,
1502 jint mount_external, jstring managed_se_info,
1503 jstring managed_nice_name, bool is_system_server,
1504 bool is_child_zygote, jstring managed_instruction_set,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001505 jstring managed_app_data_dir, bool is_top_app,
1506 jobjectArray pkg_data_info_list) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001507 const char* process_name = is_system_server ? "system_server" : "zygote";
1508 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
1509 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001510
1511 auto se_info = extract_fn(managed_se_info);
1512 auto nice_name = extract_fn(managed_nice_name);
1513 auto instruction_set = extract_fn(managed_instruction_set);
1514 auto app_data_dir = extract_fn(managed_app_data_dir);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001515
Chris Wailesaf594fc2018-11-02 11:00:07 -07001516 // Keep capabilities across UID change, unless we're staying root.
1517 if (uid != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001518 EnableKeepCapabilities(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001519 }
1520
Chris Wailesaa1c9622019-01-10 16:55:32 -08001521 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001522
Chris Wailesaa1c9622019-01-10 16:55:32 -08001523 DropCapabilitiesBoundingSet(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001524
Lev Rumyantsev2b7a5ea2019-12-13 16:03:30 -08001525 bool need_pre_initialize_native_bridge =
1526 !is_system_server &&
1527 instruction_set.has_value() &&
1528 android::NativeBridgeAvailable() &&
1529 // Native bridge may be already initialized if this
1530 // is an app forked from app-zygote.
1531 !android::NativeBridgeInitialized() &&
1532 android::NeedsNativeBridge(instruction_set.value().c_str());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001533
Lev Rumyantsev2b7a5ea2019-12-13 16:03:30 -08001534 MountEmulatedStorage(uid, mount_external, need_pre_initialize_native_bridge, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001535
Ricky Wai4482ab52019-12-10 19:08:18 +00001536 // System services, isolated process, webview/app zygote, old target sdk app, should
1537 // give a null in same_uid_pkgs and private_volumes so they don't need app data isolation.
1538 // Isolated process / webview / app zygote should be gated by SELinux and file permission
1539 // so they can't even traverse CE / DE directories.
1540 if (pkg_data_info_list != nullptr
Ricky Wai19889422020-01-15 01:59:00 +00001541 && GetBoolProperty(ANDROID_APP_DATA_ISOLATION_ENABLED_PROPERTY, true)) {
Ricky Waiba4325f2019-12-02 16:32:58 +00001542 isolateAppData(env, pkg_data_info_list, uid, process_name, managed_nice_name, fail_fn);
1543 isolateJitProfile(env, pkg_data_info_list, uid, process_name, managed_nice_name, fail_fn);
Ricky Wai4482ab52019-12-10 19:08:18 +00001544 }
1545
Chris Wailesaf594fc2018-11-02 11:00:07 -07001546 // If this zygote isn't root, it won't be able to create a process group,
1547 // since the directory is owned by root.
1548 if (!is_system_server && getuid() == 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001549 const int rc = createProcessGroup(uid, getpid());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001550 if (rc == -EROFS) {
1551 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
1552 } else if (rc != 0) {
1553 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
1554 }
1555 }
1556
Chris Wailesaa1c9622019-01-10 16:55:32 -08001557 SetGids(env, gids, fail_fn);
1558 SetRLimits(env, rlimits, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001559
Lev Rumyantsev2b7a5ea2019-12-13 16:03:30 -08001560 if (need_pre_initialize_native_bridge) {
1561 // Due to the logic behind need_pre_initialize_native_bridge we know that
1562 // instruction_set contains a value.
1563 android::PreInitializeNativeBridge(
1564 app_data_dir.has_value() ? app_data_dir.value().c_str() : nullptr,
1565 instruction_set.value().c_str());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001566 }
1567
1568 if (setresgid(gid, gid, gid) == -1) {
1569 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
1570 }
1571
1572 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
1573 // before changing uid from 0, which clears capabilities. The other
1574 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
1575 // breaks SELinux domain transition (see b/71859146). As the result,
1576 // privileged syscalls used below still need to be accessible in app process.
Martijn Coenen86f08a52019-01-03 16:23:01 +01001577 SetUpSeccompFilter(uid, is_child_zygote);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001578
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001579 // Must be called before losing the permission to set scheduler policy.
1580 SetSchedulerPolicy(fail_fn, is_top_app);
1581
Chris Wailesaf594fc2018-11-02 11:00:07 -07001582 if (setresuid(uid, uid, uid) == -1) {
1583 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1584 }
1585
1586 // The "dumpable" flag of a process, which controls core dump generation, is
1587 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1588 // user or group ID changes. See proc(5) for possible values. In most cases,
1589 // the value is 0, so core dumps are disabled for zygote children. However,
1590 // when running in a Chrome OS container, the value is already set to 2,
1591 // which allows the external crash reporter to collect all core dumps. Since
1592 // only system crashes are interested, core dump is disabled for app
1593 // processes. This also ensures compliance with CTS.
1594 int dumpable = prctl(PR_GET_DUMPABLE);
1595 if (dumpable == -1) {
1596 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1597 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1598 }
1599
1600 if (dumpable == 2 && uid >= AID_APP) {
1601 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1602 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1603 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1604 }
1605 }
1606
Orion Hodson8d005a62018-12-05 12:28:53 +00001607 // Set process properties to enable debugging if required.
1608 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1609 EnableDebugger();
1610 }
Yabin Cui4d8546d2019-01-29 16:29:20 -08001611 if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
1612 // simpleperf needs the process to be dumpable to profile it.
1613 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
1614 ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
1615 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
1616 }
1617 }
Orion Hodson8d005a62018-12-05 12:28:53 +00001618
Chris Wailesaf594fc2018-11-02 11:00:07 -07001619 if (NeedsNoRandomizeWorkaround()) {
1620 // Work around ARM kernel ASLR lossage (http://b/5817320).
1621 int old_personality = personality(0xffffffff);
1622 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1623 if (new_personality == -1) {
1624 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1625 }
1626 }
1627
Chris Wailesaa1c9622019-01-10 16:55:32 -08001628 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001629
Mathieu Chartier0bccbf72019-01-30 15:56:17 -08001630 __android_log_close();
1631 stats_log_close();
1632
Chris Wailesaf594fc2018-11-02 11:00:07 -07001633 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1634 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1635
1636 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1637 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1638 uid, is_system_server, se_info_ptr, nice_name_ptr));
1639 }
1640
1641 // Make it easier to debug audit logs by setting the main thread's name to the
1642 // nice name rather than "app_process".
1643 if (nice_name.has_value()) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001644 SetThreadName(nice_name.value());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001645 } else if (is_system_server) {
1646 SetThreadName("system_server");
1647 }
1648
1649 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1650 UnsetChldSignalHandler();
1651
1652 if (is_system_server) {
Mathieu Chartier2cb0a4d2019-11-21 14:30:03 -08001653 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks, runtime_flags);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001654 if (env->ExceptionCheck()) {
1655 fail_fn("Error calling post fork system server hooks.");
1656 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001657
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07001658 // Prefetch the classloader for the system server. This is done early to
1659 // allow a tie-down of the proper system server selinux domain.
1660 env->CallStaticVoidMethod(gZygoteInitClass, gCreateSystemServerClassLoader);
1661 if (env->ExceptionCheck()) {
1662 // Be robust here. The Java code will attempt to create the classloader
1663 // at a later point (but may not have rights to use AoT artifacts).
1664 env->ExceptionClear();
1665 }
1666
Chris Wailesaf594fc2018-11-02 11:00:07 -07001667 // TODO(oth): Remove hardcoded label here (b/117874058).
1668 static const char* kSystemServerLabel = "u:r:system_server:s0";
1669 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1670 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1671 }
1672 }
1673
Jing Jie29afc92019-10-29 18:14:49 -07001674 if (is_child_zygote) {
1675 initUnsolSocketToSystemServer();
1676 }
1677
Chris Wailesaf594fc2018-11-02 11:00:07 -07001678 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1679 is_system_server, is_child_zygote, managed_instruction_set);
1680
Chris Wailes3d748212019-05-09 17:11:00 -07001681 // Reset the process priority to the default value.
1682 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_DEFAULT);
1683
Chris Wailesaf594fc2018-11-02 11:00:07 -07001684 if (env->ExceptionCheck()) {
1685 fail_fn("Error calling post fork hooks.");
1686 }
1687}
1688
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001689static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1690 __user_cap_header_struct capheader;
1691 memset(&capheader, 0, sizeof(capheader));
1692 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1693 capheader.pid = 0;
1694
1695 __user_cap_data_struct capdata[2];
1696 if (capget(&capheader, &capdata[0]) == -1) {
1697 ALOGE("capget failed: %s", strerror(errno));
1698 RuntimeAbort(env, __LINE__, "capget failed");
1699 }
1700
Chris Wailesaf594fc2018-11-02 11:00:07 -07001701 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1702}
1703
1704static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1705 bool is_child_zygote) {
1706 jlong capabilities = 0;
1707
1708 /*
1709 * Grant the following capabilities to the Bluetooth user:
1710 * - CAP_WAKE_ALARM
Nitin Shivpure99cec9d2019-05-29 14:02:49 +05301711 * - CAP_NET_ADMIN
Chris Wailesaf594fc2018-11-02 11:00:07 -07001712 * - CAP_NET_RAW
1713 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1714 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1715 */
1716
1717 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1718 capabilities |= (1LL << CAP_WAKE_ALARM);
Nitin Shivpure99cec9d2019-05-29 14:02:49 +05301719 capabilities |= (1LL << CAP_NET_ADMIN);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001720 capabilities |= (1LL << CAP_NET_RAW);
1721 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1722 capabilities |= (1LL << CAP_SYS_NICE);
1723 }
1724
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001725 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1726 capabilities |= (1LL << CAP_NET_ADMIN);
1727 capabilities |= (1LL << CAP_NET_BROADCAST);
1728 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1729 capabilities |= (1LL << CAP_NET_RAW);
1730 }
1731
Chris Wailesaf594fc2018-11-02 11:00:07 -07001732 /*
1733 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1734 */
1735
1736 bool gid_wakelock_found = false;
1737 if (gid == AID_WAKELOCK) {
1738 gid_wakelock_found = true;
1739 } else if (gids != nullptr) {
1740 jsize gids_num = env->GetArrayLength(gids);
1741 ScopedIntArrayRO native_gid_proxy(env, gids);
1742
1743 if (native_gid_proxy.get() == nullptr) {
1744 RuntimeAbort(env, __LINE__, "Bad gids array");
1745 }
1746
Chris Wailes31c52c92019-02-14 11:20:02 -08001747 for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
1748 if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001749 gid_wakelock_found = true;
1750 break;
1751 }
1752 }
1753 }
1754
1755 if (gid_wakelock_found) {
1756 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1757 }
1758
1759 /*
1760 * Grant child Zygote processes the following capabilities:
1761 * - CAP_SETUID (change UID of child processes)
1762 * - CAP_SETGID (change GID of child processes)
1763 * - CAP_SETPCAP (change capabilities of child processes)
1764 */
1765
1766 if (is_child_zygote) {
1767 capabilities |= (1LL << CAP_SETUID);
1768 capabilities |= (1LL << CAP_SETGID);
1769 capabilities |= (1LL << CAP_SETPCAP);
1770 }
1771
1772 /*
1773 * Containers run without some capabilities, so drop any caps that are not
1774 * available.
1775 */
1776
1777 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001778}
Chris Wailesaa1c9622019-01-10 16:55:32 -08001779
1780/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001781 * Adds the given information about a newly created unspecialized app
1782 * processes to the Zygote's USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001783 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001784 * @param usap_pid Process ID of the newly created USAP
1785 * @param read_pipe_fd File descriptor for the read end of the USAP
1786 * reporting pipe. Used in the ZygoteServer poll loop to track USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001787 * specialization.
1788 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001789static void AddUsapTableEntry(pid_t usap_pid, int read_pipe_fd) {
1790 static int sUsapTableInsertIndex = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001791
Chris Wailes7e797b62019-02-22 18:29:22 -08001792 int search_index = sUsapTableInsertIndex;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001793
1794 do {
Chris Wailes7e797b62019-02-22 18:29:22 -08001795 if (gUsapTable[search_index].SetIfInvalid(usap_pid, read_pipe_fd)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001796 // Start our next search right after where we finished this one.
Chris Wailes7e797b62019-02-22 18:29:22 -08001797 sUsapTableInsertIndex = (search_index + 1) % gUsapTable.size();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001798
1799 return;
1800 }
1801
Chris Wailes7e797b62019-02-22 18:29:22 -08001802 search_index = (search_index + 1) % gUsapTable.size();
1803 } while (search_index != sUsapTableInsertIndex);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001804
1805 // Much like money in the banana stand, there should always be an entry
Chris Wailes7e797b62019-02-22 18:29:22 -08001806 // in the USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001807 __builtin_unreachable();
1808}
1809
1810/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001811 * Invalidates the entry in the USAPTable corresponding to the provided
1812 * process ID if it is present. If an entry was removed the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001813 * count is decremented.
1814 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001815 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001816 * @return True if an entry was invalidated; false otherwise
1817 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001818static bool RemoveUsapTableEntry(pid_t usap_pid) {
1819 for (UsapTableEntry& entry : gUsapTable) {
1820 if (entry.ClearForPID(usap_pid)) {
1821 --gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001822 return true;
1823 }
1824 }
1825
1826 return false;
1827}
1828
1829/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001830 * @return A vector of the read pipe FDs for each of the active USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001831 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001832std::vector<int> MakeUsapPipeReadFDVector() {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001833 std::vector<int> fd_vec;
Chris Wailes7e797b62019-02-22 18:29:22 -08001834 fd_vec.reserve(gUsapTable.size());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001835
Chris Wailes7e797b62019-02-22 18:29:22 -08001836 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001837 auto entry_values = entry.GetValues();
1838
1839 if (entry_values.has_value()) {
1840 fd_vec.push_back(entry_values.value().read_pipe_fd);
1841 }
1842 }
1843
1844 return fd_vec;
1845}
1846
Chris Wailes6d482d542019-04-03 13:00:52 -07001847static void UnmountStorageOnInit(JNIEnv* env) {
1848 // Zygote process unmount root storage space initially before every child processes are forked.
1849 // Every forked child processes (include SystemServer) only mount their own root storage space
1850 // and no need unmount storage operation in MountEmulatedStorage method.
1851 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1852
1853 // See storage config details at http://source.android.com/tech/storage/
1854 // Create private mount namespace shared by all children
1855 if (unshare(CLONE_NEWNS) == -1) {
1856 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1857 return;
1858 }
1859
1860 // Mark rootfs as being a slave so that changes from default
1861 // namespace only flow into our children.
1862 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1863 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1864 return;
1865 }
1866
1867 // Create a staging tmpfs that is shared by our children; they will
1868 // bind mount storage into their respective private namespaces, which
1869 // are isolated from each other.
1870 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1871 if (target_base != nullptr) {
1872#define STRINGIFY_UID(x) __STRING(x)
1873 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1874 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1875 ALOGE("Failed to mount tmpfs to %s", target_base);
1876 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1877 return;
1878 }
1879#undef STRINGIFY_UID
1880 }
1881
1882 UnmountTree("/storage");
1883}
1884
Chris Wailesff8d4e72019-04-10 17:49:24 -07001885static int DisableExecuteOnly(struct dl_phdr_info* info,
1886 size_t size [[maybe_unused]],
1887 void* data [[maybe_unused]]) {
1888 // Search for any execute-only segments and mark them read+execute.
1889 for (int i = 0; i < info->dlpi_phnum; i++) {
Nick Desaulniersa9940c22019-12-11 15:33:39 -08001890 const auto& phdr = info->dlpi_phdr[i];
1891 if ((phdr.p_type == PT_LOAD) && (phdr.p_flags == PF_X)) {
1892 auto addr = reinterpret_cast<void*>(info->dlpi_addr + PAGE_START(phdr.p_vaddr));
1893 size_t len = PAGE_OFFSET(phdr.p_vaddr) + phdr.p_memsz;
1894 if (mprotect(addr, len, PROT_READ | PROT_EXEC) == -1) {
1895 ALOGE("mprotect(%p, %zu, PROT_READ | PROT_EXEC) failed: %m", addr, len);
1896 return -1;
1897 }
Chris Wailesff8d4e72019-04-10 17:49:24 -07001898 }
1899 }
1900 // Return non-zero to exit dl_iterate_phdr.
1901 return 0;
1902}
1903
Narayan Kamath973b4662014-03-31 13:41:26 +01001904} // anonymous namespace
1905
1906namespace android {
1907
Christopher Ferris76de39e2017-06-20 16:13:40 -07001908static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1909 PreApplicationInit();
1910}
1911
Narayan Kamath973b4662014-03-31 13:41:26 +01001912static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1913 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001914 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001915 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001916 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001917 jstring instruction_set, jstring app_data_dir, jboolean is_top_app,
1918 jobjectArray pkg_data_info_list) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001919 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001920
Chris Wailesaa1c9622019-01-10 16:55:32 -08001921 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1922 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1923 }
1924
1925 std::vector<int> fds_to_close =
1926 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1927 std::vector<int> fds_to_ignore =
1928 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1929 .value_or(std::vector<int>());
1930
Chris Wailes7e797b62019-02-22 18:29:22 -08001931 std::vector<int> usap_pipes = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001932
Chris Wailes7e797b62019-02-22 18:29:22 -08001933 fds_to_close.insert(fds_to_close.end(), usap_pipes.begin(), usap_pipes.end());
1934 fds_to_ignore.insert(fds_to_ignore.end(), usap_pipes.begin(), usap_pipes.end());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001935
Chris Wailes7e797b62019-02-22 18:29:22 -08001936 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001937
Chris Wailes7e797b62019-02-22 18:29:22 -08001938 if (gUsapPoolEventFD != -1) {
1939 fds_to_close.push_back(gUsapPoolEventFD);
1940 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001941 }
1942
Jing Jie29afc92019-10-29 18:14:49 -07001943 if (gSystemServerSocketFd != -1) {
1944 fds_to_close.push_back(gSystemServerSocketFd);
1945 fds_to_ignore.push_back(gSystemServerSocketFd);
1946 }
1947
Chris Wailes3d748212019-05-09 17:11:00 -07001948 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore, true);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001949
David Sehrde8d0bd2018-06-22 10:45:36 -07001950 if (pid == 0) {
1951 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1952 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001953 mount_external, se_info, nice_name, false,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001954 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001955 is_top_app == JNI_TRUE, pkg_data_info_list);
David Sehrde8d0bd2018-06-22 10:45:36 -07001956 }
1957 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001958}
1959
1960static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1961 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001962 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1963 jlong effective_capabilities) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001964 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001965 fds_to_ignore(fds_to_close);
1966
Chris Wailes7e797b62019-02-22 18:29:22 -08001967 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001968
Chris Wailes7e797b62019-02-22 18:29:22 -08001969 if (gUsapPoolEventFD != -1) {
1970 fds_to_close.push_back(gUsapPoolEventFD);
1971 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001972 }
1973
Jing Jie29afc92019-10-29 18:14:49 -07001974 if (gSystemServerSocketFd != -1) {
1975 fds_to_close.push_back(gSystemServerSocketFd);
1976 fds_to_ignore.push_back(gSystemServerSocketFd);
1977 }
1978
Chris Wailesaf594fc2018-11-02 11:00:07 -07001979 pid_t pid = ForkCommon(env, true,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001980 fds_to_close,
Chris Wailes3d748212019-05-09 17:11:00 -07001981 fds_to_ignore,
1982 true);
David Sehrde8d0bd2018-06-22 10:45:36 -07001983 if (pid == 0) {
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001984 // System server prcoess does not need data isolation so no need to
1985 // know pkg_data_info_list.
David Sehrde8d0bd2018-06-22 10:45:36 -07001986 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001987 permitted_capabilities, effective_capabilities,
1988 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001989 false, nullptr, nullptr, /* is_top_app= */ false,
1990 /* pkg_data_info_list */ nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001991 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001992 // The zygote process checks whether the child process has died or not.
1993 ALOGI("System server process %d has been created", pid);
1994 gSystemServerPid = pid;
1995 // There is a slight window that the system server process has crashed
1996 // but it went unnoticed because we haven't published its pid yet. So
1997 // we recheck here just to make sure that all is well.
1998 int status;
1999 if (waitpid(pid, &status, WNOHANG) == pid) {
2000 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08002001 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01002002 }
Carmen Jacksondd401252017-02-23 15:21:10 -08002003
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08002004 if (UsePerAppMemcg()) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09002005 // Assign system_server to the correct memory cgroup.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08002006 // Not all devices mount memcg so check if it is mounted first
Minchan Kim5fa8af22018-06-27 11:32:40 +09002007 // to avoid unnecessarily printing errors and denials in the logs.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08002008 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
2009 ALOGE("couldn't add process %d into system memcg group", pid);
Minchan Kim5fa8af22018-06-27 11:32:40 +09002010 }
Carmen Jacksondd401252017-02-23 15:21:10 -08002011 }
Narayan Kamath973b4662014-03-31 13:41:26 +01002012 }
2013 return pid;
2014}
2015
Chris Wailesaa1c9622019-01-10 16:55:32 -08002016/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002017 * A JNI function that forks an unspecialized app process from the Zygote while
2018 * ensuring proper file descriptor hygiene.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002019 *
2020 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08002021 * @param read_pipe_fd The read FD for the USAP reporting pipe. Manually closed by blastlas
Chris Wailesaa1c9622019-01-10 16:55:32 -08002022 * in managed code.
Chris Wailes7e797b62019-02-22 18:29:22 -08002023 * @param write_pipe_fd The write FD for the USAP reporting pipe. Manually closed by the
Chris Wailesaa1c9622019-01-10 16:55:32 -08002024 * zygote in managed code.
2025 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
Chris Wailes7e797b62019-02-22 18:29:22 -08002026 * the FD hygiene code and automatically "closed" in the new USAP.
Chris Wailes3d748212019-05-09 17:11:00 -07002027 * @param is_priority_fork Controls the nice level assigned to the newly created process
Chris Wailesaa1c9622019-01-10 16:55:32 -08002028 * @return
2029 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002030static jint com_android_internal_os_Zygote_nativeForkUsap(JNIEnv* env,
2031 jclass,
2032 jint read_pipe_fd,
2033 jint write_pipe_fd,
Chris Wailes3d748212019-05-09 17:11:00 -07002034 jintArray managed_session_socket_fds,
2035 jboolean is_priority_fork) {
Chris Wailes7e797b62019-02-22 18:29:22 -08002036 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08002037 fds_to_ignore(fds_to_close);
2038
2039 std::vector<int> session_socket_fds =
Chris Wailes7e797b62019-02-22 18:29:22 -08002040 ExtractJIntArray(env, "USAP", nullptr, managed_session_socket_fds)
Chris Wailesaa1c9622019-01-10 16:55:32 -08002041 .value_or(std::vector<int>());
2042
Chris Wailes7e797b62019-02-22 18:29:22 -08002043 // The USAP Pool Event FD is created during the initialization of the
2044 // USAP pool and should always be valid here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002045
2046 fds_to_close.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08002047 fds_to_close.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002048 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
Jing Jie29afc92019-10-29 18:14:49 -07002049 if (gSystemServerSocketFd != -1) {
2050 fds_to_close.push_back(gSystemServerSocketFd);
2051 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08002052
2053 fds_to_ignore.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08002054 fds_to_ignore.push_back(gUsapPoolSocketFD);
2055 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002056 fds_to_ignore.push_back(read_pipe_fd);
2057 fds_to_ignore.push_back(write_pipe_fd);
2058 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
Jing Jie29afc92019-10-29 18:14:49 -07002059 if (gSystemServerSocketFd != -1) {
2060 fds_to_ignore.push_back(gSystemServerSocketFd);
2061 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08002062
Chris Wailes3d748212019-05-09 17:11:00 -07002063 pid_t usap_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore,
2064 is_priority_fork == JNI_TRUE);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002065
Chris Wailes7e797b62019-02-22 18:29:22 -08002066 if (usap_pid != 0) {
2067 ++gUsapPoolCount;
2068 AddUsapTableEntry(usap_pid, read_pipe_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002069 }
2070
Chris Wailes7e797b62019-02-22 18:29:22 -08002071 return usap_pid;
Chris Wailesaa1c9622019-01-10 16:55:32 -08002072}
2073
Robert Sesek54e387d2016-12-02 17:27:50 -05002074static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
2075 JNIEnv* env, jclass, jstring path) {
2076 ScopedUtfChars path_native(env, path);
2077 const char* path_cstr = path_native.c_str();
2078 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07002079 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05002080 }
2081 FileDescriptorWhitelist::Get()->Allow(path_cstr);
2082}
2083
Martijn Coenen86f08a52019-01-03 16:23:01 +01002084static void com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(
2085 JNIEnv* env, jclass, jint uidGidMin, jint uidGidMax) {
Chris Wailes6d482d542019-04-03 13:00:52 -07002086 if (!gIsSecurityEnforced) {
Martijn Coenen86f08a52019-01-03 16:23:01 +01002087 ALOGI("seccomp disabled by setenforce 0");
2088 return;
2089 }
2090
Martijn Coenen86f08a52019-01-03 16:23:01 +01002091 bool installed = install_setuidgid_seccomp_filter(uidGidMin, uidGidMax);
2092 if (!installed) {
2093 RuntimeAbort(env, __LINE__, "Could not install setuid/setgid seccomp filter.");
2094 }
Martijn Coenen86f08a52019-01-03 16:23:01 +01002095}
2096
Chris Wailesaa1c9622019-01-10 16:55:32 -08002097/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002098 * Called from an unspecialized app process to specialize the process for a
2099 * given application.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002100 *
2101 * @param env Managed runtime environment
2102 * @param uid User ID of the new application
2103 * @param gid Group ID of the new application
2104 * @param gids Extra groups that the process belongs to
2105 * @param runtime_flags Flags for changing the behavior of the managed runtime
2106 * @param rlimits Resource limits
2107 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
2108 * @param se_info SELinux policy information
2109 * @param nice_name New name for this process
2110 * @param is_child_zygote If the process is to become a WebViewZygote
2111 * @param instruction_set The instruction set expected/requested by the new application
2112 * @param app_data_dir Path to the application's data directory
Riddle Hsu32dbdca2019-05-17 23:10:16 -06002113 * @param is_top_app If the process is for top (high priority) application
Chris Wailesaa1c9622019-01-10 16:55:32 -08002114 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002115static void com_android_internal_os_Zygote_nativeSpecializeAppProcess(
Chris Wailesaa1c9622019-01-10 16:55:32 -08002116 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
2117 jint runtime_flags, jobjectArray rlimits,
2118 jint mount_external, jstring se_info, jstring nice_name,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00002119 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app,
2120 jobjectArray pkg_data_info_list) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08002121 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
2122
2123 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
2124 capabilities, capabilities,
2125 mount_external, se_info, nice_name, false,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06002126 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00002127 is_top_app == JNI_TRUE, pkg_data_info_list);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002128}
2129
2130/**
2131 * A helper method for fetching socket file descriptors that were opened by init from the
2132 * environment.
2133 *
2134 * @param env Managed runtime environment
2135 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
2136 * of the environment variable storing the file descriptors.
2137 */
Chris Wailes6d482d542019-04-03 13:00:52 -07002138static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv* env, jclass,
2139 jboolean is_primary) {
2140 /*
2141 * Obtain file descriptors created by init from the environment.
2142 */
2143
Chris Wailesee1fd452019-04-10 18:05:25 -07002144 gZygoteSocketFD =
2145 android_get_control_socket(is_primary ? "zygote" : "zygote_secondary");
2146 if (gZygoteSocketFD >= 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08002147 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
2148 } else {
2149 ALOGE("Unable to fetch Zygote socket file descriptor");
2150 }
2151
Chris Wailesee1fd452019-04-10 18:05:25 -07002152 gUsapPoolSocketFD =
2153 android_get_control_socket(is_primary ? "usap_pool_primary" : "usap_pool_secondary");
2154 if (gUsapPoolSocketFD >= 0) {
Chris Wailes7e797b62019-02-22 18:29:22 -08002155 ALOGV("Zygote:usapPoolSocketFD = %d", gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002156 } else {
Chris Wailes7e797b62019-02-22 18:29:22 -08002157 ALOGE("Unable to fetch USAP pool socket file descriptor");
Chris Wailesaa1c9622019-01-10 16:55:32 -08002158 }
Chris Wailes6d482d542019-04-03 13:00:52 -07002159
Jing Jie29afc92019-10-29 18:14:49 -07002160 initUnsolSocketToSystemServer();
2161
Chris Wailes6d482d542019-04-03 13:00:52 -07002162 /*
2163 * Security Initialization
2164 */
2165
2166 // security_getenforce is not allowed on app process. Initialize and cache
2167 // the value before zygote forks.
2168 gIsSecurityEnforced = security_getenforce();
2169
2170 selinux_android_seapp_context_init();
2171
2172 /*
2173 * Storage Initialization
2174 */
2175
2176 UnmountStorageOnInit(env);
2177
2178 /*
2179 * Performance Initialization
2180 */
2181
2182 if (!SetTaskProfiles(0, {})) {
2183 ZygoteFailure(env, "zygote", nullptr, "Zygote SetTaskProfiles failed");
2184 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08002185}
2186
2187/**
2188 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08002189 * @return A managed array of raw file descriptors for the read ends of the USAP reporting
Chris Wailesaa1c9622019-01-10 16:55:32 -08002190 * pipes.
2191 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002192static jintArray com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv* env, jclass) {
2193 std::vector<int> usap_fds = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08002194
Chris Wailes7e797b62019-02-22 18:29:22 -08002195 jintArray managed_usap_fds = env->NewIntArray(usap_fds.size());
2196 env->SetIntArrayRegion(managed_usap_fds, 0, usap_fds.size(), usap_fds.data());
Chris Wailesaa1c9622019-01-10 16:55:32 -08002197
Chris Wailes7e797b62019-02-22 18:29:22 -08002198 return managed_usap_fds;
Chris Wailesaa1c9622019-01-10 16:55:32 -08002199}
2200
2201/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002202 * A JNI wrapper around RemoveUsapTableEntry.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002203 *
2204 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08002205 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08002206 * @return True if an entry was invalidated; false otherwise.
2207 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002208static jboolean com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(JNIEnv* env, jclass,
2209 jint usap_pid) {
2210 return RemoveUsapTableEntry(usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002211}
2212
2213/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002214 * Creates the USAP pool event FD if it doesn't exist and returns it. This is used by the
2215 * ZygoteServer poll loop to know when to re-fill the USAP pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002216 *
2217 * @param env Managed runtime environment
2218 * @return A raw event file descriptor used to communicate (from the signal handler) when the
Chris Wailes7e797b62019-02-22 18:29:22 -08002219 * Zygote receives a SIGCHLD for a USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08002220 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002221static jint com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv* env, jclass) {
2222 if (gUsapPoolEventFD == -1) {
2223 if ((gUsapPoolEventFD = eventfd(0, 0)) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08002224 ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
2225 }
2226 }
2227
Chris Wailes7e797b62019-02-22 18:29:22 -08002228 return gUsapPoolEventFD;
Chris Wailesaa1c9622019-01-10 16:55:32 -08002229}
2230
2231/**
2232 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08002233 * @return The number of USAPs currently in the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08002234 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002235static jint com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv* env, jclass) {
2236 return gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08002237}
2238
Chris Wailesae937142019-01-24 12:57:33 -08002239/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002240 * Kills all processes currently in the USAP pool and closes their read pipe
2241 * FDs.
Chris Wailesae937142019-01-24 12:57:33 -08002242 *
2243 * @param env Managed runtime environment
Chris Wailesae937142019-01-24 12:57:33 -08002244 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002245static void com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv* env, jclass) {
2246 for (auto& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -08002247 auto entry_storage = entry.GetValues();
2248
2249 if (entry_storage.has_value()) {
Chris Wailesfb329ba2019-06-05 16:07:50 -07002250 kill(entry_storage.value().pid, SIGTERM);
2251
2252 // Clean up the USAP table entry here. This avoids a potential race
2253 // where a newly created USAP might not be able to find a valid table
2254 // entry if signal handler (which would normally do the cleanup) doesn't
2255 // run between now and when the new process is created.
2256
Chris Wailesdb132a32019-02-20 10:49:27 -08002257 close(entry_storage.value().read_pipe_fd);
2258
2259 // Avoid a second atomic load by invalidating instead of clearing.
2260 entry.Invalidate();
Chris Wailes7e797b62019-02-22 18:29:22 -08002261 --gUsapPoolCount;
Chris Wailesae937142019-01-24 12:57:33 -08002262 }
2263 }
2264}
2265
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07002266/**
2267 * @param env Managed runtime environment
2268 * @return True if disable was successful.
2269 */
2270static jboolean com_android_internal_os_Zygote_nativeDisableExecuteOnly(JNIEnv* env, jclass) {
Chris Wailesff8d4e72019-04-10 17:49:24 -07002271 return dl_iterate_phdr(DisableExecuteOnly, nullptr) == 0;
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07002272}
2273
Chris Wailesfb329ba2019-06-05 16:07:50 -07002274static void com_android_internal_os_Zygote_nativeBlockSigTerm(JNIEnv* env, jclass) {
2275 auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
2276 BlockSignal(SIGTERM, fail_fn);
2277}
2278
2279static void com_android_internal_os_Zygote_nativeUnblockSigTerm(JNIEnv* env, jclass) {
2280 auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
2281 UnblockSignal(SIGTERM, fail_fn);
2282}
2283
Chris Wailes3d748212019-05-09 17:11:00 -07002284static void com_android_internal_os_Zygote_nativeBoostUsapPriority(JNIEnv* env, jclass) {
2285 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
2286}
2287
Jing Jie29afc92019-10-29 18:14:49 -07002288static jint com_android_internal_os_Zygote_nativeParseSigChld(JNIEnv* env, jclass, jbyteArray in,
2289 jint length, jintArray out) {
2290 if (length != sizeof(struct UnsolicitedZygoteMessageSigChld)) {
2291 // Apparently it's not the message we are expecting.
2292 return -1;
2293 }
2294 if (in == nullptr || out == nullptr) {
2295 // Invalid parameter
2296 jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2297 return -1;
2298 }
2299 ScopedByteArrayRO source(env, in);
2300 if (source.size() < length) {
2301 // Invalid parameter
2302 jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2303 return -1;
2304 }
2305 const struct UnsolicitedZygoteMessageSigChld* msg =
2306 reinterpret_cast<const struct UnsolicitedZygoteMessageSigChld*>(source.get());
2307
2308 switch (msg->header.type) {
2309 case UNSOLICITED_ZYGOTE_MESSAGE_TYPE_SIGCHLD: {
2310 ScopedIntArrayRW buf(env, out);
2311 if (buf.size() != 3) {
2312 jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2313 return UNSOLICITED_ZYGOTE_MESSAGE_TYPE_RESERVED;
2314 }
2315 buf[0] = msg->payload.pid;
2316 buf[1] = msg->payload.uid;
2317 buf[2] = msg->payload.status;
2318 return 3;
2319 }
2320 default:
2321 break;
2322 }
2323 return -1;
2324}
2325
Daniel Micay76f6a862015-09-19 17:31:01 -04002326static const JNINativeMethod gMethods[] = {
Jing Jie29afc92019-10-29 18:14:49 -07002327 {"nativeForkAndSpecialize",
2328 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/"
2329 "String;Z[Ljava/lang/String;)I",
2330 (void*)com_android_internal_os_Zygote_nativeForkAndSpecialize},
2331 {"nativeForkSystemServer", "(II[II[[IJJ)I",
2332 (void*)com_android_internal_os_Zygote_nativeForkSystemServer},
2333 {"nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
2334 (void*)com_android_internal_os_Zygote_nativeAllowFileAcrossFork},
2335 {"nativePreApplicationInit", "()V",
2336 (void*)com_android_internal_os_Zygote_nativePreApplicationInit},
2337 {"nativeInstallSeccompUidGidFilter", "(II)V",
2338 (void*)com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter},
2339 {"nativeForkUsap", "(II[IZ)I", (void*)com_android_internal_os_Zygote_nativeForkUsap},
2340 {"nativeSpecializeAppProcess",
2341 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/"
2342 "String;Z[Ljava/lang/String;)V",
2343 (void*)com_android_internal_os_Zygote_nativeSpecializeAppProcess},
2344 {"nativeInitNativeState", "(Z)V",
2345 (void*)com_android_internal_os_Zygote_nativeInitNativeState},
2346 {"nativeGetUsapPipeFDs", "()[I",
2347 (void*)com_android_internal_os_Zygote_nativeGetUsapPipeFDs},
2348 {"nativeRemoveUsapTableEntry", "(I)Z",
2349 (void*)com_android_internal_os_Zygote_nativeRemoveUsapTableEntry},
2350 {"nativeGetUsapPoolEventFD", "()I",
2351 (void*)com_android_internal_os_Zygote_nativeGetUsapPoolEventFD},
2352 {"nativeGetUsapPoolCount", "()I",
2353 (void*)com_android_internal_os_Zygote_nativeGetUsapPoolCount},
2354 {"nativeEmptyUsapPool", "()V", (void*)com_android_internal_os_Zygote_nativeEmptyUsapPool},
2355 {"nativeDisableExecuteOnly", "()Z",
2356 (void*)com_android_internal_os_Zygote_nativeDisableExecuteOnly},
2357 {"nativeBlockSigTerm", "()V", (void*)com_android_internal_os_Zygote_nativeBlockSigTerm},
2358 {"nativeUnblockSigTerm", "()V", (void*)com_android_internal_os_Zygote_nativeUnblockSigTerm},
2359 {"nativeBoostUsapPriority", "()V",
2360 (void*)com_android_internal_os_Zygote_nativeBoostUsapPriority},
2361 {"nativeParseSigChld", "([BI[I)I",
2362 (void*)com_android_internal_os_Zygote_nativeParseSigChld},
Narayan Kamath973b4662014-03-31 13:41:26 +01002363};
2364
2365int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08002366 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01002367 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
2368 "callPostForkSystemServerHooks",
Mathieu Chartier2cb0a4d2019-11-21 14:30:03 -08002369 "(I)V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08002370 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05002371 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01002372
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07002373 gZygoteInitClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteInitClassName));
2374 gCreateSystemServerClassLoader = GetStaticMethodIDOrDie(env, gZygoteInitClass,
2375 "createSystemServerClassLoader",
2376 "()V");
2377
2378 RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
2379
2380 return JNI_OK;
Narayan Kamath973b4662014-03-31 13:41:26 +01002381}
2382} // namespace android