blob: 1ea7d6144356111087be77a6aceb7053b6acd557 [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);
Martijn Coenen6a01fae2019-12-13 16:44:32 +0100823 BindMount(pass_through_source, "/storage", fail_fn);
Martijn Coenen7d60e162020-01-11 19:45:08 +0100824 } else if (mount_mode == MOUNT_EXTERNAL_INSTALLER) {
825 const std::string installer_source = StringPrintf("/mnt/installer/%d", user_id);
826 BindMount(installer_source, "/storage", fail_fn);
Martijn Coenen6a01fae2019-12-13 16:44:32 +0100827 } else {
828 BindMount(user_source, "/storage", fail_fn);
829 }
Zima11d9102019-08-15 16:50:23 +0100830 } else {
831 const std::string& storage_source = ExternalStorageViews[mount_mode];
832 BindMount(storage_source, "/storage", fail_fn);
833
834 // Mount user-specific symlink helper into place
835 BindMount(user_source, "/storage/self", fail_fn);
836 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100837}
838
Narayan Kamath973b4662014-03-31 13:41:26 +0100839static bool NeedsNoRandomizeWorkaround() {
840#if !defined(__arm__)
841 return false;
842#else
843 int major;
844 int minor;
845 struct utsname uts;
846 if (uname(&uts) == -1) {
847 return false;
848 }
849
850 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
851 return false;
852 }
853
854 // Kernels before 3.4.* need the workaround.
855 return (major < 3) || ((major == 3) && (minor < 4));
856#endif
857}
Narayan Kamath973b4662014-03-31 13:41:26 +0100858
859// Utility to close down the Zygote socket file descriptors while
860// the child is still running as root with Zygote's privileges. Each
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800861// descriptor (if any) is closed via dup3(), replacing it with a valid
Narayan Kamath973b4662014-03-31 13:41:26 +0100862// (open) descriptor to /dev/null.
863
Chris Wailesaa1c9622019-01-10 16:55:32 -0800864static void DetachDescriptors(JNIEnv* env,
865 const std::vector<int>& fds_to_close,
866 fail_fn_t fail_fn) {
867
868 if (fds_to_close.size() > 0) {
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800869 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800870 if (devnull_fd == -1) {
871 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100872 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800873
874 for (int fd : fds_to_close) {
875 ALOGV("Switching descriptor %d to /dev/null", fd);
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800876 if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
877 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
Chris Wailesaa1c9622019-01-10 16:55:32 -0800878 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100879 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100880 }
881}
882
Chris Wailesaa1c9622019-01-10 16:55:32 -0800883void SetThreadName(const std::string& thread_name) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100884 bool hasAt = false;
885 bool hasDot = false;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800886
887 for (const char str_el : thread_name) {
888 if (str_el == '.') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100889 hasDot = true;
Chris Wailesaa1c9622019-01-10 16:55:32 -0800890 } else if (str_el == '@') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100891 hasAt = true;
892 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100893 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800894
895 const char* name_start_ptr = thread_name.c_str();
896 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
897 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
Narayan Kamath973b4662014-03-31 13:41:26 +0100898 }
Chris Wailesaa1c9622019-01-10 16:55:32 -0800899
Narayan Kamath973b4662014-03-31 13:41:26 +0100900 // pthread_setname_np fails rather than truncating long strings.
901 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
Chris Wailesaa1c9622019-01-10 16:55:32 -0800902 strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
Narayan Kamath973b4662014-03-31 13:41:26 +0100903 errno = pthread_setname_np(pthread_self(), buf);
904 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700905 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100906 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800907 // Update base::logging default tag.
908 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100909}
910
Chris Wailesaa1c9622019-01-10 16:55:32 -0800911/**
912 * A failure function used to report fatal errors to the managed runtime. This
913 * function is often curried with the process name information and then passed
914 * to called functions.
915 *
916 * @param env Managed runtime environment
917 * @param process_name A native representation of the process name
918 * @param managed_process_name A managed representation of the process name
919 * @param msg The error message to be reported
920 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700921[[noreturn]]
922static void ZygoteFailure(JNIEnv* env,
923 const char* process_name,
924 jstring managed_process_name,
925 const std::string& msg) {
926 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
927 if (managed_process_name != nullptr) {
928 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
929 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
930 process_name = scoped_managed_process_name_ptr->c_str();
David Sehrde8d0bd2018-06-22 10:45:36 -0700931 }
932 }
933
Chris Wailesaf594fc2018-11-02 11:00:07 -0700934 const std::string& error_msg =
935 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700936
Chris Wailesaf594fc2018-11-02 11:00:07 -0700937 env->FatalError(error_msg.c_str());
938 __builtin_unreachable();
939}
David Sehrde8d0bd2018-06-22 10:45:36 -0700940
Chris Wailesaa1c9622019-01-10 16:55:32 -0800941/**
942 * A helper method for converting managed strings to native strings. A fatal
943 * error is generated if a problem is encountered in extracting a non-null
944 * string.
945 *
946 * @param env Managed runtime environment
947 * @param process_name A native representation of the process name
948 * @param managed_process_name A managed representation of the process name
949 * @param managed_string The managed string to extract
950 *
951 * @return An empty option if the managed string is null. A optional-wrapped
952 * string otherwise.
953 */
Chris Wailesaf594fc2018-11-02 11:00:07 -0700954static std::optional<std::string> ExtractJString(JNIEnv* env,
955 const char* process_name,
956 jstring managed_process_name,
957 jstring managed_string) {
958 if (managed_string == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -0800959 return std::nullopt;
Chris Wailesaf594fc2018-11-02 11:00:07 -0700960 } else {
961 ScopedUtfChars scoped_string_chars(env, managed_string);
962
963 if (scoped_string_chars.c_str() != nullptr) {
964 return std::optional<std::string>(scoped_string_chars.c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700965 } else {
Chris Wailesaf594fc2018-11-02 11:00:07 -0700966 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700967 }
968 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700969}
970
Chris Wailesaa1c9622019-01-10 16:55:32 -0800971/**
972 * A helper method for converting managed string arrays to native vectors. A
973 * fatal error is generated if a problem is encountered in extracting a non-null array.
974 *
975 * @param env Managed runtime environment
976 * @param process_name A native representation of the process name
977 * @param managed_process_name A managed representation of the process name
978 * @param managed_array The managed integer array to extract
979 *
980 * @return An empty option if the managed array is null. A optional-wrapped
981 * vector otherwise.
982 */
983static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
984 const char* process_name,
985 jstring managed_process_name,
986 jintArray managed_array) {
987 if (managed_array == nullptr) {
988 return std::nullopt;
989 } else {
990 ScopedIntArrayRO managed_array_handle(env, managed_array);
Narayan Kamath973b4662014-03-31 13:41:26 +0100991
Chris Wailesaa1c9622019-01-10 16:55:32 -0800992 if (managed_array_handle.get() != nullptr) {
993 std::vector<int> native_array;
994 native_array.reserve(managed_array_handle.size());
995
996 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
997 native_array.push_back(managed_array_handle[array_index]);
998 }
999
1000 return std::move(native_array);
1001
1002 } else {
1003 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
1004 }
1005 }
1006}
1007
1008/**
Chris Wailesaa1c9622019-01-10 16:55:32 -08001009 * A utility function for blocking signals.
1010 *
1011 * @param signum Signal number to block
1012 * @param fail_fn Fatal error reporting function
1013 *
1014 * @see ZygoteFailure
1015 */
1016static void BlockSignal(int signum, fail_fn_t fail_fn) {
1017 sigset_t sigs;
1018 sigemptyset(&sigs);
1019 sigaddset(&sigs, signum);
1020
1021 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
1022 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
1023 }
1024}
1025
1026
1027/**
1028 * A utility function for unblocking signals.
1029 *
1030 * @param signum Signal number to unblock
1031 * @param fail_fn Fatal error reporting function
1032 *
1033 * @see ZygoteFailure
1034 */
1035static void UnblockSignal(int signum, fail_fn_t fail_fn) {
1036 sigset_t sigs;
1037 sigemptyset(&sigs);
1038 sigaddset(&sigs, signum);
1039
1040 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
1041 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
1042 }
1043}
1044
Chris Wailes7e797b62019-02-22 18:29:22 -08001045static void ClearUsapTable() {
1046 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -08001047 entry.Clear();
1048 }
1049
Chris Wailes7e797b62019-02-22 18:29:22 -08001050 gUsapPoolCount = 0;
Chris Wailesae937142019-01-24 12:57:33 -08001051}
1052
Chris Wailesaa1c9622019-01-10 16:55:32 -08001053// Utility routine to fork a process from the zygote.
1054static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
1055 const std::vector<int>& fds_to_close,
Chris Wailes3d748212019-05-09 17:11:00 -07001056 const std::vector<int>& fds_to_ignore,
1057 bool is_priority_fork) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001058 SetSignalHandlers();
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001059
Chris Wailesaf594fc2018-11-02 11:00:07 -07001060 // Curry a failure function.
1061 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
1062 nullptr, _1);
Andreas Gamped5758f62018-03-12 12:08:55 -07001063
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001064 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
1065 // log, which would result in the logging FDs we close being reopened.
1066 // This would cause failures because the FDs are not whitelisted.
1067 //
1068 // Note that the zygote process is single threaded at this point.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001069 BlockSignal(SIGCHLD, fail_fn);
Narayan Kamathdfcc79e2016-11-07 16:22:48 +00001070
Narayan Kamath3764a262016-08-30 15:36:19 +01001071 // Close any logging related FDs before we start evaluating the list of
1072 // file descriptors.
1073 __android_log_close();
Howard Ro27330412018-10-02 12:08:28 -07001074 stats_log_close();
Narayan Kamath3764a262016-08-30 15:36:19 +01001075
Chris Wailesaf594fc2018-11-02 11:00:07 -07001076 // If this is the first fork for this zygote, create the open FD table. If
1077 // it isn't, we just need to check whether the list of open files has changed
1078 // (and it shouldn't in the normal case).
Chris Wailesaf594fc2018-11-02 11:00:07 -07001079 if (gOpenFdTable == nullptr) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001080 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
1081 } else {
1082 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001083 }
1084
Josh Gaod7951102018-06-26 16:05:12 -07001085 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
1086
Chris Wailes7699d612020-01-28 17:26:56 -08001087 // Purge unused native memory in an attempt to reduce the amount of false
1088 // sharing with the child process. By reducing the size of the libc_malloc
1089 // region shared with the child process we reduce the number of pages that
1090 // transition to the private-dirty state when malloc adjusts the meta-data
1091 // on each of the pages it is managing after the fork.
1092 mallopt(M_PURGE, 0);
1093
Narayan Kamath973b4662014-03-31 13:41:26 +01001094 pid_t pid = fork();
1095
1096 if (pid == 0) {
Chris Wailes3d748212019-05-09 17:11:00 -07001097 if (is_priority_fork) {
1098 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
1099 } else {
1100 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MIN);
1101 }
1102
David Sehrde8d0bd2018-06-22 10:45:36 -07001103 // The child process.
Christopher Ferris76de39e2017-06-20 16:13:40 -07001104 PreApplicationInit();
Christopher Ferrisab16dd12017-05-15 16:50:29 -07001105
Narayan Kamath973b4662014-03-31 13:41:26 +01001106 // Clean up any descriptors which must be closed immediately
Chris Wailesaa1c9622019-01-10 16:55:32 -08001107 DetachDescriptors(env, fds_to_close, fail_fn);
Narayan Kamath973b4662014-03-31 13:41:26 +01001108
Chris Wailes7e797b62019-02-22 18:29:22 -08001109 // Invalidate the entries in the USAP table.
1110 ClearUsapTable();
Chris Wailesae937142019-01-24 12:57:33 -08001111
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001112 // Re-open all remaining open file descriptors so that they aren't shared
1113 // with the zygote across a fork.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001114 gOpenFdTable->ReopenOrDetach(fail_fn);
Josh Gaod7951102018-06-26 16:05:12 -07001115
1116 // Turn fdsan back on.
1117 android_fdsan_set_error_level(fdsan_error_level);
Jing Jie29afc92019-10-29 18:14:49 -07001118
1119 // Reset the fd to the unsolicited zygote socket
1120 gSystemServerSocketFd = -1;
Martin Stjernholma9bd8c32019-02-23 02:35:07 +00001121 } else {
1122 ALOGD("Forked child process %d", pid);
David Sehrde8d0bd2018-06-22 10:45:36 -07001123 }
Narayan Kamathc5f27a72016-08-19 13:45:24 +01001124
David Sehrde8d0bd2018-06-22 10:45:36 -07001125 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001126 UnblockSignal(SIGCHLD, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001127
Narayan Kamath973b4662014-03-31 13:41:26 +01001128 return pid;
1129}
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001130
Ricky Wai4482ab52019-12-10 19:08:18 +00001131// Create an app data directory over tmpfs overlayed CE / DE storage, and bind mount it
1132// from the actual app data directory in data mirror.
1133static void createAndMountAppData(std::string_view package_name,
1134 std::string_view mirror_pkg_dir_name, std::string_view mirror_data_path,
1135 std::string_view actual_data_path, fail_fn_t fail_fn) {
1136
1137 char mirrorAppDataPath[PATH_MAX];
1138 char actualAppDataPath[PATH_MAX];
1139 snprintf(mirrorAppDataPath, PATH_MAX, "%s/%s", mirror_data_path.data(),
1140 mirror_pkg_dir_name.data());
1141 snprintf(actualAppDataPath, PATH_MAX, "%s/%s", actual_data_path.data(), package_name.data());
1142
1143 PrepareDir(actualAppDataPath, 0700, AID_ROOT, AID_ROOT, fail_fn);
1144
1145 // Bind mount from original app data directory in mirror.
1146 BindMount(mirrorAppDataPath, actualAppDataPath, fail_fn);
1147}
1148
1149// Get the directory name stored in /data/data. If device is unlocked it should be the same as
1150// package name, otherwise it will be an encrypted name but with same inode number.
1151static std::string getAppDataDirName(std::string_view parent_path, std::string_view package_name,
1152 long long ce_data_inode, fail_fn_t fail_fn) {
1153 // Check if directory exists
1154 char tmpPath[PATH_MAX];
1155 snprintf(tmpPath, PATH_MAX, "%s/%s", parent_path.data(), package_name.data());
1156 struct stat s;
1157 int err = stat(tmpPath, &s);
1158 if (err == 0) {
1159 // Directory exists, so return the directory name
1160 return package_name.data();
1161 } else {
1162 if (errno != ENOENT) {
1163 fail_fn(CREATE_ERROR("Unexpected error in getAppDataDirName: %s", strerror(errno)));
1164 return nullptr;
1165 }
Ricky Waiffedc572020-01-20 17:07:58 +00001166 {
1167 // Directory doesn't exist, try to search the name from inode
1168 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(parent_path.data()), closedir);
1169 if (dir == nullptr) {
1170 fail_fn(CREATE_ERROR("Failed to opendir %s", parent_path.data()));
1171 }
1172 struct dirent* ent;
1173 while ((ent = readdir(dir.get()))) {
1174 if (ent->d_ino == ce_data_inode) {
1175 return ent->d_name;
1176 }
Ricky Wai4482ab52019-12-10 19:08:18 +00001177 }
1178 }
Ricky Wai4482ab52019-12-10 19:08:18 +00001179
1180 // Fallback due to b/145989852, ce_data_inode stored in package manager may be corrupted
1181 // if ino_t is 32 bits.
1182 ino_t fixed_ce_data_inode = 0;
1183 if ((ce_data_inode & UPPER_HALF_WORD_MASK) == UPPER_HALF_WORD_MASK) {
1184 fixed_ce_data_inode = ce_data_inode & LOWER_HALF_WORD_MASK;
1185 } else if ((ce_data_inode & LOWER_HALF_WORD_MASK) == LOWER_HALF_WORD_MASK) {
1186 fixed_ce_data_inode = ((ce_data_inode >> 32) & LOWER_HALF_WORD_MASK);
1187 }
1188 if (fixed_ce_data_inode != 0) {
Ricky Waiffedc572020-01-20 17:07:58 +00001189 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(parent_path.data()), closedir);
Ricky Wai4482ab52019-12-10 19:08:18 +00001190 if (dir == nullptr) {
1191 fail_fn(CREATE_ERROR("Failed to opendir %s", parent_path.data()));
1192 }
Ricky Waiffedc572020-01-20 17:07:58 +00001193 struct dirent* ent;
1194 while ((ent = readdir(dir.get()))) {
Ricky Wai4482ab52019-12-10 19:08:18 +00001195 if (ent->d_ino == fixed_ce_data_inode) {
1196 long long d_ino = ent->d_ino;
1197 ALOGW("Fallback success inode %lld -> %lld", ce_data_inode, d_ino);
Ricky Wai4482ab52019-12-10 19:08:18 +00001198 return ent->d_name;
1199 }
1200 }
Ricky Wai4482ab52019-12-10 19:08:18 +00001201 }
1202 // Fallback done
1203
1204 fail_fn(CREATE_ERROR("Unable to find %s:%lld in %s", package_name.data(),
1205 ce_data_inode, parent_path.data()));
1206 return nullptr;
1207 }
1208}
1209
1210// Isolate app's data directory, by mounting a tmpfs on CE DE storage,
1211// and create and bind mount app data in related_packages.
1212static void isolateAppDataPerPackage(int userId, std::string_view package_name,
1213 std::string_view volume_uuid, long long ce_data_inode, std::string_view actualCePath,
1214 std::string_view actualDePath, fail_fn_t fail_fn) {
1215
1216 char mirrorCePath[PATH_MAX];
1217 char mirrorDePath[PATH_MAX];
1218 char mirrorCeParent[PATH_MAX];
1219 snprintf(mirrorCeParent, PATH_MAX, "/data_mirror/data_ce/%s", volume_uuid.data());
1220 snprintf(mirrorCePath, PATH_MAX, "%s/%d", mirrorCeParent, userId);
1221 snprintf(mirrorDePath, PATH_MAX, "/data_mirror/data_de/%s/%d", volume_uuid.data(), userId);
1222
1223 createAndMountAppData(package_name, package_name, mirrorDePath, actualDePath, fail_fn);
1224
1225 std::string ce_data_path = getAppDataDirName(mirrorCePath, package_name, ce_data_inode, fail_fn);
1226 createAndMountAppData(package_name, ce_data_path, mirrorCePath, actualCePath, fail_fn);
1227}
1228
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001229// Relabel directory
1230static void relabelDir(const char* path, security_context_t context, fail_fn_t fail_fn) {
1231 if (setfilecon(path, context) != 0) {
1232 fail_fn(CREATE_ERROR("Failed to setfilecon %s %s", path, strerror(errno)));
1233 }
1234}
1235
1236// Relabel all directories under a path non-recursively.
1237static void relabelAllDirs(const char* path, security_context_t context, fail_fn_t fail_fn) {
1238 DIR* dir = opendir(path);
1239 if (dir == nullptr) {
1240 fail_fn(CREATE_ERROR("Failed to opendir %s", path));
1241 }
1242 struct dirent* ent;
1243 while ((ent = readdir(dir))) {
1244 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1245 auto filePath = StringPrintf("%s/%s", path, ent->d_name);
1246 if (ent->d_type == DT_DIR) {
1247 relabelDir(filePath.c_str(), context, fail_fn);
1248 } else if (ent->d_type == DT_LNK) {
1249 if (lsetfilecon(filePath.c_str(), context) != 0) {
1250 fail_fn(CREATE_ERROR("Failed to lsetfilecon %s %s", filePath.c_str(), strerror(errno)));
1251 }
1252 } else {
1253 fail_fn(CREATE_ERROR("Unexpected type: %d %s", ent->d_type, filePath.c_str()));
1254 }
1255 }
1256 closedir(dir);
1257}
1258
Ricky Wai4482ab52019-12-10 19:08:18 +00001259/**
1260 * Make other apps data directory not visible in CE, DE storage.
1261 *
1262 * Apps without app data isolation can detect if another app is installed on system,
1263 * by "touching" other apps data directory like /data/data/com.whatsapp, if it returns
1264 * "Permission denied" it means apps installed, otherwise it returns "File not found".
1265 * Traditional file permissions or SELinux can only block accessing those directories but
1266 * can't fix fingerprinting like this.
1267 * We fix it by "overlaying" data directory, and only relevant app data packages exists
1268 * in data directories.
1269 *
1270 * Steps:
1271 * 1). Collect a list of all related apps (apps with same uid and whitelisted apps) data info
1272 * (package name, data stored volume uuid, and inode number of its CE data directory)
1273 * 2). Mount tmpfs on /data/data, /data/user(_de) and /mnt/expand, so apps no longer
1274 * able to access apps data directly.
1275 * 3). For each related app, create its app data directory and bind mount the actual content
1276 * from apps data mirror directory. This works on both CE and DE storage, as DE storage
1277 * is always available even storage is FBE locked, while we use inode number to find
1278 * the encrypted DE directory in mirror so we can still bind mount it successfully.
1279 *
1280 * Example:
1281 * 0). Assuming com.android.foo CE data is stored in /data/data and no shared uid
1282 * 1). Mount a tmpfs on /data/data, /data/user, /data/user_de, /mnt/expand
1283 * List = ["com.android.foo", "null" (volume uuid "null"=default),
1284 * 123456 (inode number)]
1285 * 2). On DE storage, we create a directory /data/user_de/0/com.com.android.foo, and bind
1286 * mount (in the app's mount namespace) it from /data_mirror/data_de/0/com.android.foo.
1287 * 3). We do similar for CE storage. But in direct boot mode, as /data_mirror/data_ce/0/ is
1288 * encrypted, we can't find a directory with name com.android.foo on it, so we will
1289 * use the inode number to find the right directory instead, which that directory content will
1290 * be decrypted after storage is decrypted.
1291 *
1292 */
1293static void isolateAppData(JNIEnv* env, jobjectArray pkg_data_info_list,
1294 uid_t uid, const char* process_name, jstring managed_nice_name,
1295 fail_fn_t fail_fn) {
1296
1297 const userid_t userId = multiuser_get_user_id(uid);
1298
1299 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
1300
1301 int size = (pkg_data_info_list != nullptr) ? env->GetArrayLength(pkg_data_info_list) : 0;
1302 // Size should be a multiple of 3, as it contains list of <package_name, volume_uuid, inode>
1303 if ((size % 3) != 0) {
1304 fail_fn(CREATE_ERROR("Wrong pkg_inode_list size %d", size));
1305 }
1306
1307 // Mount tmpfs on all possible data directories, so app no longer see the original apps data.
1308 char internalCePath[PATH_MAX];
1309 char internalLegacyCePath[PATH_MAX];
1310 char internalDePath[PATH_MAX];
1311 char externalPrivateMountPath[PATH_MAX];
1312
1313 snprintf(internalCePath, PATH_MAX, "/data/user");
1314 snprintf(internalLegacyCePath, PATH_MAX, "/data/data");
1315 snprintf(internalDePath, PATH_MAX, "/data/user_de");
1316 snprintf(externalPrivateMountPath, PATH_MAX, "/mnt/expand");
1317
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001318 security_context_t dataDataContext = nullptr;
1319 if (getfilecon(internalDePath, &dataDataContext) < 0) {
1320 fail_fn(CREATE_ERROR("Unable to getfilecon on %s %s", internalDePath,
1321 strerror(errno)));
1322 }
1323
Ricky Wai4482ab52019-12-10 19:08:18 +00001324 MountAppDataTmpFs(internalLegacyCePath, fail_fn);
1325 MountAppDataTmpFs(internalCePath, fail_fn);
1326 MountAppDataTmpFs(internalDePath, fail_fn);
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001327
1328 // Mount tmpfs on all external vols DE and CE storage
1329 DIR* dir = opendir(externalPrivateMountPath);
1330 if (dir == nullptr) {
1331 fail_fn(CREATE_ERROR("Failed to opendir %s", externalPrivateMountPath));
1332 }
1333 struct dirent* ent;
1334 while ((ent = readdir(dir))) {
1335 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1336 if (ent->d_type != DT_DIR) {
1337 fail_fn(CREATE_ERROR("Unexpected type: %d %s", ent->d_type, ent->d_name));
1338 }
1339 auto volPath = StringPrintf("%s/%s", externalPrivateMountPath, ent->d_name);
1340 auto cePath = StringPrintf("%s/user", volPath.c_str());
1341 auto dePath = StringPrintf("%s/user_de", volPath.c_str());
1342 MountAppDataTmpFs(cePath.c_str(), fail_fn);
1343 MountAppDataTmpFs(dePath.c_str(), fail_fn);
1344 }
1345 closedir(dir);
1346
1347 bool legacySymlinkCreated = false;
Ricky Wai4482ab52019-12-10 19:08:18 +00001348
1349 for (int i = 0; i < size; i += 3) {
1350 jstring package_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i));
1351 std::string packageName = extract_fn(package_str).value();
1352
1353 jstring vol_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i + 1));
1354 std::string volUuid = extract_fn(vol_str).value();
1355
1356 jstring inode_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i + 2));
1357 std::string inode = extract_fn(inode_str).value();
1358 std::string::size_type sz;
1359 long long ceDataInode = std::stoll(inode, &sz);
1360
1361 std::string actualCePath, actualDePath;
1362 if (volUuid.compare("null") != 0) {
1363 // Volume that is stored in /mnt/expand
1364 char volPath[PATH_MAX];
1365 char volCePath[PATH_MAX];
1366 char volDePath[PATH_MAX];
1367 char volCeUserPath[PATH_MAX];
1368 char volDeUserPath[PATH_MAX];
1369
1370 snprintf(volPath, PATH_MAX, "/mnt/expand/%s", volUuid.c_str());
1371 snprintf(volCePath, PATH_MAX, "%s/user", volPath);
1372 snprintf(volDePath, PATH_MAX, "%s/user_de", volPath);
1373 snprintf(volCeUserPath, PATH_MAX, "%s/%d", volCePath, userId);
1374 snprintf(volDeUserPath, PATH_MAX, "%s/%d", volDePath, userId);
1375
1376 PrepareDirIfNotPresent(volPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1377 PrepareDirIfNotPresent(volCePath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1378 PrepareDirIfNotPresent(volDePath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1379 PrepareDirIfNotPresent(volCeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1380 fail_fn);
1381 PrepareDirIfNotPresent(volDeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1382 fail_fn);
1383
1384 actualCePath = volCeUserPath;
1385 actualDePath = volDeUserPath;
1386 } else {
1387 // Internal volume that stored in /data
1388 char internalCeUserPath[PATH_MAX];
1389 char internalDeUserPath[PATH_MAX];
1390 snprintf(internalCeUserPath, PATH_MAX, "/data/user/%d", userId);
1391 snprintf(internalDeUserPath, PATH_MAX, "/data/user_de/%d", userId);
1392 // If it's user 0, create a symlink /data/user/0 -> /data/data,
1393 // otherwise create /data/user/$USER
1394 if (userId == 0) {
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001395 if (!legacySymlinkCreated) {
1396 legacySymlinkCreated = true;
1397 int result = symlink(internalLegacyCePath, internalCeUserPath);
1398 if (result != 0) {
1399 fail_fn(CREATE_ERROR("Failed to create symlink %s %s", internalCeUserPath,
1400 strerror(errno)));
1401 }
1402 }
Ricky Wai4482ab52019-12-10 19:08:18 +00001403 actualCePath = internalLegacyCePath;
1404 } else {
1405 PrepareDirIfNotPresent(internalCeUserPath, DEFAULT_DATA_DIR_PERMISSION,
1406 AID_ROOT, AID_ROOT, fail_fn);
1407 actualCePath = internalCeUserPath;
1408 }
1409 PrepareDirIfNotPresent(internalDeUserPath, DEFAULT_DATA_DIR_PERMISSION,
1410 AID_ROOT, AID_ROOT, fail_fn);
1411 actualDePath = internalDeUserPath;
1412 }
1413 isolateAppDataPerPackage(userId, packageName, volUuid, ceDataInode,
1414 actualCePath, actualDePath, fail_fn);
1415 }
Ricky Waid2eb1ff2020-01-09 18:35:38 +00001416 // We set the label AFTER everything is done, as we are applying
1417 // the file operations on tmpfs. If we set the label when we mount
1418 // tmpfs, SELinux will not happy as we are changing system_data_files.
1419 // Relabel dir under /data/user, including /data/user/0
1420 relabelAllDirs(internalCePath, dataDataContext, fail_fn);
1421
1422 // Relabel /data/user
1423 relabelDir(internalCePath, dataDataContext, fail_fn);
1424
1425 // Relabel /data/data
1426 relabelDir(internalLegacyCePath, dataDataContext, fail_fn);
1427
1428 // Relabel dir under /data/user_de
1429 relabelAllDirs(internalDePath, dataDataContext, fail_fn);
1430
1431 // Relabel /data/user_de
1432 relabelDir(internalDePath, dataDataContext, fail_fn);
1433
1434 // Relabel CE and DE dirs under /mnt/expand
1435 dir = opendir(externalPrivateMountPath);
1436 if (dir == nullptr) {
1437 fail_fn(CREATE_ERROR("Failed to opendir %s", externalPrivateMountPath));
1438 }
1439 while ((ent = readdir(dir))) {
1440 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1441 auto volPath = StringPrintf("%s/%s", externalPrivateMountPath, ent->d_name);
1442 auto cePath = StringPrintf("%s/user", volPath.c_str());
1443 auto dePath = StringPrintf("%s/user_de", volPath.c_str());
1444
1445 relabelAllDirs(cePath.c_str(), dataDataContext, fail_fn);
1446 relabelDir(cePath.c_str(), dataDataContext, fail_fn);
1447 relabelAllDirs(dePath.c_str(), dataDataContext, fail_fn);
1448 relabelDir(dePath.c_str(), dataDataContext, fail_fn);
1449 }
1450 closedir(dir);
1451
1452 freecon(dataDataContext);
Ricky Wai4482ab52019-12-10 19:08:18 +00001453}
1454
Ricky Waiba4325f2019-12-02 16:32:58 +00001455/**
1456 * Like isolateAppData(), isolate jit profile directories, so apps don't see what
1457 * other apps are installed by reading content inside /data/misc/profiles/cur.
1458 *
1459 * The implementation is similar to isolateAppData(), it creates a tmpfs
1460 * on /data/misc/profiles/cur, and bind mounts related package profiles to it.
1461 */
1462static void isolateJitProfile(JNIEnv* env, jobjectArray pkg_data_info_list,
1463 uid_t uid, const char* process_name, jstring managed_nice_name,
1464 fail_fn_t fail_fn) {
1465
1466 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
1467 const userid_t user_id = multiuser_get_user_id(uid);
1468
1469 int size = (pkg_data_info_list != nullptr) ? env->GetArrayLength(pkg_data_info_list) : 0;
1470 // Size should be a multiple of 3, as it contains list of <package_name, volume_uuid, inode>
1471 if ((size % 3) != 0) {
1472 fail_fn(CREATE_ERROR("Wrong pkg_inode_list size %d", size));
1473 }
1474
1475 // Mount (namespace) tmpfs on profile directory, so apps no longer access
1476 // the original profile directory anymore.
1477 MountAppDataTmpFs(kCurProfileDirPath, fail_fn);
1478
1479 // Create profile directory for this user.
1480 std::string actualCurUserProfile = StringPrintf("%s/%d", kCurProfileDirPath, user_id);
Greg Kaiser4a966702020-01-21 06:41:29 -08001481 PrepareDir(actualCurUserProfile, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
Ricky Waiba4325f2019-12-02 16:32:58 +00001482
1483 for (int i = 0; i < size; i += 3) {
1484 jstring package_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i));
1485 std::string packageName = extract_fn(package_str).value();
1486
1487 std::string actualCurPackageProfile = StringPrintf("%s/%s", actualCurUserProfile.c_str(),
1488 packageName.c_str());
1489 std::string mirrorCurPackageProfile = StringPrintf("/data_mirror/cur_profiles/%d/%s",
1490 user_id, packageName.c_str());
1491
1492 PrepareDir(actualCurPackageProfile, DEFAULT_DATA_DIR_PERMISSION, uid, uid, fail_fn);
1493 BindMount(mirrorCurPackageProfile, actualCurPackageProfile, fail_fn);
1494 }
1495}
1496
Chris Wailesaf594fc2018-11-02 11:00:07 -07001497// Utility routine to specialize a zygote child process.
1498static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
1499 jint runtime_flags, jobjectArray rlimits,
1500 jlong permitted_capabilities, jlong effective_capabilities,
1501 jint mount_external, jstring managed_se_info,
1502 jstring managed_nice_name, bool is_system_server,
1503 bool is_child_zygote, jstring managed_instruction_set,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001504 jstring managed_app_data_dir, bool is_top_app,
1505 jobjectArray pkg_data_info_list) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001506 const char* process_name = is_system_server ? "system_server" : "zygote";
1507 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
1508 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001509
1510 auto se_info = extract_fn(managed_se_info);
1511 auto nice_name = extract_fn(managed_nice_name);
1512 auto instruction_set = extract_fn(managed_instruction_set);
1513 auto app_data_dir = extract_fn(managed_app_data_dir);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001514
Chris Wailesaf594fc2018-11-02 11:00:07 -07001515 // Keep capabilities across UID change, unless we're staying root.
1516 if (uid != 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001517 EnableKeepCapabilities(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001518 }
1519
Chris Wailesaa1c9622019-01-10 16:55:32 -08001520 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001521
Chris Wailesaa1c9622019-01-10 16:55:32 -08001522 DropCapabilitiesBoundingSet(fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001523
Lev Rumyantsev2b7a5ea2019-12-13 16:03:30 -08001524 bool need_pre_initialize_native_bridge =
1525 !is_system_server &&
1526 instruction_set.has_value() &&
1527 android::NativeBridgeAvailable() &&
1528 // Native bridge may be already initialized if this
1529 // is an app forked from app-zygote.
1530 !android::NativeBridgeInitialized() &&
1531 android::NeedsNativeBridge(instruction_set.value().c_str());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001532
Lev Rumyantsev2b7a5ea2019-12-13 16:03:30 -08001533 MountEmulatedStorage(uid, mount_external, need_pre_initialize_native_bridge, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001534
Ricky Wai4482ab52019-12-10 19:08:18 +00001535 // System services, isolated process, webview/app zygote, old target sdk app, should
1536 // give a null in same_uid_pkgs and private_volumes so they don't need app data isolation.
1537 // Isolated process / webview / app zygote should be gated by SELinux and file permission
1538 // so they can't even traverse CE / DE directories.
1539 if (pkg_data_info_list != nullptr
Ricky Wai19889422020-01-15 01:59:00 +00001540 && GetBoolProperty(ANDROID_APP_DATA_ISOLATION_ENABLED_PROPERTY, true)) {
Ricky Waiba4325f2019-12-02 16:32:58 +00001541 isolateAppData(env, pkg_data_info_list, uid, process_name, managed_nice_name, fail_fn);
1542 isolateJitProfile(env, pkg_data_info_list, uid, process_name, managed_nice_name, fail_fn);
Ricky Wai4482ab52019-12-10 19:08:18 +00001543 }
1544
Chris Wailesaf594fc2018-11-02 11:00:07 -07001545 // If this zygote isn't root, it won't be able to create a process group,
1546 // since the directory is owned by root.
1547 if (!is_system_server && getuid() == 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001548 const int rc = createProcessGroup(uid, getpid());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001549 if (rc == -EROFS) {
1550 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
1551 } else if (rc != 0) {
1552 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
1553 }
1554 }
1555
Chris Wailesaa1c9622019-01-10 16:55:32 -08001556 SetGids(env, gids, fail_fn);
1557 SetRLimits(env, rlimits, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001558
Lev Rumyantsev2b7a5ea2019-12-13 16:03:30 -08001559 if (need_pre_initialize_native_bridge) {
1560 // Due to the logic behind need_pre_initialize_native_bridge we know that
1561 // instruction_set contains a value.
1562 android::PreInitializeNativeBridge(
1563 app_data_dir.has_value() ? app_data_dir.value().c_str() : nullptr,
1564 instruction_set.value().c_str());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001565 }
1566
1567 if (setresgid(gid, gid, gid) == -1) {
1568 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
1569 }
1570
1571 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
1572 // before changing uid from 0, which clears capabilities. The other
1573 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
1574 // breaks SELinux domain transition (see b/71859146). As the result,
1575 // privileged syscalls used below still need to be accessible in app process.
Martijn Coenen86f08a52019-01-03 16:23:01 +01001576 SetUpSeccompFilter(uid, is_child_zygote);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001577
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001578 // Must be called before losing the permission to set scheduler policy.
1579 SetSchedulerPolicy(fail_fn, is_top_app);
1580
Chris Wailesaf594fc2018-11-02 11:00:07 -07001581 if (setresuid(uid, uid, uid) == -1) {
1582 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1583 }
1584
1585 // The "dumpable" flag of a process, which controls core dump generation, is
1586 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1587 // user or group ID changes. See proc(5) for possible values. In most cases,
1588 // the value is 0, so core dumps are disabled for zygote children. However,
1589 // when running in a Chrome OS container, the value is already set to 2,
1590 // which allows the external crash reporter to collect all core dumps. Since
1591 // only system crashes are interested, core dump is disabled for app
1592 // processes. This also ensures compliance with CTS.
1593 int dumpable = prctl(PR_GET_DUMPABLE);
1594 if (dumpable == -1) {
1595 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1596 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1597 }
1598
1599 if (dumpable == 2 && uid >= AID_APP) {
1600 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1601 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1602 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1603 }
1604 }
1605
Orion Hodson8d005a62018-12-05 12:28:53 +00001606 // Set process properties to enable debugging if required.
1607 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1608 EnableDebugger();
1609 }
Yabin Cui4d8546d2019-01-29 16:29:20 -08001610 if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
1611 // simpleperf needs the process to be dumpable to profile it.
1612 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
1613 ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
1614 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
1615 }
1616 }
Orion Hodson8d005a62018-12-05 12:28:53 +00001617
Chris Wailesaf594fc2018-11-02 11:00:07 -07001618 if (NeedsNoRandomizeWorkaround()) {
1619 // Work around ARM kernel ASLR lossage (http://b/5817320).
1620 int old_personality = personality(0xffffffff);
1621 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1622 if (new_personality == -1) {
1623 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1624 }
1625 }
1626
Chris Wailesaa1c9622019-01-10 16:55:32 -08001627 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001628
Mathieu Chartier0bccbf72019-01-30 15:56:17 -08001629 __android_log_close();
1630 stats_log_close();
1631
Chris Wailesaf594fc2018-11-02 11:00:07 -07001632 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1633 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1634
1635 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1636 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1637 uid, is_system_server, se_info_ptr, nice_name_ptr));
1638 }
1639
1640 // Make it easier to debug audit logs by setting the main thread's name to the
1641 // nice name rather than "app_process".
1642 if (nice_name.has_value()) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001643 SetThreadName(nice_name.value());
Chris Wailesaf594fc2018-11-02 11:00:07 -07001644 } else if (is_system_server) {
1645 SetThreadName("system_server");
1646 }
1647
1648 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1649 UnsetChldSignalHandler();
1650
1651 if (is_system_server) {
Mathieu Chartier2cb0a4d2019-11-21 14:30:03 -08001652 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks, runtime_flags);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001653 if (env->ExceptionCheck()) {
1654 fail_fn("Error calling post fork system server hooks.");
1655 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08001656
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07001657 // Prefetch the classloader for the system server. This is done early to
1658 // allow a tie-down of the proper system server selinux domain.
1659 env->CallStaticVoidMethod(gZygoteInitClass, gCreateSystemServerClassLoader);
1660 if (env->ExceptionCheck()) {
1661 // Be robust here. The Java code will attempt to create the classloader
1662 // at a later point (but may not have rights to use AoT artifacts).
1663 env->ExceptionClear();
1664 }
1665
Chris Wailesaf594fc2018-11-02 11:00:07 -07001666 // TODO(oth): Remove hardcoded label here (b/117874058).
1667 static const char* kSystemServerLabel = "u:r:system_server:s0";
1668 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1669 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1670 }
1671 }
1672
Jing Jie29afc92019-10-29 18:14:49 -07001673 if (is_child_zygote) {
1674 initUnsolSocketToSystemServer();
1675 }
1676
Chris Wailesaf594fc2018-11-02 11:00:07 -07001677 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1678 is_system_server, is_child_zygote, managed_instruction_set);
1679
Chris Wailes3d748212019-05-09 17:11:00 -07001680 // Reset the process priority to the default value.
1681 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_DEFAULT);
1682
Chris Wailesaf594fc2018-11-02 11:00:07 -07001683 if (env->ExceptionCheck()) {
1684 fail_fn("Error calling post fork hooks.");
1685 }
1686}
1687
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001688static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1689 __user_cap_header_struct capheader;
1690 memset(&capheader, 0, sizeof(capheader));
1691 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1692 capheader.pid = 0;
1693
1694 __user_cap_data_struct capdata[2];
1695 if (capget(&capheader, &capdata[0]) == -1) {
1696 ALOGE("capget failed: %s", strerror(errno));
1697 RuntimeAbort(env, __LINE__, "capget failed");
1698 }
1699
Chris Wailesaf594fc2018-11-02 11:00:07 -07001700 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1701}
1702
1703static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1704 bool is_child_zygote) {
1705 jlong capabilities = 0;
1706
1707 /*
1708 * Grant the following capabilities to the Bluetooth user:
1709 * - CAP_WAKE_ALARM
Nitin Shivpure99cec9d2019-05-29 14:02:49 +05301710 * - CAP_NET_ADMIN
Chris Wailesaf594fc2018-11-02 11:00:07 -07001711 * - CAP_NET_RAW
1712 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1713 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1714 */
1715
1716 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1717 capabilities |= (1LL << CAP_WAKE_ALARM);
Nitin Shivpure99cec9d2019-05-29 14:02:49 +05301718 capabilities |= (1LL << CAP_NET_ADMIN);
Chris Wailesaf594fc2018-11-02 11:00:07 -07001719 capabilities |= (1LL << CAP_NET_RAW);
1720 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1721 capabilities |= (1LL << CAP_SYS_NICE);
1722 }
1723
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001724 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1725 capabilities |= (1LL << CAP_NET_ADMIN);
1726 capabilities |= (1LL << CAP_NET_BROADCAST);
1727 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1728 capabilities |= (1LL << CAP_NET_RAW);
1729 }
1730
Chris Wailesaf594fc2018-11-02 11:00:07 -07001731 /*
1732 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1733 */
1734
1735 bool gid_wakelock_found = false;
1736 if (gid == AID_WAKELOCK) {
1737 gid_wakelock_found = true;
1738 } else if (gids != nullptr) {
1739 jsize gids_num = env->GetArrayLength(gids);
1740 ScopedIntArrayRO native_gid_proxy(env, gids);
1741
1742 if (native_gid_proxy.get() == nullptr) {
1743 RuntimeAbort(env, __LINE__, "Bad gids array");
1744 }
1745
Chris Wailes31c52c92019-02-14 11:20:02 -08001746 for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
1747 if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001748 gid_wakelock_found = true;
1749 break;
1750 }
1751 }
1752 }
1753
1754 if (gid_wakelock_found) {
1755 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1756 }
1757
1758 /*
1759 * Grant child Zygote processes the following capabilities:
1760 * - CAP_SETUID (change UID of child processes)
1761 * - CAP_SETGID (change GID of child processes)
1762 * - CAP_SETPCAP (change capabilities of child processes)
1763 */
1764
1765 if (is_child_zygote) {
1766 capabilities |= (1LL << CAP_SETUID);
1767 capabilities |= (1LL << CAP_SETGID);
1768 capabilities |= (1LL << CAP_SETPCAP);
1769 }
1770
1771 /*
1772 * Containers run without some capabilities, so drop any caps that are not
1773 * available.
1774 */
1775
1776 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001777}
Chris Wailesaa1c9622019-01-10 16:55:32 -08001778
1779/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001780 * Adds the given information about a newly created unspecialized app
1781 * processes to the Zygote's USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001782 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001783 * @param usap_pid Process ID of the newly created USAP
1784 * @param read_pipe_fd File descriptor for the read end of the USAP
1785 * reporting pipe. Used in the ZygoteServer poll loop to track USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08001786 * specialization.
1787 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001788static void AddUsapTableEntry(pid_t usap_pid, int read_pipe_fd) {
1789 static int sUsapTableInsertIndex = 0;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001790
Chris Wailes7e797b62019-02-22 18:29:22 -08001791 int search_index = sUsapTableInsertIndex;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001792
1793 do {
Chris Wailes7e797b62019-02-22 18:29:22 -08001794 if (gUsapTable[search_index].SetIfInvalid(usap_pid, read_pipe_fd)) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001795 // Start our next search right after where we finished this one.
Chris Wailes7e797b62019-02-22 18:29:22 -08001796 sUsapTableInsertIndex = (search_index + 1) % gUsapTable.size();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001797
1798 return;
1799 }
1800
Chris Wailes7e797b62019-02-22 18:29:22 -08001801 search_index = (search_index + 1) % gUsapTable.size();
1802 } while (search_index != sUsapTableInsertIndex);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001803
1804 // Much like money in the banana stand, there should always be an entry
Chris Wailes7e797b62019-02-22 18:29:22 -08001805 // in the USAP table.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001806 __builtin_unreachable();
1807}
1808
1809/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001810 * Invalidates the entry in the USAPTable corresponding to the provided
1811 * process ID if it is present. If an entry was removed the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08001812 * count is decremented.
1813 *
Chris Wailes7e797b62019-02-22 18:29:22 -08001814 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08001815 * @return True if an entry was invalidated; false otherwise
1816 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001817static bool RemoveUsapTableEntry(pid_t usap_pid) {
1818 for (UsapTableEntry& entry : gUsapTable) {
1819 if (entry.ClearForPID(usap_pid)) {
1820 --gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08001821 return true;
1822 }
1823 }
1824
1825 return false;
1826}
1827
1828/**
Chris Wailes7e797b62019-02-22 18:29:22 -08001829 * @return A vector of the read pipe FDs for each of the active USAPs.
Chris Wailesaa1c9622019-01-10 16:55:32 -08001830 */
Chris Wailes7e797b62019-02-22 18:29:22 -08001831std::vector<int> MakeUsapPipeReadFDVector() {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001832 std::vector<int> fd_vec;
Chris Wailes7e797b62019-02-22 18:29:22 -08001833 fd_vec.reserve(gUsapTable.size());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001834
Chris Wailes7e797b62019-02-22 18:29:22 -08001835 for (UsapTableEntry& entry : gUsapTable) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08001836 auto entry_values = entry.GetValues();
1837
1838 if (entry_values.has_value()) {
1839 fd_vec.push_back(entry_values.value().read_pipe_fd);
1840 }
1841 }
1842
1843 return fd_vec;
1844}
1845
Chris Wailes6d482d542019-04-03 13:00:52 -07001846static void UnmountStorageOnInit(JNIEnv* env) {
1847 // Zygote process unmount root storage space initially before every child processes are forked.
1848 // Every forked child processes (include SystemServer) only mount their own root storage space
1849 // and no need unmount storage operation in MountEmulatedStorage method.
1850 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1851
1852 // See storage config details at http://source.android.com/tech/storage/
1853 // Create private mount namespace shared by all children
1854 if (unshare(CLONE_NEWNS) == -1) {
1855 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1856 return;
1857 }
1858
1859 // Mark rootfs as being a slave so that changes from default
1860 // namespace only flow into our children.
1861 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1862 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1863 return;
1864 }
1865
1866 // Create a staging tmpfs that is shared by our children; they will
1867 // bind mount storage into their respective private namespaces, which
1868 // are isolated from each other.
1869 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1870 if (target_base != nullptr) {
1871#define STRINGIFY_UID(x) __STRING(x)
1872 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1873 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1874 ALOGE("Failed to mount tmpfs to %s", target_base);
1875 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1876 return;
1877 }
1878#undef STRINGIFY_UID
1879 }
1880
1881 UnmountTree("/storage");
1882}
1883
Chris Wailesff8d4e72019-04-10 17:49:24 -07001884static int DisableExecuteOnly(struct dl_phdr_info* info,
1885 size_t size [[maybe_unused]],
1886 void* data [[maybe_unused]]) {
1887 // Search for any execute-only segments and mark them read+execute.
1888 for (int i = 0; i < info->dlpi_phnum; i++) {
Nick Desaulniersa9940c22019-12-11 15:33:39 -08001889 const auto& phdr = info->dlpi_phdr[i];
1890 if ((phdr.p_type == PT_LOAD) && (phdr.p_flags == PF_X)) {
1891 auto addr = reinterpret_cast<void*>(info->dlpi_addr + PAGE_START(phdr.p_vaddr));
1892 size_t len = PAGE_OFFSET(phdr.p_vaddr) + phdr.p_memsz;
1893 if (mprotect(addr, len, PROT_READ | PROT_EXEC) == -1) {
1894 ALOGE("mprotect(%p, %zu, PROT_READ | PROT_EXEC) failed: %m", addr, len);
1895 return -1;
1896 }
Chris Wailesff8d4e72019-04-10 17:49:24 -07001897 }
1898 }
1899 // Return non-zero to exit dl_iterate_phdr.
1900 return 0;
1901}
1902
Narayan Kamath973b4662014-03-31 13:41:26 +01001903} // anonymous namespace
1904
1905namespace android {
1906
Christopher Ferris76de39e2017-06-20 16:13:40 -07001907static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1908 PreApplicationInit();
1909}
1910
Narayan Kamath973b4662014-03-31 13:41:26 +01001911static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1912 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001913 jint runtime_flags, jobjectArray rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001914 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001915 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001916 jstring instruction_set, jstring app_data_dir, jboolean is_top_app,
1917 jobjectArray pkg_data_info_list) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07001918 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001919
Chris Wailesaa1c9622019-01-10 16:55:32 -08001920 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1921 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1922 }
1923
1924 std::vector<int> fds_to_close =
1925 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1926 std::vector<int> fds_to_ignore =
1927 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1928 .value_or(std::vector<int>());
1929
Chris Wailes7e797b62019-02-22 18:29:22 -08001930 std::vector<int> usap_pipes = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08001931
Chris Wailes7e797b62019-02-22 18:29:22 -08001932 fds_to_close.insert(fds_to_close.end(), usap_pipes.begin(), usap_pipes.end());
1933 fds_to_ignore.insert(fds_to_ignore.end(), usap_pipes.begin(), usap_pipes.end());
Chris Wailesaa1c9622019-01-10 16:55:32 -08001934
Chris Wailes7e797b62019-02-22 18:29:22 -08001935 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001936
Chris Wailes7e797b62019-02-22 18:29:22 -08001937 if (gUsapPoolEventFD != -1) {
1938 fds_to_close.push_back(gUsapPoolEventFD);
1939 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001940 }
1941
Jing Jie29afc92019-10-29 18:14:49 -07001942 if (gSystemServerSocketFd != -1) {
1943 fds_to_close.push_back(gSystemServerSocketFd);
1944 fds_to_ignore.push_back(gSystemServerSocketFd);
1945 }
1946
Chris Wailes3d748212019-05-09 17:11:00 -07001947 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore, true);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001948
David Sehrde8d0bd2018-06-22 10:45:36 -07001949 if (pid == 0) {
1950 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1951 capabilities, capabilities,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001952 mount_external, se_info, nice_name, false,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06001953 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001954 is_top_app == JNI_TRUE, pkg_data_info_list);
David Sehrde8d0bd2018-06-22 10:45:36 -07001955 }
1956 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001957}
1958
1959static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1960 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001961 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1962 jlong effective_capabilities) {
Chris Wailes7e797b62019-02-22 18:29:22 -08001963 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08001964 fds_to_ignore(fds_to_close);
1965
Chris Wailes7e797b62019-02-22 18:29:22 -08001966 fds_to_close.push_back(gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001967
Chris Wailes7e797b62019-02-22 18:29:22 -08001968 if (gUsapPoolEventFD != -1) {
1969 fds_to_close.push_back(gUsapPoolEventFD);
1970 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08001971 }
1972
Jing Jie29afc92019-10-29 18:14:49 -07001973 if (gSystemServerSocketFd != -1) {
1974 fds_to_close.push_back(gSystemServerSocketFd);
1975 fds_to_ignore.push_back(gSystemServerSocketFd);
1976 }
1977
Chris Wailesaf594fc2018-11-02 11:00:07 -07001978 pid_t pid = ForkCommon(env, true,
Chris Wailesaa1c9622019-01-10 16:55:32 -08001979 fds_to_close,
Chris Wailes3d748212019-05-09 17:11:00 -07001980 fds_to_ignore,
1981 true);
David Sehrde8d0bd2018-06-22 10:45:36 -07001982 if (pid == 0) {
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001983 // System server prcoess does not need data isolation so no need to
1984 // know pkg_data_info_list.
David Sehrde8d0bd2018-06-22 10:45:36 -07001985 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesaf594fc2018-11-02 11:00:07 -07001986 permitted_capabilities, effective_capabilities,
1987 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00001988 false, nullptr, nullptr, /* is_top_app= */ false,
1989 /* pkg_data_info_list */ nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001990 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001991 // The zygote process checks whether the child process has died or not.
1992 ALOGI("System server process %d has been created", pid);
1993 gSystemServerPid = pid;
1994 // There is a slight window that the system server process has crashed
1995 // but it went unnoticed because we haven't published its pid yet. So
1996 // we recheck here just to make sure that all is well.
1997 int status;
1998 if (waitpid(pid, &status, WNOHANG) == pid) {
1999 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08002000 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01002001 }
Carmen Jacksondd401252017-02-23 15:21:10 -08002002
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08002003 if (UsePerAppMemcg()) {
Minchan Kim5fa8af22018-06-27 11:32:40 +09002004 // Assign system_server to the correct memory cgroup.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08002005 // Not all devices mount memcg so check if it is mounted first
Minchan Kim5fa8af22018-06-27 11:32:40 +09002006 // to avoid unnecessarily printing errors and denials in the logs.
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -08002007 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
2008 ALOGE("couldn't add process %d into system memcg group", pid);
Minchan Kim5fa8af22018-06-27 11:32:40 +09002009 }
Carmen Jacksondd401252017-02-23 15:21:10 -08002010 }
Narayan Kamath973b4662014-03-31 13:41:26 +01002011 }
2012 return pid;
2013}
2014
Chris Wailesaa1c9622019-01-10 16:55:32 -08002015/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002016 * A JNI function that forks an unspecialized app process from the Zygote while
2017 * ensuring proper file descriptor hygiene.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002018 *
2019 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08002020 * @param read_pipe_fd The read FD for the USAP reporting pipe. Manually closed by blastlas
Chris Wailesaa1c9622019-01-10 16:55:32 -08002021 * in managed code.
Chris Wailes7e797b62019-02-22 18:29:22 -08002022 * @param write_pipe_fd The write FD for the USAP reporting pipe. Manually closed by the
Chris Wailesaa1c9622019-01-10 16:55:32 -08002023 * zygote in managed code.
2024 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
Chris Wailes7e797b62019-02-22 18:29:22 -08002025 * the FD hygiene code and automatically "closed" in the new USAP.
Chris Wailes3d748212019-05-09 17:11:00 -07002026 * @param is_priority_fork Controls the nice level assigned to the newly created process
Chris Wailesaa1c9622019-01-10 16:55:32 -08002027 * @return
2028 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002029static jint com_android_internal_os_Zygote_nativeForkUsap(JNIEnv* env,
2030 jclass,
2031 jint read_pipe_fd,
2032 jint write_pipe_fd,
Chris Wailes3d748212019-05-09 17:11:00 -07002033 jintArray managed_session_socket_fds,
2034 jboolean is_priority_fork) {
Chris Wailes7e797b62019-02-22 18:29:22 -08002035 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
Chris Wailesaa1c9622019-01-10 16:55:32 -08002036 fds_to_ignore(fds_to_close);
2037
2038 std::vector<int> session_socket_fds =
Chris Wailes7e797b62019-02-22 18:29:22 -08002039 ExtractJIntArray(env, "USAP", nullptr, managed_session_socket_fds)
Chris Wailesaa1c9622019-01-10 16:55:32 -08002040 .value_or(std::vector<int>());
2041
Chris Wailes7e797b62019-02-22 18:29:22 -08002042 // The USAP Pool Event FD is created during the initialization of the
2043 // USAP pool and should always be valid here.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002044
2045 fds_to_close.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08002046 fds_to_close.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002047 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
Jing Jie29afc92019-10-29 18:14:49 -07002048 if (gSystemServerSocketFd != -1) {
2049 fds_to_close.push_back(gSystemServerSocketFd);
2050 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08002051
2052 fds_to_ignore.push_back(gZygoteSocketFD);
Chris Wailes7e797b62019-02-22 18:29:22 -08002053 fds_to_ignore.push_back(gUsapPoolSocketFD);
2054 fds_to_ignore.push_back(gUsapPoolEventFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002055 fds_to_ignore.push_back(read_pipe_fd);
2056 fds_to_ignore.push_back(write_pipe_fd);
2057 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
Jing Jie29afc92019-10-29 18:14:49 -07002058 if (gSystemServerSocketFd != -1) {
2059 fds_to_ignore.push_back(gSystemServerSocketFd);
2060 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08002061
Chris Wailes3d748212019-05-09 17:11:00 -07002062 pid_t usap_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore,
2063 is_priority_fork == JNI_TRUE);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002064
Chris Wailes7e797b62019-02-22 18:29:22 -08002065 if (usap_pid != 0) {
2066 ++gUsapPoolCount;
2067 AddUsapTableEntry(usap_pid, read_pipe_fd);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002068 }
2069
Chris Wailes7e797b62019-02-22 18:29:22 -08002070 return usap_pid;
Chris Wailesaa1c9622019-01-10 16:55:32 -08002071}
2072
Robert Sesek54e387d2016-12-02 17:27:50 -05002073static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
2074 JNIEnv* env, jclass, jstring path) {
2075 ScopedUtfChars path_native(env, path);
2076 const char* path_cstr = path_native.c_str();
2077 if (!path_cstr) {
Chris Wailesaf594fc2018-11-02 11:00:07 -07002078 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05002079 }
2080 FileDescriptorWhitelist::Get()->Allow(path_cstr);
2081}
2082
Martijn Coenen86f08a52019-01-03 16:23:01 +01002083static void com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(
2084 JNIEnv* env, jclass, jint uidGidMin, jint uidGidMax) {
Chris Wailes6d482d542019-04-03 13:00:52 -07002085 if (!gIsSecurityEnforced) {
Martijn Coenen86f08a52019-01-03 16:23:01 +01002086 ALOGI("seccomp disabled by setenforce 0");
2087 return;
2088 }
2089
Martijn Coenen86f08a52019-01-03 16:23:01 +01002090 bool installed = install_setuidgid_seccomp_filter(uidGidMin, uidGidMax);
2091 if (!installed) {
2092 RuntimeAbort(env, __LINE__, "Could not install setuid/setgid seccomp filter.");
2093 }
Martijn Coenen86f08a52019-01-03 16:23:01 +01002094}
2095
Chris Wailesaa1c9622019-01-10 16:55:32 -08002096/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002097 * Called from an unspecialized app process to specialize the process for a
2098 * given application.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002099 *
2100 * @param env Managed runtime environment
2101 * @param uid User ID of the new application
2102 * @param gid Group ID of the new application
2103 * @param gids Extra groups that the process belongs to
2104 * @param runtime_flags Flags for changing the behavior of the managed runtime
2105 * @param rlimits Resource limits
2106 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
2107 * @param se_info SELinux policy information
2108 * @param nice_name New name for this process
2109 * @param is_child_zygote If the process is to become a WebViewZygote
2110 * @param instruction_set The instruction set expected/requested by the new application
2111 * @param app_data_dir Path to the application's data directory
Riddle Hsu32dbdca2019-05-17 23:10:16 -06002112 * @param is_top_app If the process is for top (high priority) application
Chris Wailesaa1c9622019-01-10 16:55:32 -08002113 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002114static void com_android_internal_os_Zygote_nativeSpecializeAppProcess(
Chris Wailesaa1c9622019-01-10 16:55:32 -08002115 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
2116 jint runtime_flags, jobjectArray rlimits,
2117 jint mount_external, jstring se_info, jstring nice_name,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00002118 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app,
2119 jobjectArray pkg_data_info_list) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08002120 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
2121
2122 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
2123 capabilities, capabilities,
2124 mount_external, se_info, nice_name, false,
Riddle Hsu32dbdca2019-05-17 23:10:16 -06002125 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
Ricky Wai5a8fe7a2019-12-13 15:20:47 +00002126 is_top_app == JNI_TRUE, pkg_data_info_list);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002127}
2128
2129/**
2130 * A helper method for fetching socket file descriptors that were opened by init from the
2131 * environment.
2132 *
2133 * @param env Managed runtime environment
2134 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
2135 * of the environment variable storing the file descriptors.
2136 */
Chris Wailes6d482d542019-04-03 13:00:52 -07002137static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv* env, jclass,
2138 jboolean is_primary) {
2139 /*
2140 * Obtain file descriptors created by init from the environment.
2141 */
2142
Chris Wailesee1fd452019-04-10 18:05:25 -07002143 gZygoteSocketFD =
2144 android_get_control_socket(is_primary ? "zygote" : "zygote_secondary");
2145 if (gZygoteSocketFD >= 0) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08002146 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
2147 } else {
2148 ALOGE("Unable to fetch Zygote socket file descriptor");
2149 }
2150
Chris Wailesee1fd452019-04-10 18:05:25 -07002151 gUsapPoolSocketFD =
2152 android_get_control_socket(is_primary ? "usap_pool_primary" : "usap_pool_secondary");
2153 if (gUsapPoolSocketFD >= 0) {
Chris Wailes7e797b62019-02-22 18:29:22 -08002154 ALOGV("Zygote:usapPoolSocketFD = %d", gUsapPoolSocketFD);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002155 } else {
Chris Wailes7e797b62019-02-22 18:29:22 -08002156 ALOGE("Unable to fetch USAP pool socket file descriptor");
Chris Wailesaa1c9622019-01-10 16:55:32 -08002157 }
Chris Wailes6d482d542019-04-03 13:00:52 -07002158
Jing Jie29afc92019-10-29 18:14:49 -07002159 initUnsolSocketToSystemServer();
2160
Chris Wailes6d482d542019-04-03 13:00:52 -07002161 /*
2162 * Security Initialization
2163 */
2164
2165 // security_getenforce is not allowed on app process. Initialize and cache
2166 // the value before zygote forks.
2167 gIsSecurityEnforced = security_getenforce();
2168
2169 selinux_android_seapp_context_init();
2170
2171 /*
2172 * Storage Initialization
2173 */
2174
2175 UnmountStorageOnInit(env);
2176
2177 /*
2178 * Performance Initialization
2179 */
2180
2181 if (!SetTaskProfiles(0, {})) {
2182 ZygoteFailure(env, "zygote", nullptr, "Zygote SetTaskProfiles failed");
2183 }
Chris Wailesaa1c9622019-01-10 16:55:32 -08002184}
2185
2186/**
2187 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08002188 * @return A managed array of raw file descriptors for the read ends of the USAP reporting
Chris Wailesaa1c9622019-01-10 16:55:32 -08002189 * pipes.
2190 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002191static jintArray com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv* env, jclass) {
2192 std::vector<int> usap_fds = MakeUsapPipeReadFDVector();
Chris Wailesaa1c9622019-01-10 16:55:32 -08002193
Chris Wailes7e797b62019-02-22 18:29:22 -08002194 jintArray managed_usap_fds = env->NewIntArray(usap_fds.size());
2195 env->SetIntArrayRegion(managed_usap_fds, 0, usap_fds.size(), usap_fds.data());
Chris Wailesaa1c9622019-01-10 16:55:32 -08002196
Chris Wailes7e797b62019-02-22 18:29:22 -08002197 return managed_usap_fds;
Chris Wailesaa1c9622019-01-10 16:55:32 -08002198}
2199
2200/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002201 * A JNI wrapper around RemoveUsapTableEntry.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002202 *
2203 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08002204 * @param usap_pid Process ID of the USAP entry to invalidate
Chris Wailesaa1c9622019-01-10 16:55:32 -08002205 * @return True if an entry was invalidated; false otherwise.
2206 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002207static jboolean com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(JNIEnv* env, jclass,
2208 jint usap_pid) {
2209 return RemoveUsapTableEntry(usap_pid);
Chris Wailesaa1c9622019-01-10 16:55:32 -08002210}
2211
2212/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002213 * Creates the USAP pool event FD if it doesn't exist and returns it. This is used by the
2214 * ZygoteServer poll loop to know when to re-fill the USAP pool.
Chris Wailesaa1c9622019-01-10 16:55:32 -08002215 *
2216 * @param env Managed runtime environment
2217 * @return A raw event file descriptor used to communicate (from the signal handler) when the
Chris Wailes7e797b62019-02-22 18:29:22 -08002218 * Zygote receives a SIGCHLD for a USAP
Chris Wailesaa1c9622019-01-10 16:55:32 -08002219 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002220static jint com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv* env, jclass) {
2221 if (gUsapPoolEventFD == -1) {
2222 if ((gUsapPoolEventFD = eventfd(0, 0)) == -1) {
Chris Wailesaa1c9622019-01-10 16:55:32 -08002223 ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
2224 }
2225 }
2226
Chris Wailes7e797b62019-02-22 18:29:22 -08002227 return gUsapPoolEventFD;
Chris Wailesaa1c9622019-01-10 16:55:32 -08002228}
2229
2230/**
2231 * @param env Managed runtime environment
Chris Wailes7e797b62019-02-22 18:29:22 -08002232 * @return The number of USAPs currently in the USAP pool
Chris Wailesaa1c9622019-01-10 16:55:32 -08002233 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002234static jint com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv* env, jclass) {
2235 return gUsapPoolCount;
Chris Wailesaa1c9622019-01-10 16:55:32 -08002236}
2237
Chris Wailesae937142019-01-24 12:57:33 -08002238/**
Chris Wailes7e797b62019-02-22 18:29:22 -08002239 * Kills all processes currently in the USAP pool and closes their read pipe
2240 * FDs.
Chris Wailesae937142019-01-24 12:57:33 -08002241 *
2242 * @param env Managed runtime environment
Chris Wailesae937142019-01-24 12:57:33 -08002243 */
Chris Wailes7e797b62019-02-22 18:29:22 -08002244static void com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv* env, jclass) {
2245 for (auto& entry : gUsapTable) {
Chris Wailesae937142019-01-24 12:57:33 -08002246 auto entry_storage = entry.GetValues();
2247
2248 if (entry_storage.has_value()) {
Chris Wailesfb329ba2019-06-05 16:07:50 -07002249 kill(entry_storage.value().pid, SIGTERM);
2250
2251 // Clean up the USAP table entry here. This avoids a potential race
2252 // where a newly created USAP might not be able to find a valid table
2253 // entry if signal handler (which would normally do the cleanup) doesn't
2254 // run between now and when the new process is created.
2255
Chris Wailesdb132a32019-02-20 10:49:27 -08002256 close(entry_storage.value().read_pipe_fd);
2257
2258 // Avoid a second atomic load by invalidating instead of clearing.
2259 entry.Invalidate();
Chris Wailes7e797b62019-02-22 18:29:22 -08002260 --gUsapPoolCount;
Chris Wailesae937142019-01-24 12:57:33 -08002261 }
2262 }
2263}
2264
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07002265/**
2266 * @param env Managed runtime environment
2267 * @return True if disable was successful.
2268 */
2269static jboolean com_android_internal_os_Zygote_nativeDisableExecuteOnly(JNIEnv* env, jclass) {
Chris Wailesff8d4e72019-04-10 17:49:24 -07002270 return dl_iterate_phdr(DisableExecuteOnly, nullptr) == 0;
Jeff Vander Stoep739c0b52019-03-25 20:27:52 -07002271}
2272
Chris Wailesfb329ba2019-06-05 16:07:50 -07002273static void com_android_internal_os_Zygote_nativeBlockSigTerm(JNIEnv* env, jclass) {
2274 auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
2275 BlockSignal(SIGTERM, fail_fn);
2276}
2277
2278static void com_android_internal_os_Zygote_nativeUnblockSigTerm(JNIEnv* env, jclass) {
2279 auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
2280 UnblockSignal(SIGTERM, fail_fn);
2281}
2282
Chris Wailes3d748212019-05-09 17:11:00 -07002283static void com_android_internal_os_Zygote_nativeBoostUsapPriority(JNIEnv* env, jclass) {
2284 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
2285}
2286
Jing Jie29afc92019-10-29 18:14:49 -07002287static jint com_android_internal_os_Zygote_nativeParseSigChld(JNIEnv* env, jclass, jbyteArray in,
2288 jint length, jintArray out) {
2289 if (length != sizeof(struct UnsolicitedZygoteMessageSigChld)) {
2290 // Apparently it's not the message we are expecting.
2291 return -1;
2292 }
2293 if (in == nullptr || out == nullptr) {
2294 // Invalid parameter
2295 jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2296 return -1;
2297 }
2298 ScopedByteArrayRO source(env, in);
2299 if (source.size() < length) {
2300 // Invalid parameter
2301 jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2302 return -1;
2303 }
2304 const struct UnsolicitedZygoteMessageSigChld* msg =
2305 reinterpret_cast<const struct UnsolicitedZygoteMessageSigChld*>(source.get());
2306
2307 switch (msg->header.type) {
2308 case UNSOLICITED_ZYGOTE_MESSAGE_TYPE_SIGCHLD: {
2309 ScopedIntArrayRW buf(env, out);
2310 if (buf.size() != 3) {
2311 jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2312 return UNSOLICITED_ZYGOTE_MESSAGE_TYPE_RESERVED;
2313 }
2314 buf[0] = msg->payload.pid;
2315 buf[1] = msg->payload.uid;
2316 buf[2] = msg->payload.status;
2317 return 3;
2318 }
2319 default:
2320 break;
2321 }
2322 return -1;
2323}
2324
Daniel Micay76f6a862015-09-19 17:31:01 -04002325static const JNINativeMethod gMethods[] = {
Jing Jie29afc92019-10-29 18:14:49 -07002326 {"nativeForkAndSpecialize",
2327 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/"
2328 "String;Z[Ljava/lang/String;)I",
2329 (void*)com_android_internal_os_Zygote_nativeForkAndSpecialize},
2330 {"nativeForkSystemServer", "(II[II[[IJJ)I",
2331 (void*)com_android_internal_os_Zygote_nativeForkSystemServer},
2332 {"nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
2333 (void*)com_android_internal_os_Zygote_nativeAllowFileAcrossFork},
2334 {"nativePreApplicationInit", "()V",
2335 (void*)com_android_internal_os_Zygote_nativePreApplicationInit},
2336 {"nativeInstallSeccompUidGidFilter", "(II)V",
2337 (void*)com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter},
2338 {"nativeForkUsap", "(II[IZ)I", (void*)com_android_internal_os_Zygote_nativeForkUsap},
2339 {"nativeSpecializeAppProcess",
2340 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/"
2341 "String;Z[Ljava/lang/String;)V",
2342 (void*)com_android_internal_os_Zygote_nativeSpecializeAppProcess},
2343 {"nativeInitNativeState", "(Z)V",
2344 (void*)com_android_internal_os_Zygote_nativeInitNativeState},
2345 {"nativeGetUsapPipeFDs", "()[I",
2346 (void*)com_android_internal_os_Zygote_nativeGetUsapPipeFDs},
2347 {"nativeRemoveUsapTableEntry", "(I)Z",
2348 (void*)com_android_internal_os_Zygote_nativeRemoveUsapTableEntry},
2349 {"nativeGetUsapPoolEventFD", "()I",
2350 (void*)com_android_internal_os_Zygote_nativeGetUsapPoolEventFD},
2351 {"nativeGetUsapPoolCount", "()I",
2352 (void*)com_android_internal_os_Zygote_nativeGetUsapPoolCount},
2353 {"nativeEmptyUsapPool", "()V", (void*)com_android_internal_os_Zygote_nativeEmptyUsapPool},
2354 {"nativeDisableExecuteOnly", "()Z",
2355 (void*)com_android_internal_os_Zygote_nativeDisableExecuteOnly},
2356 {"nativeBlockSigTerm", "()V", (void*)com_android_internal_os_Zygote_nativeBlockSigTerm},
2357 {"nativeUnblockSigTerm", "()V", (void*)com_android_internal_os_Zygote_nativeUnblockSigTerm},
2358 {"nativeBoostUsapPriority", "()V",
2359 (void*)com_android_internal_os_Zygote_nativeBoostUsapPriority},
2360 {"nativeParseSigChld", "([BI[I)I",
2361 (void*)com_android_internal_os_Zygote_nativeParseSigChld},
Narayan Kamath973b4662014-03-31 13:41:26 +01002362};
2363
2364int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08002365 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01002366 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
2367 "callPostForkSystemServerHooks",
Mathieu Chartier2cb0a4d2019-11-21 14:30:03 -08002368 "(I)V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08002369 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05002370 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01002371
Andreas Gampe76b4b2c2019-03-15 11:56:48 -07002372 gZygoteInitClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteInitClassName));
2373 gCreateSystemServerClassLoader = GetStaticMethodIDOrDie(env, gZygoteInitClass,
2374 "createSystemServerClassLoader",
2375 "()V");
2376
2377 RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
2378
2379 return JNI_OK;
Narayan Kamath973b4662014-03-31 13:41:26 +01002380}
2381} // namespace android