1 /*
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
17 #define LOG_TAG "Zygote"
18 #define ATRACE_TAG ATRACE_TAG_DALVIK
19
20 #include "com_android_internal_os_Zygote.h"
21
22 #include <async_safe/log.h>
23
24 // sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
25 #include <sys/mount.h>
26 #include <linux/fs.h>
27 #include <sys/types.h>
28 #include <dirent.h>
29
30 #include <algorithm>
31 #include <array>
32 #include <atomic>
33 #include <functional>
34 #include <iterator>
35 #include <list>
36 #include <optional>
37 #include <sstream>
38 #include <string>
39 #include <string_view>
40 #include <unordered_set>
41
42 #include <android/fdsan.h>
43 #include <arpa/inet.h>
44 #include <fcntl.h>
45 #include <grp.h>
46 #include <inttypes.h>
47 #include <malloc.h>
48 #include <mntent.h>
49 #include <paths.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <sys/auxv.h>
54 #include <sys/capability.h>
55 #include <sys/cdefs.h>
56 #include <sys/eventfd.h>
57 #include <sys/personality.h>
58 #include <sys/prctl.h>
59 #include <sys/resource.h>
60 #include <sys/socket.h>
61 #include <sys/stat.h>
62 #include <sys/time.h>
63 #include <sys/types.h>
64 #include <sys/un.h>
65 #include <sys/wait.h>
66 #include <unistd.h>
67
68 #include <android-base/file.h>
69 #include <android-base/logging.h>
70 #include <android-base/properties.h>
71 #include <android-base/stringprintf.h>
72 #include <android-base/unique_fd.h>
73 #include <bionic/malloc.h>
74 #include <bionic/mte.h>
75 #include <cutils/fs.h>
76 #include <cutils/multiuser.h>
77 #include <cutils/sockets.h>
78 #include <private/android_filesystem_config.h>
79 #include <processgroup/processgroup.h>
80 #include <processgroup/sched_policy.h>
81 #include <seccomp_policy.h>
82 #include <selinux/android.h>
83 #include <stats_socket.h>
84 #include <utils/String8.h>
85 #include <utils/Trace.h>
86
87 #include <nativehelper/JNIHelp.h>
88 #include <nativehelper/ScopedLocalRef.h>
89 #include <nativehelper/ScopedPrimitiveArray.h>
90 #include <nativehelper/ScopedUtfChars.h>
91 #include "core_jni_helpers.h"
92 #include "fd_utils.h"
93 #include "filesystem_utils.h"
94
95 #include "nativebridge/native_bridge.h"
96
97 #if defined(__BIONIC__)
98 extern "C" void android_reset_stack_guards();
99 #endif
100
101 namespace {
102
103 // TODO (chriswailes): Add a function to initialize native Zygote data.
104 // TODO (chriswailes): Fix mixed indentation style (2 and 4 spaces).
105
106 using namespace std::placeholders;
107
108 using android::String8;
109 using android::base::ReadFileToString;
110 using android::base::StringAppendF;
111 using android::base::StringPrintf;
112 using android::base::WriteStringToFile;
113 using android::base::GetBoolProperty;
114
115 using android::zygote::ZygoteFailure;
116
117 using Action = android_mallopt_gwp_asan_options_t::Action;
118
119 // This type is duplicated in fd_utils.h
120 typedef const std::function<void(std::string)>& fail_fn_t;
121
122 static pid_t gSystemServerPid = 0;
123
124 static constexpr const char* kVoldAppDataIsolation = "persist.sys.vold_app_data_isolation_enabled";
125 static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
126 static jclass gZygoteClass;
127 static jmethodID gCallPostForkSystemServerHooks;
128 static jmethodID gCallPostForkChildHooks;
129
130 static constexpr const char* kZygoteInitClassName = "com/android/internal/os/ZygoteInit";
131 static jclass gZygoteInitClass;
132 static jmethodID gGetOrCreateSystemServerClassLoader;
133 static jmethodID gPrefetchStandaloneSystemServerJars;
134
135 static bool gIsSecurityEnforced = true;
136
137 /**
138 * True if the app process is running in its mount namespace.
139 */
140 static bool gInAppMountNamespace = false;
141
142 /**
143 * The maximum number of characters (not including a null terminator) that a
144 * process name may contain.
145 */
146 static constexpr size_t MAX_NAME_LENGTH = 15;
147
148 /**
149 * The file descriptor for the Zygote socket opened by init.
150 */
151
152 static int gZygoteSocketFD = -1;
153
154 /**
155 * The file descriptor for the unspecialized app process (USAP) pool socket opened by init.
156 */
157
158 static int gUsapPoolSocketFD = -1;
159
160 /**
161 * The number of USAPs currently in this Zygote's pool.
162 */
163 static std::atomic_uint32_t gUsapPoolCount = 0;
164
165 /**
166 * Event file descriptor used to communicate reaped USAPs to the
167 * ZygoteServer.
168 */
169 static int gUsapPoolEventFD = -1;
170
171 /**
172 * The socket file descriptor used to send notifications to the
173 * system_server.
174 */
175 static int gSystemServerSocketFd = -1;
176
177 static constexpr int DEFAULT_DATA_DIR_PERMISSION = 0751;
178
179 static constexpr const uint64_t UPPER_HALF_WORD_MASK = 0xFFFF'FFFF'0000'0000;
180 static constexpr const uint64_t LOWER_HALF_WORD_MASK = 0x0000'0000'FFFF'FFFF;
181
182 static constexpr const char* kCurProfileDirPath = "/data/misc/profiles/cur";
183 static constexpr const char* kRefProfileDirPath = "/data/misc/profiles/ref";
184
185 /**
186 * The maximum value that the gUSAPPoolSizeMax variable may take. This value
187 * is a mirror of ZygoteServer.USAP_POOL_SIZE_MAX_LIMIT
188 */
189 static constexpr int USAP_POOL_SIZE_MAX_LIMIT = 100;
190
191 /** The numeric value for the maximum priority a process may possess. */
192 static constexpr int PROCESS_PRIORITY_MAX = -20;
193
194 /** The numeric value for the minimum priority a process may possess. */
195 static constexpr int PROCESS_PRIORITY_MIN = 19;
196
197 /** The numeric value for the normal priority a process should have. */
198 static constexpr int PROCESS_PRIORITY_DEFAULT = 0;
199
200 /** Exponential back off parameters for storage dir check. */
201 static constexpr unsigned int STORAGE_DIR_CHECK_RETRY_MULTIPLIER = 2;
202 static constexpr unsigned int STORAGE_DIR_CHECK_INIT_INTERVAL_US = 50;
203 static constexpr unsigned int STORAGE_DIR_CHECK_MAX_INTERVAL_US = 1000;
204 /**
205 * Lower bound time we allow storage dir check to sleep.
206 * If it exceeds 2s, PROC_START_TIMEOUT_MSG will kill the starting app anyway,
207 * so it's fine to assume max retries is 5 mins.
208 */
209 static constexpr int STORAGE_DIR_CHECK_TIMEOUT_US = 1000 * 1000 * 60 * 5;
210
211 static void WaitUntilDirReady(const std::string& target, fail_fn_t fail_fn);
212
213 /**
214 * A helper class containing accounting information for USAPs.
215 */
216 class UsapTableEntry {
217 public:
218 struct EntryStorage {
219 int32_t pid;
220 int32_t read_pipe_fd;
221
operator !=__anon177197740111::UsapTableEntry::EntryStorage222 bool operator!=(const EntryStorage& other) {
223 return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
224 }
225 };
226
227 private:
228 static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
229
230 std::atomic<EntryStorage> mStorage;
231 static_assert(decltype(mStorage)::is_always_lock_free); // Accessed from signal handler.
232
233 public:
UsapTableEntry()234 constexpr UsapTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
235
236 /**
237 * If the provided PID matches the one stored in this entry, the entry will
238 * be invalidated and the associated file descriptor will be closed. If the
239 * PIDs don't match nothing will happen.
240 *
241 * @param pid The ID of the process who's entry we want to clear.
242 * @return True if the entry was cleared by this call; false otherwise
243 */
ClearForPID(int32_t pid)244 bool ClearForPID(int32_t pid) {
245 EntryStorage storage = mStorage.load();
246
247 if (storage.pid == pid) {
248 /*
249 * There are three possible outcomes from this compare-and-exchange:
250 * 1) It succeeds, in which case we close the FD
251 * 2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
252 * the entry has already been cleared.
253 * 3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
254 * case the entry has already been cleared and re-used.
255 *
256 * In all three cases the goal of the caller has been met, but only in
257 * the first case do we need to decrement the pool count.
258 */
259 if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
260 close(storage.read_pipe_fd);
261 return true;
262 } else {
263 return false;
264 }
265
266 } else {
267 return false;
268 }
269 }
270
Clear()271 void Clear() {
272 EntryStorage storage = mStorage.load();
273
274 if (storage != INVALID_ENTRY_VALUE) {
275 close(storage.read_pipe_fd);
276 mStorage.store(INVALID_ENTRY_VALUE);
277 }
278 }
279
Invalidate()280 void Invalidate() {
281 mStorage.store(INVALID_ENTRY_VALUE);
282 }
283
284 /**
285 * @return A copy of the data stored in this entry.
286 */
GetValues()287 std::optional<EntryStorage> GetValues() {
288 EntryStorage storage = mStorage.load();
289
290 if (storage != INVALID_ENTRY_VALUE) {
291 return storage;
292 } else {
293 return std::nullopt;
294 }
295 }
296
297 /**
298 * Sets the entry to the given values if it is currently invalid.
299 *
300 * @param pid The process ID for the new entry.
301 * @param read_pipe_fd The read end of the USAP control pipe for this
302 * process.
303 * @return True if the entry was set; false otherwise.
304 */
SetIfInvalid(int32_t pid,int32_t read_pipe_fd)305 bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
306 EntryStorage new_value_storage;
307
308 new_value_storage.pid = pid;
309 new_value_storage.read_pipe_fd = read_pipe_fd;
310
311 EntryStorage expected = INVALID_ENTRY_VALUE;
312
313 return mStorage.compare_exchange_strong(expected, new_value_storage);
314 }
315 };
316
317 /**
318 * A table containing information about the USAPs currently in the pool.
319 *
320 * Multiple threads may be attempting to modify the table, either from the
321 * signal handler or from the ZygoteServer poll loop. Atomic loads/stores in
322 * the USAPTableEntry class prevent data races during these concurrent
323 * operations.
324 */
325 static std::array<UsapTableEntry, USAP_POOL_SIZE_MAX_LIMIT> gUsapTable;
326
327 /**
328 * The list of open zygote file descriptors.
329 */
330 static FileDescriptorTable* gOpenFdTable = nullptr;
331
332 // Must match values in com.android.internal.os.Zygote.
333 // The values should be consistent with IVold.aidl
334 enum MountExternalKind {
335 MOUNT_EXTERNAL_NONE = 0,
336 MOUNT_EXTERNAL_DEFAULT = 1,
337 MOUNT_EXTERNAL_INSTALLER = 2,
338 MOUNT_EXTERNAL_PASS_THROUGH = 3,
339 MOUNT_EXTERNAL_ANDROID_WRITABLE = 4,
340 MOUNT_EXTERNAL_COUNT = 5
341 };
342
343 // Must match values in com.android.internal.os.Zygote.
344 enum RuntimeFlags : uint32_t {
345 DEBUG_ENABLE_JDWP = 1,
346 PROFILE_SYSTEM_SERVER = 1 << 14,
347 PROFILE_FROM_SHELL = 1 << 15,
348 MEMORY_TAG_LEVEL_MASK = (1 << 19) | (1 << 20),
349 MEMORY_TAG_LEVEL_TBI = 1 << 19,
350 MEMORY_TAG_LEVEL_ASYNC = 2 << 19,
351 MEMORY_TAG_LEVEL_SYNC = 3 << 19,
352 GWP_ASAN_LEVEL_MASK = (1 << 21) | (1 << 22),
353 GWP_ASAN_LEVEL_NEVER = 0 << 21,
354 GWP_ASAN_LEVEL_LOTTERY = 1 << 21,
355 GWP_ASAN_LEVEL_ALWAYS = 2 << 21,
356 GWP_ASAN_LEVEL_DEFAULT = 3 << 21,
357 NATIVE_HEAP_ZERO_INIT_ENABLED = 1 << 23,
358 PROFILEABLE = 1 << 24,
359 DEBUG_ENABLE_PTRACE = 1 << 25,
360 };
361
362 enum UnsolicitedZygoteMessageTypes : uint32_t {
363 UNSOLICITED_ZYGOTE_MESSAGE_TYPE_RESERVED = 0,
364 UNSOLICITED_ZYGOTE_MESSAGE_TYPE_SIGCHLD = 1,
365 };
366
367 struct UnsolicitedZygoteMessageSigChld {
368 struct {
369 UnsolicitedZygoteMessageTypes type;
370 } header;
371 struct {
372 pid_t pid;
373 uid_t uid;
374 int status;
375 } payload;
376 };
377
378 // Keep sync with services/core/java/com/android/server/am/ProcessList.java
379 static constexpr struct sockaddr_un kSystemServerSockAddr =
380 {.sun_family = AF_LOCAL, .sun_path = "/data/system/unsolzygotesocket"};
381
382 // Forward declaration so we don't have to move the signal handler.
383 static bool RemoveUsapTableEntry(pid_t usap_pid);
384
RuntimeAbort(JNIEnv * env,int line,const char * msg)385 static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
386 std::ostringstream oss;
387 oss << __FILE__ << ":" << line << ": " << msg;
388 env->FatalError(oss.str().c_str());
389 }
390
391 // Create the socket which is going to be used to send unsolicited message
392 // to system_server, the socket will be closed post forking a child process.
393 // It's expected to be called at each zygote's initialization.
initUnsolSocketToSystemServer()394 static void initUnsolSocketToSystemServer() {
395 gSystemServerSocketFd = socket(AF_LOCAL, SOCK_DGRAM | SOCK_NONBLOCK, 0);
396 if (gSystemServerSocketFd >= 0) {
397 ALOGV("Zygote:systemServerSocketFD = %d", gSystemServerSocketFd);
398 } else {
399 ALOGE("Unable to create socket file descriptor to connect to system_server");
400 }
401 }
402
sendSigChildStatus(const pid_t pid,const uid_t uid,const int status)403 static void sendSigChildStatus(const pid_t pid, const uid_t uid, const int status) {
404 int socketFd = gSystemServerSocketFd;
405 if (socketFd >= 0) {
406 // fill the message buffer
407 struct UnsolicitedZygoteMessageSigChld data =
408 {.header = {.type = UNSOLICITED_ZYGOTE_MESSAGE_TYPE_SIGCHLD},
409 .payload = {.pid = pid, .uid = uid, .status = status}};
410 if (TEMP_FAILURE_RETRY(
411 sendto(socketFd, &data, sizeof(data), 0,
412 reinterpret_cast<const struct sockaddr*>(&kSystemServerSockAddr),
413 sizeof(kSystemServerSockAddr))) == -1) {
414 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
415 "Zygote failed to write to system_server FD: %s",
416 strerror(errno));
417 }
418 }
419 }
420
421 // This signal handler is for zygote mode, since the zygote must reap its children
422 NO_STACK_PROTECTOR
SigChldHandler(int,siginfo_t * info,void *)423 static void SigChldHandler(int /*signal_number*/, siginfo_t* info, void* /*ucontext*/) {
424 pid_t pid;
425 int status;
426 int64_t usaps_removed = 0;
427
428 // It's necessary to save and restore the errno during this function.
429 // Since errno is stored per thread, changing it here modifies the errno
430 // on the thread on which this signal handler executes. If a signal occurs
431 // between a call and an errno check, it's possible to get the errno set
432 // here.
433 // See b/23572286 for extra information.
434 int saved_errno = errno;
435
436 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
437 // Notify system_server that we received a SIGCHLD
438 sendSigChildStatus(pid, info->si_uid, status);
439 // Log process-death status that we care about.
440 if (WIFEXITED(status)) {
441 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG, "Process %d exited cleanly (%d)", pid,
442 WEXITSTATUS(status));
443
444 // Check to see if the PID is in the USAP pool and remove it if it is.
445 if (RemoveUsapTableEntry(pid)) {
446 ++usaps_removed;
447 }
448 } else if (WIFSIGNALED(status)) {
449 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
450 "Process %d exited due to signal %d (%s)%s", pid,
451 WTERMSIG(status), strsignal(WTERMSIG(status)),
452 WCOREDUMP(status) ? "; core dumped" : "");
453
454 // If the process exited due to a signal other than SIGTERM, check to see
455 // if the PID is in the USAP pool and remove it if it is. If the process
456 // was closed by the Zygote using SIGTERM then the USAP pool entry will
457 // have already been removed (see nativeEmptyUsapPool()).
458 if (WTERMSIG(status) != SIGTERM && RemoveUsapTableEntry(pid)) {
459 ++usaps_removed;
460 }
461 }
462
463 // If the just-crashed process is the system_server, bring down zygote
464 // so that it is restarted by init and system server will be restarted
465 // from there.
466 if (pid == gSystemServerPid) {
467 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
468 "Exit zygote because system server (pid %d) has terminated", pid);
469 kill(getpid(), SIGKILL);
470 }
471 }
472
473 // Note that we shouldn't consider ECHILD an error because
474 // the secondary zygote might have no children left to wait for.
475 if (pid < 0 && errno != ECHILD) {
476 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG, "Zygote SIGCHLD error in waitpid: %s",
477 strerror(errno));
478 }
479
480 if (usaps_removed > 0) {
481 if (TEMP_FAILURE_RETRY(write(gUsapPoolEventFD, &usaps_removed, sizeof(usaps_removed))) ==
482 -1) {
483 // If this write fails something went terribly wrong. We will now kill
484 // the zygote and let the system bring it back up.
485 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
486 "Zygote failed to write to USAP pool event FD: %s",
487 strerror(errno));
488 kill(getpid(), SIGKILL);
489 }
490 }
491
492 errno = saved_errno;
493 }
494
495 // Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
496 // configured very late, because earlier in the runtime we may fork() and
497 // exec() other processes, and we want to waitpid() for those rather than
498 // have them be harvested immediately.
499 //
500 // Ignore SIGHUP because all processes forked by the zygote are in the same
501 // process group as the zygote and we don't want to be notified if we become
502 // an orphaned group and have one or more stopped processes. This is not a
503 // theoretical concern :
504 // - we can become an orphaned group if one of our direct descendants forks
505 // and is subsequently killed before its children.
506 // - crash_dump routinely STOPs the process it's tracing.
507 //
508 // See issues b/71965619 and b/25567761 for further details.
509 //
510 // This ends up being called repeatedly before each fork(), but there's
511 // no real harm in that.
SetSignalHandlers()512 static void SetSignalHandlers() {
513 struct sigaction sig_chld = {.sa_flags = SA_SIGINFO, .sa_sigaction = SigChldHandler};
514
515 if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
516 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
517 }
518
519 struct sigaction sig_hup = {};
520 sig_hup.sa_handler = SIG_IGN;
521 if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
522 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
523 }
524 }
525
526 // Sets the SIGCHLD handler back to default behavior in zygote children.
UnsetChldSignalHandler()527 static void UnsetChldSignalHandler() {
528 struct sigaction sa;
529 memset(&sa, 0, sizeof(sa));
530 sa.sa_handler = SIG_DFL;
531
532 if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
533 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
534 }
535 }
536
537 // Calls POSIX setgroups() using the int[] object as an argument.
538 // A nullptr argument is tolerated.
SetGids(JNIEnv * env,jintArray managed_gids,jboolean is_child_zygote,fail_fn_t fail_fn)539 static void SetGids(JNIEnv* env, jintArray managed_gids, jboolean is_child_zygote,
540 fail_fn_t fail_fn) {
541 if (managed_gids == nullptr) {
542 if (is_child_zygote) {
543 // For child zygotes like webview and app zygote, we want to clear out
544 // any supplemental groups the parent zygote had.
545 if (setgroups(0, NULL) == -1) {
546 fail_fn(CREATE_ERROR("Failed to remove supplementary groups for child zygote"));
547 }
548 }
549 return;
550 }
551
552 ScopedIntArrayRO gids(env, managed_gids);
553 if (gids.get() == nullptr) {
554 fail_fn(CREATE_ERROR("Getting gids int array failed"));
555 }
556
557 if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
558 fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
559 }
560 }
561
ensureInAppMountNamespace(fail_fn_t fail_fn)562 static void ensureInAppMountNamespace(fail_fn_t fail_fn) {
563 if (gInAppMountNamespace) {
564 // In app mount namespace already
565 return;
566 }
567 if (unshare(CLONE_NEWNS) == -1) {
568 fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
569 }
570 gInAppMountNamespace = true;
571 }
572
573 // Sets the resource limits via setrlimit(2) for the values in the
574 // two-dimensional array of integers that's passed in. The second dimension
575 // contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
576 // treated as an empty array.
SetRLimits(JNIEnv * env,jobjectArray managed_rlimits,fail_fn_t fail_fn)577 static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
578 if (managed_rlimits == nullptr) {
579 return;
580 }
581
582 rlimit rlim;
583 memset(&rlim, 0, sizeof(rlim));
584
585 for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
586 ScopedLocalRef<jobject>
587 managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
588 ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
589
590 if (rlimit_handle.size() != 3) {
591 fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
592 }
593
594 rlim.rlim_cur = rlimit_handle[1];
595 rlim.rlim_max = rlimit_handle[2];
596
597 if (setrlimit(rlimit_handle[0], &rlim) == -1) {
598 fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
599 rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
600 }
601 }
602 }
603
EnableDebugger()604 static void EnableDebugger() {
605 // To let a non-privileged gdbserver attach to this
606 // process, we must set our dumpable flag.
607 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
608 ALOGE("prctl(PR_SET_DUMPABLE) failed");
609 }
610
611 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
612 // is enabled (see kernel/Documentation/security/Yama.txt).
613 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
614 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
615 // case since it's expected behaviour.
616 if (errno != EINVAL) {
617 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
618 }
619 }
620
621 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
622 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
623 // Set the soft limit on core dump size to 0 without changing the hard limit.
624 rlimit rl;
625 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
626 ALOGE("getrlimit(RLIMIT_CORE) failed");
627 } else {
628 rl.rlim_cur = 0;
629 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
630 ALOGE("setrlimit(RLIMIT_CORE) failed");
631 }
632 }
633 }
634 }
635
PreApplicationInit()636 static void PreApplicationInit() {
637 // The child process sets this to indicate it's not the zygote.
638 android_mallopt(M_SET_ZYGOTE_CHILD, nullptr, 0);
639
640 // Set the jemalloc decay time to 1.
641 mallopt(M_DECAY_TIME, 1);
642 }
643
SetUpSeccompFilter(uid_t uid,bool is_child_zygote)644 static void SetUpSeccompFilter(uid_t uid, bool is_child_zygote) {
645 if (!gIsSecurityEnforced) {
646 ALOGI("seccomp disabled by setenforce 0");
647 return;
648 }
649
650 // Apply system or app filter based on uid.
651 if (uid >= AID_APP_START) {
652 if (is_child_zygote) {
653 set_app_zygote_seccomp_filter();
654 } else {
655 set_app_seccomp_filter();
656 }
657 } else {
658 set_system_seccomp_filter();
659 }
660 }
661
EnableKeepCapabilities(fail_fn_t fail_fn)662 static void EnableKeepCapabilities(fail_fn_t fail_fn) {
663 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
664 fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
665 }
666 }
667
DropCapabilitiesBoundingSet(fail_fn_t fail_fn)668 static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
669 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
670 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
671 if (errno == EINVAL) {
672 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
673 "your kernel is compiled with file capabilities support");
674 } else {
675 fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
676 }
677 }
678 }
679 }
680
SetInheritable(uint64_t inheritable,fail_fn_t fail_fn)681 static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
682 __user_cap_header_struct capheader;
683 memset(&capheader, 0, sizeof(capheader));
684 capheader.version = _LINUX_CAPABILITY_VERSION_3;
685 capheader.pid = 0;
686
687 __user_cap_data_struct capdata[2];
688 if (capget(&capheader, &capdata[0]) == -1) {
689 fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
690 }
691
692 capdata[0].inheritable = inheritable;
693 capdata[1].inheritable = inheritable >> 32;
694
695 if (capset(&capheader, &capdata[0]) == -1) {
696 fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
697 }
698 }
699
SetCapabilities(uint64_t permitted,uint64_t effective,uint64_t inheritable,fail_fn_t fail_fn)700 static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
701 fail_fn_t fail_fn) {
702 __user_cap_header_struct capheader;
703 memset(&capheader, 0, sizeof(capheader));
704 capheader.version = _LINUX_CAPABILITY_VERSION_3;
705 capheader.pid = 0;
706
707 __user_cap_data_struct capdata[2];
708 memset(&capdata, 0, sizeof(capdata));
709 capdata[0].effective = effective;
710 capdata[1].effective = effective >> 32;
711 capdata[0].permitted = permitted;
712 capdata[1].permitted = permitted >> 32;
713 capdata[0].inheritable = inheritable;
714 capdata[1].inheritable = inheritable >> 32;
715
716 if (capset(&capheader, &capdata[0]) == -1) {
717 fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
718 "failed: %s", permitted, effective, inheritable, strerror(errno)));
719 }
720 }
721
SetSchedulerPolicy(fail_fn_t fail_fn,bool is_top_app)722 static void SetSchedulerPolicy(fail_fn_t fail_fn, bool is_top_app) {
723 SchedPolicy policy = is_top_app ? SP_TOP_APP : SP_DEFAULT;
724
725 if (is_top_app && cpusets_enabled()) {
726 errno = -set_cpuset_policy(0, policy);
727 if (errno != 0) {
728 fail_fn(CREATE_ERROR("set_cpuset_policy(0, %d) failed: %s", policy, strerror(errno)));
729 }
730 }
731
732 errno = -set_sched_policy(0, policy);
733 if (errno != 0) {
734 fail_fn(CREATE_ERROR("set_sched_policy(0, %d) failed: %s", policy, strerror(errno)));
735 }
736
737 // We are going to lose the permission to set scheduler policy during the specialization, so make
738 // sure that we don't cache the fd of cgroup path that may cause sepolicy violation by writing
739 // value to the cached fd directly when creating new thread.
740 DropTaskProfilesResourceCaching();
741 }
742
UnmountTree(const char * path)743 static int UnmountTree(const char* path) {
744 ATRACE_CALL();
745
746 size_t path_len = strlen(path);
747
748 FILE* fp = setmntent("/proc/mounts", "r");
749 if (fp == nullptr) {
750 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
751 return -errno;
752 }
753
754 // Some volumes can be stacked on each other, so force unmount in
755 // reverse order to give us the best chance of success.
756 std::list<std::string> to_unmount;
757 mntent* mentry;
758 while ((mentry = getmntent(fp)) != nullptr) {
759 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
760 to_unmount.push_front(std::string(mentry->mnt_dir));
761 }
762 }
763 endmntent(fp);
764
765 for (const auto& path : to_unmount) {
766 if (umount2(path.c_str(), MNT_DETACH)) {
767 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
768 }
769 }
770 return 0;
771 }
772
PrepareDir(const std::string & dir,mode_t mode,uid_t uid,gid_t gid,fail_fn_t fail_fn)773 static void PrepareDir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
774 fail_fn_t fail_fn) {
775 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
776 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s: %s",
777 dir.c_str(), strerror(errno)));
778 }
779 }
780
PrepareDirIfNotPresent(const std::string & dir,mode_t mode,uid_t uid,gid_t gid,fail_fn_t fail_fn)781 static void PrepareDirIfNotPresent(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
782 fail_fn_t fail_fn) {
783 struct stat sb;
784 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) != -1) {
785 // Directory exists already
786 return;
787 }
788 PrepareDir(dir, mode, uid, gid, fail_fn);
789 }
790
BindMount(const std::string & source_dir,const std::string & target_dir)791 static bool BindMount(const std::string& source_dir, const std::string& target_dir) {
792 return !(TEMP_FAILURE_RETRY(mount(source_dir.c_str(), target_dir.c_str(), nullptr,
793 MS_BIND | MS_REC, nullptr)) == -1);
794 }
795
BindMount(const std::string & source_dir,const std::string & target_dir,fail_fn_t fail_fn)796 static void BindMount(const std::string& source_dir, const std::string& target_dir,
797 fail_fn_t fail_fn) {
798 if (!BindMount(source_dir, target_dir)) {
799 fail_fn(CREATE_ERROR("Failed to mount %s to %s: %s",
800 source_dir.c_str(), target_dir.c_str(), strerror(errno)));
801 }
802 }
803
MountAppDataTmpFs(const std::string & target_dir,fail_fn_t fail_fn)804 static void MountAppDataTmpFs(const std::string& target_dir,
805 fail_fn_t fail_fn) {
806 if (TEMP_FAILURE_RETRY(mount("tmpfs", target_dir.c_str(), "tmpfs",
807 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
808 fail_fn(CREATE_ERROR("Failed to mount tmpfs to %s: %s",
809 target_dir.c_str(), strerror(errno)));
810 }
811 }
812
813 // Create a private mount namespace and bind mount appropriate emulated
814 // storage for the given user.
MountEmulatedStorage(uid_t uid,jint mount_mode,bool force_mount_namespace,fail_fn_t fail_fn)815 static void MountEmulatedStorage(uid_t uid, jint mount_mode,
816 bool force_mount_namespace,
817 fail_fn_t fail_fn) {
818 // See storage config details at http://source.android.com/tech/storage/
819 ATRACE_CALL();
820
821 if (mount_mode < 0 || mount_mode >= MOUNT_EXTERNAL_COUNT) {
822 fail_fn(CREATE_ERROR("Unknown mount_mode: %d", mount_mode));
823 }
824
825 if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
826 // Valid default of no storage visible
827 return;
828 }
829
830 // Create a second private mount namespace for our process
831 ensureInAppMountNamespace(fail_fn);
832
833 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
834 if (mount_mode == MOUNT_EXTERNAL_NONE) {
835 return;
836 }
837
838 const userid_t user_id = multiuser_get_user_id(uid);
839 const std::string user_source = StringPrintf("/mnt/user/%d", user_id);
840 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
841 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
842 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
843 // These bits should be consistent with what is set in vold in
844 // Utils#MountUserFuse on FUSE volume mount
845 PrepareDir(user_source, 0710, user_id ? AID_ROOT : AID_SHELL,
846 multiuser_get_uid(user_id, AID_EVERYBODY), fail_fn);
847
848 bool isAppDataIsolationEnabled = GetBoolProperty(kVoldAppDataIsolation, false);
849
850 if (mount_mode == MOUNT_EXTERNAL_PASS_THROUGH) {
851 const std::string pass_through_source = StringPrintf("/mnt/pass_through/%d", user_id);
852 PrepareDir(pass_through_source, 0710, AID_ROOT, AID_MEDIA_RW, fail_fn);
853 BindMount(pass_through_source, "/storage", fail_fn);
854 } else if (mount_mode == MOUNT_EXTERNAL_INSTALLER) {
855 const std::string installer_source = StringPrintf("/mnt/installer/%d", user_id);
856 BindMount(installer_source, "/storage", fail_fn);
857 } else if (isAppDataIsolationEnabled && mount_mode == MOUNT_EXTERNAL_ANDROID_WRITABLE) {
858 const std::string writable_source = StringPrintf("/mnt/androidwritable/%d", user_id);
859 BindMount(writable_source, "/storage", fail_fn);
860 } else {
861 BindMount(user_source, "/storage", fail_fn);
862 }
863 }
864
865 // Utility to close down the Zygote socket file descriptors while
866 // the child is still running as root with Zygote's privileges. Each
867 // descriptor (if any) is closed via dup3(), replacing it with a valid
868 // (open) descriptor to /dev/null.
869
DetachDescriptors(JNIEnv * env,const std::vector<int> & fds_to_close,fail_fn_t fail_fn)870 static void DetachDescriptors(JNIEnv* env,
871 const std::vector<int>& fds_to_close,
872 fail_fn_t fail_fn) {
873
874 if (fds_to_close.size() > 0) {
875 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
876 if (devnull_fd == -1) {
877 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
878 }
879
880 for (int fd : fds_to_close) {
881 ALOGV("Switching descriptor %d to /dev/null", fd);
882 if (TEMP_FAILURE_RETRY(dup3(devnull_fd, fd, O_CLOEXEC)) == -1) {
883 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
884 }
885 }
886 }
887 }
888
SetThreadName(const std::string & thread_name)889 void SetThreadName(const std::string& thread_name) {
890 bool hasAt = false;
891 bool hasDot = false;
892
893 for (const char str_el : thread_name) {
894 if (str_el == '.') {
895 hasDot = true;
896 } else if (str_el == '@') {
897 hasAt = true;
898 }
899 }
900
901 const char* name_start_ptr = thread_name.c_str();
902 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
903 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
904 }
905
906 // pthread_setname_np fails rather than truncating long strings.
907 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
908 strlcpy(buf, name_start_ptr, sizeof(buf));
909 errno = pthread_setname_np(pthread_self(), buf);
910 if (errno != 0) {
911 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
912 }
913 // Update base::logging default tag.
914 android::base::SetDefaultTag(buf);
915 }
916
917 /**
918 * A helper method for converting managed strings to native strings. A fatal
919 * error is generated if a problem is encountered in extracting a non-null
920 * string.
921 *
922 * @param env Managed runtime environment
923 * @param process_name A native representation of the process name
924 * @param managed_process_name A managed representation of the process name
925 * @param managed_string The managed string to extract
926 *
927 * @return An empty option if the managed string is null. A optional-wrapped
928 * string otherwise.
929 */
ExtractJString(JNIEnv * env,const char * process_name,jstring managed_process_name,jstring managed_string)930 static std::optional<std::string> ExtractJString(JNIEnv* env,
931 const char* process_name,
932 jstring managed_process_name,
933 jstring managed_string) {
934 if (managed_string == nullptr) {
935 return std::nullopt;
936 } else {
937 ScopedUtfChars scoped_string_chars(env, managed_string);
938
939 if (scoped_string_chars.c_str() != nullptr) {
940 return std::optional<std::string>(scoped_string_chars.c_str());
941 } else {
942 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
943 }
944 }
945 }
946
947 /**
948 * A helper method for converting managed string arrays to native vectors. A
949 * fatal error is generated if a problem is encountered in extracting a non-null array.
950 *
951 * @param env Managed runtime environment
952 * @param process_name A native representation of the process name
953 * @param managed_process_name A managed representation of the process name
954 * @param managed_array The managed integer array to extract
955 *
956 * @return An empty option if the managed array is null. A optional-wrapped
957 * vector otherwise.
958 */
ExtractJIntArray(JNIEnv * env,const char * process_name,jstring managed_process_name,jintArray managed_array)959 static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
960 const char* process_name,
961 jstring managed_process_name,
962 jintArray managed_array) {
963 if (managed_array == nullptr) {
964 return std::nullopt;
965 } else {
966 ScopedIntArrayRO managed_array_handle(env, managed_array);
967
968 if (managed_array_handle.get() != nullptr) {
969 std::vector<int> native_array;
970 native_array.reserve(managed_array_handle.size());
971
972 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
973 native_array.push_back(managed_array_handle[array_index]);
974 }
975
976 return std::move(native_array);
977
978 } else {
979 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
980 }
981 }
982 }
983
984 /**
985 * A utility function for blocking signals.
986 *
987 * @param signum Signal number to block
988 * @param fail_fn Fatal error reporting function
989 *
990 * @see ZygoteFailure
991 */
BlockSignal(int signum,fail_fn_t fail_fn)992 static void BlockSignal(int signum, fail_fn_t fail_fn) {
993 sigset_t sigs;
994 sigemptyset(&sigs);
995 sigaddset(&sigs, signum);
996
997 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
998 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
999 }
1000 }
1001
1002
1003 /**
1004 * A utility function for unblocking signals.
1005 *
1006 * @param signum Signal number to unblock
1007 * @param fail_fn Fatal error reporting function
1008 *
1009 * @see ZygoteFailure
1010 */
UnblockSignal(int signum,fail_fn_t fail_fn)1011 static void UnblockSignal(int signum, fail_fn_t fail_fn) {
1012 sigset_t sigs;
1013 sigemptyset(&sigs);
1014 sigaddset(&sigs, signum);
1015
1016 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
1017 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
1018 }
1019 }
1020
ClearUsapTable()1021 static void ClearUsapTable() {
1022 for (UsapTableEntry& entry : gUsapTable) {
1023 entry.Clear();
1024 }
1025
1026 gUsapPoolCount = 0;
1027 }
1028
1029 // Create an app data directory over tmpfs overlayed CE / DE storage, and bind mount it
1030 // from the actual app data directory in data mirror.
createAndMountAppData(std::string_view package_name,std::string_view mirror_pkg_dir_name,std::string_view mirror_data_path,std::string_view actual_data_path,fail_fn_t fail_fn,bool call_fail_fn)1031 static bool createAndMountAppData(std::string_view package_name,
1032 std::string_view mirror_pkg_dir_name, std::string_view mirror_data_path,
1033 std::string_view actual_data_path, fail_fn_t fail_fn, bool call_fail_fn) {
1034
1035 char mirrorAppDataPath[PATH_MAX];
1036 char actualAppDataPath[PATH_MAX];
1037 snprintf(mirrorAppDataPath, PATH_MAX, "%s/%s", mirror_data_path.data(),
1038 mirror_pkg_dir_name.data());
1039 snprintf(actualAppDataPath, PATH_MAX, "%s/%s", actual_data_path.data(), package_name.data());
1040
1041 PrepareDir(actualAppDataPath, 0700, AID_ROOT, AID_ROOT, fail_fn);
1042
1043 // Bind mount from original app data directory in mirror.
1044 if (call_fail_fn) {
1045 BindMount(mirrorAppDataPath, actualAppDataPath, fail_fn);
1046 } else if(!BindMount(mirrorAppDataPath, actualAppDataPath)) {
1047 ALOGW("Failed to mount %s to %s: %s",
1048 mirrorAppDataPath, actualAppDataPath, strerror(errno));
1049 return false;
1050 }
1051 return true;
1052 }
1053
1054 // There is an app data directory over tmpfs overlaid CE / DE storage
1055 // bind mount it from the actual app data directory in data mirror.
mountAppData(std::string_view package_name,std::string_view mirror_pkg_dir_name,std::string_view mirror_data_path,std::string_view actual_data_path,fail_fn_t fail_fn)1056 static void mountAppData(std::string_view package_name,
1057 std::string_view mirror_pkg_dir_name, std::string_view mirror_data_path,
1058 std::string_view actual_data_path, fail_fn_t fail_fn) {
1059
1060 char mirrorAppDataPath[PATH_MAX];
1061 char actualAppDataPath[PATH_MAX];
1062 snprintf(mirrorAppDataPath, PATH_MAX, "%s/%s", mirror_data_path.data(),
1063 mirror_pkg_dir_name.data());
1064 snprintf(actualAppDataPath, PATH_MAX, "%s/%s", actual_data_path.data(), package_name.data());
1065
1066 // Bind mount from original app data directory in mirror.
1067 BindMount(mirrorAppDataPath, actualAppDataPath, fail_fn);
1068 }
1069
1070 // Get the directory name stored in /data/data. If device is unlocked it should be the same as
1071 // package name, otherwise it will be an encrypted name but with same inode number.
getAppDataDirName(std::string_view parent_path,std::string_view package_name,long long ce_data_inode,fail_fn_t fail_fn)1072 static std::string getAppDataDirName(std::string_view parent_path, std::string_view package_name,
1073 long long ce_data_inode, fail_fn_t fail_fn) {
1074 // Check if directory exists
1075 char tmpPath[PATH_MAX];
1076 snprintf(tmpPath, PATH_MAX, "%s/%s", parent_path.data(), package_name.data());
1077 struct stat s;
1078 int err = stat(tmpPath, &s);
1079 if (err == 0) {
1080 // Directory exists, so return the directory name
1081 return package_name.data();
1082 } else {
1083 if (errno != ENOENT) {
1084 fail_fn(CREATE_ERROR("Unexpected error in getAppDataDirName: %s", strerror(errno)));
1085 return nullptr;
1086 }
1087 {
1088 // Directory doesn't exist, try to search the name from inode
1089 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(parent_path.data()), closedir);
1090 if (dir == nullptr) {
1091 fail_fn(CREATE_ERROR("Failed to opendir %s", parent_path.data()));
1092 }
1093 struct dirent* ent;
1094 while ((ent = readdir(dir.get()))) {
1095 if (ent->d_ino == ce_data_inode) {
1096 return ent->d_name;
1097 }
1098 }
1099 }
1100
1101 // Fallback due to b/145989852, ce_data_inode stored in package manager may be corrupted
1102 // if ino_t is 32 bits.
1103 ino_t fixed_ce_data_inode = 0;
1104 if ((ce_data_inode & UPPER_HALF_WORD_MASK) == UPPER_HALF_WORD_MASK) {
1105 fixed_ce_data_inode = ce_data_inode & LOWER_HALF_WORD_MASK;
1106 } else if ((ce_data_inode & LOWER_HALF_WORD_MASK) == LOWER_HALF_WORD_MASK) {
1107 fixed_ce_data_inode = ((ce_data_inode >> 32) & LOWER_HALF_WORD_MASK);
1108 }
1109 if (fixed_ce_data_inode != 0) {
1110 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(parent_path.data()), closedir);
1111 if (dir == nullptr) {
1112 fail_fn(CREATE_ERROR("Failed to opendir %s", parent_path.data()));
1113 }
1114 struct dirent* ent;
1115 while ((ent = readdir(dir.get()))) {
1116 if (ent->d_ino == fixed_ce_data_inode) {
1117 long long d_ino = ent->d_ino;
1118 ALOGW("Fallback success inode %lld -> %lld", ce_data_inode, d_ino);
1119 return ent->d_name;
1120 }
1121 }
1122 }
1123 // Fallback done
1124
1125 fail_fn(CREATE_ERROR("Unable to find %s:%lld in %s", package_name.data(),
1126 ce_data_inode, parent_path.data()));
1127 return nullptr;
1128 }
1129 }
1130
1131 // Isolate app's data directory, by mounting a tmpfs on CE DE storage,
1132 // and create and bind mount app data in related_packages.
isolateAppDataPerPackage(int userId,std::string_view package_name,std::string_view volume_uuid,long long ce_data_inode,std::string_view actualCePath,std::string_view actualDePath,fail_fn_t fail_fn)1133 static void isolateAppDataPerPackage(int userId, std::string_view package_name,
1134 std::string_view volume_uuid, long long ce_data_inode, std::string_view actualCePath,
1135 std::string_view actualDePath, fail_fn_t fail_fn) {
1136
1137 char mirrorCePath[PATH_MAX];
1138 char mirrorDePath[PATH_MAX];
1139 char mirrorCeParent[PATH_MAX];
1140 snprintf(mirrorCeParent, PATH_MAX, "/data_mirror/data_ce/%s", volume_uuid.data());
1141 snprintf(mirrorCePath, PATH_MAX, "%s/%d", mirrorCeParent, userId);
1142 snprintf(mirrorDePath, PATH_MAX, "/data_mirror/data_de/%s/%d", volume_uuid.data(), userId);
1143
1144 createAndMountAppData(package_name, package_name, mirrorDePath, actualDePath, fail_fn,
1145 true /*call_fail_fn*/);
1146
1147 std::string ce_data_path = getAppDataDirName(mirrorCePath, package_name, ce_data_inode, fail_fn);
1148 if (!createAndMountAppData(package_name, ce_data_path, mirrorCePath, actualCePath, fail_fn,
1149 false /*call_fail_fn*/)) {
1150 // CE might unlocks and the name is decrypted
1151 // get the name and mount again
1152 ce_data_path=getAppDataDirName(mirrorCePath, package_name, ce_data_inode, fail_fn);
1153 mountAppData(package_name, ce_data_path, mirrorCePath, actualCePath, fail_fn);
1154 }
1155 }
1156
1157 // Relabel directory
relabelDir(const char * path,const char * context,fail_fn_t fail_fn)1158 static void relabelDir(const char* path, const char* context, fail_fn_t fail_fn) {
1159 if (setfilecon(path, context) != 0) {
1160 fail_fn(CREATE_ERROR("Failed to setfilecon %s %s", path, strerror(errno)));
1161 }
1162 }
1163
1164 // Relabel the subdirectories and symlinks in the given directory, non-recursively.
relabelSubdirs(const char * path,const char * context,fail_fn_t fail_fn)1165 static void relabelSubdirs(const char* path, const char* context, fail_fn_t fail_fn) {
1166 DIR* dir = opendir(path);
1167 if (dir == nullptr) {
1168 fail_fn(CREATE_ERROR("Failed to opendir %s", path));
1169 }
1170 struct dirent* ent;
1171 while ((ent = readdir(dir))) {
1172 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1173 auto filePath = StringPrintf("%s/%s", path, ent->d_name);
1174 if (ent->d_type == DT_DIR) {
1175 relabelDir(filePath.c_str(), context, fail_fn);
1176 } else if (ent->d_type == DT_LNK) {
1177 if (lsetfilecon(filePath.c_str(), context) != 0) {
1178 fail_fn(CREATE_ERROR("Failed to lsetfilecon %s %s", filePath.c_str(), strerror(errno)));
1179 }
1180 } else {
1181 fail_fn(CREATE_ERROR("Unexpected type: %d %s", ent->d_type, filePath.c_str()));
1182 }
1183 }
1184 closedir(dir);
1185 }
1186
1187 /**
1188 * Hide the CE and DE data directories of non-related apps.
1189 *
1190 * Without this, apps can detect if any app is installed by trying to "touch" the app's CE
1191 * or DE data directory, e.g. /data/data/com.whatsapp. This fails with EACCES if the app
1192 * is installed, or ENOENT if it's not. Traditional file permissions or SELinux can only
1193 * block accessing those directories but can't fix fingerprinting like this.
1194 *
1195 * Instead, we hide non-related apps' data directories from the filesystem entirely by
1196 * mounting tmpfs instances over their parent directories and bind-mounting in just the
1197 * needed app data directories. This is done in a private mount namespace.
1198 *
1199 * Steps:
1200 * (1) Collect a list of all related apps (apps with same uid and allowlisted apps) data info
1201 * (package name, data stored volume uuid, and inode number of its CE data directory)
1202 * (2) Mount tmpfs on /data/data and /data/user{,_de}, and on /mnt/expand/$volume/user{,_de}
1203 * for all adoptable storage volumes. This hides all app data directories.
1204 * (3) For each related app, create stubs for its data directories in the relevant tmpfs
1205 * instances, then bind mount in the actual directories from /data_mirror. This works
1206 * for both the CE and DE directories. DE storage is always unlocked, whereas the
1207 * app's CE directory can be found via inode number if CE storage is locked.
1208 *
1209 * Example assuming user 0, app "com.android.foo", no shared uid, and no adoptable storage:
1210 * (1) Info = ["com.android.foo", "null" (volume uuid "null"=default), "123456" (inode number)]
1211 * (2) Mount tmpfs on /data/data, /data/user, and /data/user_de.
1212 * (3) For DE storage, create a directory /data/user_de/0/com.android.foo and bind mount
1213 * /data_mirror/data_de/0/com.android.foo onto it.
1214 * (4) Do similar for CE storage. But if the device is in direct boot mode, then CE
1215 * storage will be locked, so the app's CE data directory won't exist at the usual
1216 * path /data_mirror/data_ce/0/com.android.foo. It will still exist in
1217 * /data_mirror/data_ce/0, but its filename will be an unpredictable no-key name. In
1218 * this case, we use the inode number to find the right directory instead. Note that
1219 * the bind-mounted app CE data directory will remain locked. It will be unlocked
1220 * automatically if/when the user's CE storage is unlocked, since adding an encryption
1221 * key takes effect on a whole filesystem instance including all its mounts.
1222 */
isolateAppData(JNIEnv * env,const std::vector<std::string> & merged_data_info_list,uid_t uid,const char * process_name,jstring managed_nice_name,fail_fn_t fail_fn)1223 static void isolateAppData(JNIEnv* env, const std::vector<std::string>& merged_data_info_list,
1224 uid_t uid, const char* process_name,
1225 jstring managed_nice_name, fail_fn_t fail_fn) {
1226
1227 const userid_t userId = multiuser_get_user_id(uid);
1228
1229 int size = merged_data_info_list.size();
1230
1231 // Mount tmpfs on all possible data directories, so app no longer see the original apps data.
1232 char internalCePath[PATH_MAX];
1233 char internalLegacyCePath[PATH_MAX];
1234 char internalDePath[PATH_MAX];
1235 char externalPrivateMountPath[PATH_MAX];
1236
1237 snprintf(internalCePath, PATH_MAX, "/data/user");
1238 snprintf(internalLegacyCePath, PATH_MAX, "/data/data");
1239 snprintf(internalDePath, PATH_MAX, "/data/user_de");
1240 snprintf(externalPrivateMountPath, PATH_MAX, "/mnt/expand");
1241
1242 // Get the "u:object_r:system_userdir_file:s0" security context. This can be
1243 // gotten from several different places; we use /data/user.
1244 char* dataUserdirContext = nullptr;
1245 if (getfilecon(internalCePath, &dataUserdirContext) < 0) {
1246 fail_fn(CREATE_ERROR("Unable to getfilecon on %s %s", internalCePath,
1247 strerror(errno)));
1248 }
1249 // Get the "u:object_r:system_data_file:s0" security context. This can be
1250 // gotten from several different places; we use /data/misc.
1251 char* dataFileContext = nullptr;
1252 if (getfilecon("/data/misc", &dataFileContext) < 0) {
1253 fail_fn(CREATE_ERROR("Unable to getfilecon on /data/misc %s", strerror(errno)));
1254 }
1255
1256 MountAppDataTmpFs(internalLegacyCePath, fail_fn);
1257 MountAppDataTmpFs(internalCePath, fail_fn);
1258 MountAppDataTmpFs(internalDePath, fail_fn);
1259
1260 // Mount tmpfs on all external vols DE and CE storage
1261 DIR* dir = opendir(externalPrivateMountPath);
1262 if (dir == nullptr) {
1263 fail_fn(CREATE_ERROR("Failed to opendir %s", externalPrivateMountPath));
1264 }
1265 struct dirent* ent;
1266 while ((ent = readdir(dir))) {
1267 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1268 if (ent->d_type != DT_DIR) {
1269 fail_fn(CREATE_ERROR("Unexpected type: %d %s", ent->d_type, ent->d_name));
1270 }
1271 auto volPath = StringPrintf("%s/%s", externalPrivateMountPath, ent->d_name);
1272 auto cePath = StringPrintf("%s/user", volPath.c_str());
1273 auto dePath = StringPrintf("%s/user_de", volPath.c_str());
1274 // Wait until dir user is created.
1275 WaitUntilDirReady(cePath.c_str(), fail_fn);
1276 MountAppDataTmpFs(cePath.c_str(), fail_fn);
1277 // Wait until dir user_de is created.
1278 WaitUntilDirReady(dePath.c_str(), fail_fn);
1279 MountAppDataTmpFs(dePath.c_str(), fail_fn);
1280 }
1281 closedir(dir);
1282
1283 // No bind mounting of app data should occur in the case of a sandbox process since SDK sandboxes
1284 // should not be able to read app data. Tmpfs was mounted however since a sandbox should not have
1285 // access to app data.
1286 appid_t appId = multiuser_get_app_id(uid);
1287 bool isSdkSandboxProcess =
1288 (appId >= AID_SDK_SANDBOX_PROCESS_START && appId <= AID_SDK_SANDBOX_PROCESS_END);
1289 if (!isSdkSandboxProcess) {
1290 // Prepare default dirs for user 0 as user 0 always exists.
1291 int result = symlink("/data/data", "/data/user/0");
1292 if (result != 0) {
1293 fail_fn(CREATE_ERROR("Failed to create symlink /data/user/0 %s", strerror(errno)));
1294 }
1295 PrepareDirIfNotPresent("/data/user_de/0", DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1296 fail_fn);
1297
1298 for (int i = 0; i < size; i += 3) {
1299 std::string const& packageName = merged_data_info_list[i];
1300 std::string const& volUuid = merged_data_info_list[i + 1];
1301 std::string const& inode = merged_data_info_list[i + 2];
1302
1303 std::string::size_type sz;
1304 long long ceDataInode = std::stoll(inode, &sz);
1305
1306 std::string actualCePath, actualDePath;
1307 if (volUuid.compare("null") != 0) {
1308 // Volume that is stored in /mnt/expand
1309 char volPath[PATH_MAX];
1310 char volCePath[PATH_MAX];
1311 char volDePath[PATH_MAX];
1312 char volCeUserPath[PATH_MAX];
1313 char volDeUserPath[PATH_MAX];
1314
1315 snprintf(volPath, PATH_MAX, "/mnt/expand/%s", volUuid.c_str());
1316 snprintf(volCePath, PATH_MAX, "%s/user", volPath);
1317 snprintf(volDePath, PATH_MAX, "%s/user_de", volPath);
1318 snprintf(volCeUserPath, PATH_MAX, "%s/%d", volCePath, userId);
1319 snprintf(volDeUserPath, PATH_MAX, "%s/%d", volDePath, userId);
1320
1321 PrepareDirIfNotPresent(volPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1322 fail_fn);
1323 PrepareDirIfNotPresent(volCePath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1324 fail_fn);
1325 PrepareDirIfNotPresent(volDePath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1326 fail_fn);
1327 PrepareDirIfNotPresent(volCeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1328 fail_fn);
1329 PrepareDirIfNotPresent(volDeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT,
1330 fail_fn);
1331
1332 actualCePath = volCeUserPath;
1333 actualDePath = volDeUserPath;
1334 } else {
1335 // Internal volume that stored in /data
1336 char internalCeUserPath[PATH_MAX];
1337 char internalDeUserPath[PATH_MAX];
1338 snprintf(internalCeUserPath, PATH_MAX, "/data/user/%d", userId);
1339 snprintf(internalDeUserPath, PATH_MAX, "/data/user_de/%d", userId);
1340 // If it's not user 0, create /data/user/$USER.
1341 if (userId == 0) {
1342 actualCePath = internalLegacyCePath;
1343 } else {
1344 PrepareDirIfNotPresent(internalCeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT,
1345 AID_ROOT, fail_fn);
1346 actualCePath = internalCeUserPath;
1347 }
1348 PrepareDirIfNotPresent(internalDeUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT,
1349 AID_ROOT, fail_fn);
1350 actualDePath = internalDeUserPath;
1351 }
1352 isolateAppDataPerPackage(userId, packageName, volUuid, ceDataInode, actualCePath,
1353 actualDePath, fail_fn);
1354 }
1355 }
1356
1357 // We set the label AFTER everything is done, as we are applying
1358 // the file operations on tmpfs. If we set the label when we mount
1359 // tmpfs, SELinux will not happy as we are changing system_data_files.
1360 // Relabel dir under /data/user, including /data/user/0
1361 relabelSubdirs(internalCePath, dataFileContext, fail_fn);
1362
1363 // Relabel /data/user
1364 relabelDir(internalCePath, dataUserdirContext, fail_fn);
1365
1366 // Relabel /data/data
1367 relabelDir(internalLegacyCePath, dataFileContext, fail_fn);
1368
1369 // Relabel subdirectories of /data/user_de
1370 relabelSubdirs(internalDePath, dataFileContext, fail_fn);
1371
1372 // Relabel /data/user_de
1373 relabelDir(internalDePath, dataUserdirContext, fail_fn);
1374
1375 // Relabel CE and DE dirs under /mnt/expand
1376 dir = opendir(externalPrivateMountPath);
1377 if (dir == nullptr) {
1378 fail_fn(CREATE_ERROR("Failed to opendir %s", externalPrivateMountPath));
1379 }
1380 while ((ent = readdir(dir))) {
1381 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1382 auto volPath = StringPrintf("%s/%s", externalPrivateMountPath, ent->d_name);
1383 auto cePath = StringPrintf("%s/user", volPath.c_str());
1384 auto dePath = StringPrintf("%s/user_de", volPath.c_str());
1385
1386 relabelSubdirs(cePath.c_str(), dataFileContext, fail_fn);
1387 relabelDir(cePath.c_str(), dataUserdirContext, fail_fn);
1388 relabelSubdirs(dePath.c_str(), dataFileContext, fail_fn);
1389 relabelDir(dePath.c_str(), dataUserdirContext, fail_fn);
1390 }
1391 closedir(dir);
1392
1393 freecon(dataUserdirContext);
1394 freecon(dataFileContext);
1395 }
1396
1397 /**
1398 * Without sdk sandbox data isolation, the sandbox could detect if another app is installed on the
1399 * system by "touching" other data directories like /data/misc_ce/0/sdksandbox/com.whatsapp, similar
1400 * to apps without app data isolation (see {@link #isolateAppData()}).
1401 *
1402 * To prevent this, tmpfs is mounted onto misc_ce and misc_de directories on all possible volumes in
1403 * a separate mount namespace. The sandbox directory path is then created containing the name of the
1404 * client app package associated with the sdk sandbox. The contents for this (sdk level storage and
1405 * shared sdk storage) are bind mounted from the sandbox data mirror.
1406 */
isolateSdkSandboxData(JNIEnv * env,jobjectArray pkg_data_info_list,uid_t uid,const char * process_name,jstring managed_nice_name,fail_fn_t fail_fn)1407 static void isolateSdkSandboxData(JNIEnv* env, jobjectArray pkg_data_info_list, uid_t uid,
1408 const char* process_name, jstring managed_nice_name,
1409 fail_fn_t fail_fn) {
1410 const userid_t userId = multiuser_get_user_id(uid);
1411
1412 int size = (pkg_data_info_list != nullptr) ? env->GetArrayLength(pkg_data_info_list) : 0;
1413 // The sandbox should only have information of one associated client app (package, uuid, inode)
1414 if (size != 3) {
1415 fail_fn(CREATE_ERROR(
1416 "Unable to isolate sandbox data, incorrect associated app information"));
1417 }
1418
1419 auto extract_fn = [env, process_name, managed_nice_name,
1420 pkg_data_info_list](int info_list_idx) {
1421 jstring jstr = (jstring)(env->GetObjectArrayElement(pkg_data_info_list, info_list_idx));
1422 return ExtractJString(env, process_name, managed_nice_name, jstr).value();
1423 };
1424 std::string packageName = extract_fn(0);
1425 std::string volUuid = extract_fn(1);
1426
1427 char internalCePath[PATH_MAX];
1428 char internalDePath[PATH_MAX];
1429 char externalPrivateMountPath[PATH_MAX];
1430 snprintf(internalCePath, PATH_MAX, "/data/misc_ce");
1431 snprintf(internalDePath, PATH_MAX, "/data/misc_de");
1432 snprintf(externalPrivateMountPath, PATH_MAX, "/mnt/expand");
1433
1434 char ceUserPath[PATH_MAX];
1435 char deUserPath[PATH_MAX];
1436 if (volUuid != "null") {
1437 snprintf(ceUserPath, PATH_MAX, "%s/%s/misc_ce/%d", externalPrivateMountPath,
1438 volUuid.c_str(), userId);
1439 snprintf(deUserPath, PATH_MAX, "%s/%s/misc_de/%d", externalPrivateMountPath,
1440 volUuid.c_str(), userId);
1441 } else {
1442 snprintf(ceUserPath, PATH_MAX, "%s/%d", internalCePath, userId);
1443 snprintf(deUserPath, PATH_MAX, "%s/%d", internalDePath, userId);
1444 }
1445
1446 char ceSandboxPath[PATH_MAX];
1447 char deSandboxPath[PATH_MAX];
1448 snprintf(ceSandboxPath, PATH_MAX, "%s/sdksandbox", ceUserPath);
1449 snprintf(deSandboxPath, PATH_MAX, "%s/sdksandbox", deUserPath);
1450
1451 // If the client app using the sandbox has been installed when the device is locked and the
1452 // sandbox starts up when the device is locked, sandbox storage might not have been created.
1453 // In that case, mount tmpfs for data isolation, but don't bind mount.
1454 bool bindMountCeSandboxDataDirs = true;
1455 bool bindMountDeSandboxDataDirs = true;
1456 if (access(ceSandboxPath, F_OK) != 0) {
1457 bindMountCeSandboxDataDirs = false;
1458 }
1459 if (access(deSandboxPath, F_OK) != 0) {
1460 bindMountDeSandboxDataDirs = false;
1461 }
1462
1463 char* context = nullptr;
1464 char* userContext = nullptr;
1465 char* sandboxContext = nullptr;
1466 if (getfilecon(internalDePath, &context) < 0) {
1467 fail_fn(CREATE_ERROR("Unable to getfilecon on %s %s", internalDePath, strerror(errno)));
1468 }
1469 if (bindMountDeSandboxDataDirs) {
1470 if (getfilecon(deUserPath, &userContext) < 0) {
1471 fail_fn(CREATE_ERROR("Unable to getfilecon on %s %s", deUserPath, strerror(errno)));
1472 }
1473 if (getfilecon(deSandboxPath, &sandboxContext) < 0) {
1474 fail_fn(CREATE_ERROR("Unable to getfilecon on %s %s", deSandboxPath, strerror(errno)));
1475 }
1476 }
1477
1478 MountAppDataTmpFs(internalCePath, fail_fn);
1479 MountAppDataTmpFs(internalDePath, fail_fn);
1480
1481 // Mount tmpfs on all external volumes
1482 DIR* dir = opendir(externalPrivateMountPath);
1483 if (dir == nullptr) {
1484 fail_fn(CREATE_ERROR("Failed to opendir %s", externalPrivateMountPath));
1485 }
1486 struct dirent* ent;
1487 while ((ent = readdir(dir))) {
1488 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1489 if (ent->d_type != DT_DIR) {
1490 fail_fn(CREATE_ERROR("Unexpected type: %d %s", ent->d_type, ent->d_name));
1491 }
1492 auto volPath = StringPrintf("%s/%s", externalPrivateMountPath, ent->d_name);
1493 auto externalCePath = StringPrintf("%s/misc_ce", volPath.c_str());
1494 auto externalDePath = StringPrintf("%s/misc_de", volPath.c_str());
1495
1496 WaitUntilDirReady(externalCePath.c_str(), fail_fn);
1497 MountAppDataTmpFs(externalCePath.c_str(), fail_fn);
1498 WaitUntilDirReady(externalDePath.c_str(), fail_fn);
1499 MountAppDataTmpFs(externalDePath.c_str(), fail_fn);
1500 }
1501 closedir(dir);
1502
1503 char mirrorCeSandboxPath[PATH_MAX];
1504 char mirrorDeSandboxPath[PATH_MAX];
1505 snprintf(mirrorCeSandboxPath, PATH_MAX, "/data_mirror/misc_ce/%s/%d/sdksandbox",
1506 volUuid.c_str(), userId);
1507 snprintf(mirrorDeSandboxPath, PATH_MAX, "/data_mirror/misc_de/%s/%d/sdksandbox",
1508 volUuid.c_str(), userId);
1509
1510 if (bindMountCeSandboxDataDirs) {
1511 PrepareDir(ceUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1512 PrepareDir(ceSandboxPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1513 // TODO(b/231322885): Use inode numbers to find the correct app path when the device locked.
1514 createAndMountAppData(packageName, packageName, mirrorCeSandboxPath, ceSandboxPath, fail_fn,
1515 true /*call_fail_fn*/);
1516
1517 relabelDir(ceSandboxPath, sandboxContext, fail_fn);
1518 relabelDir(ceUserPath, userContext, fail_fn);
1519 }
1520 if (bindMountDeSandboxDataDirs) {
1521 PrepareDir(deUserPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1522 PrepareDir(deSandboxPath, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1523 createAndMountAppData(packageName, packageName, mirrorDeSandboxPath, deSandboxPath, fail_fn,
1524 true /*call_fail_fn*/);
1525
1526 relabelDir(deSandboxPath, sandboxContext, fail_fn);
1527 relabelDir(deUserPath, userContext, fail_fn);
1528 }
1529
1530 // We set the label AFTER everything is done, as we are applying
1531 // the file operations on tmpfs. If we set the label when we mount
1532 // tmpfs, SELinux will not happy as we are changing system_data_files.
1533 relabelDir(internalCePath, context, fail_fn);
1534 relabelDir(internalDePath, context, fail_fn);
1535
1536 // Relabel CE and DE dirs under /mnt/expand
1537 dir = opendir(externalPrivateMountPath);
1538 if (dir == nullptr) {
1539 fail_fn(CREATE_ERROR("Failed to opendir %s", externalPrivateMountPath));
1540 }
1541 while ((ent = readdir(dir))) {
1542 if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
1543 auto volPath = StringPrintf("%s/%s", externalPrivateMountPath, ent->d_name);
1544 auto externalCePath = StringPrintf("%s/misc_ce", volPath.c_str());
1545 auto externalDePath = StringPrintf("%s/misc_de", volPath.c_str());
1546 relabelDir(externalCePath.c_str(), context, fail_fn);
1547 relabelDir(externalDePath.c_str(), context, fail_fn);
1548 }
1549 closedir(dir);
1550
1551 if (bindMountDeSandboxDataDirs) {
1552 freecon(sandboxContext);
1553 freecon(userContext);
1554 }
1555 freecon(context);
1556 }
1557
insertPackagesToMergedList(JNIEnv * env,std::vector<std::string> & merged_data_info_list,jobjectArray data_info_list,const char * process_name,jstring managed_nice_name,fail_fn_t fail_fn)1558 static void insertPackagesToMergedList(JNIEnv* env,
1559 std::vector<std::string>& merged_data_info_list,
1560 jobjectArray data_info_list, const char* process_name,
1561 jstring managed_nice_name, fail_fn_t fail_fn) {
1562
1563 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
1564
1565 int size = (data_info_list != nullptr) ? env->GetArrayLength(data_info_list) : 0;
1566 // Size should be a multiple of 3, as it contains list of <package_name, volume_uuid, inode>
1567 if ((size % 3) != 0) {
1568 fail_fn(CREATE_ERROR("Wrong data_info_list size %d", size));
1569 }
1570
1571 for (int i = 0; i < size; i += 3) {
1572 jstring package_str = (jstring) (env->GetObjectArrayElement(data_info_list, i));
1573 std::string packageName = extract_fn(package_str).value();
1574 merged_data_info_list.push_back(packageName);
1575
1576 jstring vol_str = (jstring) (env->GetObjectArrayElement(data_info_list, i + 1));
1577 std::string volUuid = extract_fn(vol_str).value();
1578 merged_data_info_list.push_back(volUuid);
1579
1580 jstring inode_str = (jstring) (env->GetObjectArrayElement(data_info_list, i + 2));
1581 std::string inode = extract_fn(inode_str).value();
1582 merged_data_info_list.push_back(inode);
1583 }
1584 }
1585
isolateAppData(JNIEnv * env,jobjectArray pkg_data_info_list,jobjectArray allowlisted_data_info_list,uid_t uid,const char * process_name,jstring managed_nice_name,fail_fn_t fail_fn)1586 static void isolateAppData(JNIEnv* env, jobjectArray pkg_data_info_list,
1587 jobjectArray allowlisted_data_info_list, uid_t uid,
1588 const char* process_name, jstring managed_nice_name, fail_fn_t fail_fn) {
1589 std::vector<std::string> merged_data_info_list;
1590 insertPackagesToMergedList(env, merged_data_info_list, pkg_data_info_list, process_name,
1591 managed_nice_name, fail_fn);
1592 insertPackagesToMergedList(env, merged_data_info_list, allowlisted_data_info_list, process_name,
1593 managed_nice_name, fail_fn);
1594
1595 isolateAppData(env, merged_data_info_list, uid, process_name, managed_nice_name, fail_fn);
1596 }
1597
1598 /**
1599 * Like isolateAppData(), isolate jit profile directories, so apps don't see what
1600 * other apps are installed by reading content inside /data/misc/profiles/cur.
1601 *
1602 * The implementation is similar to isolateAppData(), it creates a tmpfs
1603 * on /data/misc/profiles/cur, and bind mounts related package profiles to it.
1604 */
isolateJitProfile(JNIEnv * env,jobjectArray pkg_data_info_list,uid_t uid,const char * process_name,jstring managed_nice_name,fail_fn_t fail_fn)1605 static void isolateJitProfile(JNIEnv* env, jobjectArray pkg_data_info_list,
1606 uid_t uid, const char* process_name, jstring managed_nice_name,
1607 fail_fn_t fail_fn) {
1608
1609 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
1610 const userid_t user_id = multiuser_get_user_id(uid);
1611
1612 int size = (pkg_data_info_list != nullptr) ? env->GetArrayLength(pkg_data_info_list) : 0;
1613 // Size should be a multiple of 3, as it contains list of <package_name, volume_uuid, inode>
1614 if ((size % 3) != 0) {
1615 fail_fn(CREATE_ERROR("Wrong pkg_inode_list size %d", size));
1616 }
1617
1618 // Mount (namespace) tmpfs on profile directory, so apps no longer access
1619 // the original profile directory anymore.
1620 MountAppDataTmpFs(kCurProfileDirPath, fail_fn);
1621 MountAppDataTmpFs(kRefProfileDirPath, fail_fn);
1622
1623 // Sandbox processes do not have JIT profile, so no data needs to be bind mounted. However, it
1624 // should still not have access to JIT profile, so tmpfs is mounted.
1625 appid_t appId = multiuser_get_app_id(uid);
1626 if (appId >= AID_SDK_SANDBOX_PROCESS_START && appId <= AID_SDK_SANDBOX_PROCESS_END) {
1627 return;
1628 }
1629
1630 // Create profile directory for this user.
1631 std::string actualCurUserProfile = StringPrintf("%s/%d", kCurProfileDirPath, user_id);
1632 PrepareDir(actualCurUserProfile, DEFAULT_DATA_DIR_PERMISSION, AID_ROOT, AID_ROOT, fail_fn);
1633
1634 for (int i = 0; i < size; i += 3) {
1635 jstring package_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i));
1636 std::string packageName = extract_fn(package_str).value();
1637
1638 std::string actualCurPackageProfile = StringPrintf("%s/%s", actualCurUserProfile.c_str(),
1639 packageName.c_str());
1640 std::string mirrorCurPackageProfile = StringPrintf("/data_mirror/cur_profiles/%d/%s",
1641 user_id, packageName.c_str());
1642 std::string actualRefPackageProfile = StringPrintf("%s/%s", kRefProfileDirPath,
1643 packageName.c_str());
1644 std::string mirrorRefPackageProfile = StringPrintf("/data_mirror/ref_profiles/%s",
1645 packageName.c_str());
1646
1647 if (access(mirrorCurPackageProfile.c_str(), F_OK) != 0) {
1648 ALOGW("Can't access app profile directory: %s", mirrorCurPackageProfile.c_str());
1649 continue;
1650 }
1651 if (access(mirrorRefPackageProfile.c_str(), F_OK) != 0) {
1652 ALOGW("Can't access app profile directory: %s", mirrorRefPackageProfile.c_str());
1653 continue;
1654 }
1655
1656 PrepareDir(actualCurPackageProfile, DEFAULT_DATA_DIR_PERMISSION, uid, uid, fail_fn);
1657 BindMount(mirrorCurPackageProfile, actualCurPackageProfile, fail_fn);
1658 PrepareDir(actualRefPackageProfile, DEFAULT_DATA_DIR_PERMISSION, uid, uid, fail_fn);
1659 BindMount(mirrorRefPackageProfile, actualRefPackageProfile, fail_fn);
1660 }
1661 }
1662
WaitUntilDirReady(const std::string & target,fail_fn_t fail_fn)1663 static void WaitUntilDirReady(const std::string& target, fail_fn_t fail_fn) {
1664 unsigned int sleepIntervalUs = STORAGE_DIR_CHECK_INIT_INTERVAL_US;
1665
1666 // This is just an approximate value as it doesn't need to be very accurate.
1667 unsigned int sleepTotalUs = 0;
1668
1669 const char* dir_path = target.c_str();
1670 while (sleepTotalUs < STORAGE_DIR_CHECK_TIMEOUT_US) {
1671 if (access(dir_path, F_OK) == 0) {
1672 return;
1673 }
1674 // Failed, so we add exponential backoff and retry
1675 usleep(sleepIntervalUs);
1676 sleepTotalUs += sleepIntervalUs;
1677 sleepIntervalUs = std::min<unsigned int>(
1678 sleepIntervalUs * STORAGE_DIR_CHECK_RETRY_MULTIPLIER,
1679 STORAGE_DIR_CHECK_MAX_INTERVAL_US);
1680 }
1681 // Last chance and get the latest errno if it fails.
1682 if (access(dir_path, F_OK) == 0) {
1683 return;
1684 }
1685 fail_fn(CREATE_ERROR("Error dir is not ready %s: %s", dir_path, strerror(errno)));
1686 }
1687
BindMountStorageToLowerFs(const userid_t user_id,const uid_t uid,const char * dir_name,const char * package,fail_fn_t fail_fn)1688 static void BindMountStorageToLowerFs(const userid_t user_id, const uid_t uid,
1689 const char* dir_name, const char* package, fail_fn_t fail_fn) {
1690 bool hasSdcardFs = IsSdcardfsUsed();
1691 std::string source;
1692 if (hasSdcardFs) {
1693 source = StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s", user_id, dir_name, package);
1694 } else {
1695 source = StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s", user_id, user_id, dir_name,
1696 package);
1697 }
1698
1699 // Directory might be not ready, as prepareStorageDirs() is running asynchronously in ProcessList,
1700 // so wait until dir is created.
1701 WaitUntilDirReady(source, fail_fn);
1702 std::string target = StringPrintf("/storage/emulated/%d/%s/%s", user_id, dir_name, package);
1703
1704 // As the parent is mounted as tmpfs, we need to create the target dir here.
1705 PrepareDirIfNotPresent(target, 0700, uid, uid, fail_fn);
1706
1707 if (access(source.c_str(), F_OK) != 0) {
1708 fail_fn(CREATE_ERROR("Error accessing %s: %s", source.c_str(), strerror(errno)));
1709 }
1710 if (access(target.c_str(), F_OK) != 0) {
1711 fail_fn(CREATE_ERROR("Error accessing %s: %s", target.c_str(), strerror(errno)));
1712 }
1713 BindMount(source, target, fail_fn);
1714 }
1715
1716 // Mount tmpfs on Android/data and Android/obb, then bind mount all app visible package
1717 // directories in data and obb directories.
BindMountStorageDirs(JNIEnv * env,jobjectArray pkg_data_info_list,uid_t uid,const char * process_name,jstring managed_nice_name,fail_fn_t fail_fn)1718 static void BindMountStorageDirs(JNIEnv* env, jobjectArray pkg_data_info_list,
1719 uid_t uid, const char* process_name, jstring managed_nice_name, fail_fn_t fail_fn) {
1720
1721 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
1722 const userid_t user_id = multiuser_get_user_id(uid);
1723
1724 // Fuse is ready, so we can start using fuse path.
1725 int size = (pkg_data_info_list != nullptr) ? env->GetArrayLength(pkg_data_info_list) : 0;
1726
1727 // Create tmpfs on Android/obb and Android/data so these 2 dirs won't enter fuse anymore.
1728 std::string androidObbDir = StringPrintf("/storage/emulated/%d/Android/obb", user_id);
1729 MountAppDataTmpFs(androidObbDir, fail_fn);
1730 std::string androidDataDir = StringPrintf("/storage/emulated/%d/Android/data", user_id);
1731 MountAppDataTmpFs(androidDataDir, fail_fn);
1732
1733 // Bind mount each package obb directory
1734 for (int i = 0; i < size; i += 3) {
1735 jstring package_str = (jstring) (env->GetObjectArrayElement(pkg_data_info_list, i));
1736 std::string packageName = extract_fn(package_str).value();
1737 BindMountStorageToLowerFs(user_id, uid, "Android/obb", packageName.c_str(), fail_fn);
1738 BindMountStorageToLowerFs(user_id, uid, "Android/data", packageName.c_str(), fail_fn);
1739 }
1740 }
1741
1742 // Utility routine to specialize a zygote child process.
SpecializeCommon(JNIEnv * env,uid_t uid,gid_t gid,jintArray gids,jint runtime_flags,jobjectArray rlimits,jlong permitted_capabilities,jlong effective_capabilities,jint mount_external,jstring managed_se_info,jstring managed_nice_name,bool is_system_server,bool is_child_zygote,jstring managed_instruction_set,jstring managed_app_data_dir,bool is_top_app,jobjectArray pkg_data_info_list,jobjectArray allowlisted_data_info_list,bool mount_data_dirs,bool mount_storage_dirs)1743 static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids, jint runtime_flags,
1744 jobjectArray rlimits, jlong permitted_capabilities,
1745 jlong effective_capabilities, jint mount_external,
1746 jstring managed_se_info, jstring managed_nice_name,
1747 bool is_system_server, bool is_child_zygote,
1748 jstring managed_instruction_set, jstring managed_app_data_dir,
1749 bool is_top_app, jobjectArray pkg_data_info_list,
1750 jobjectArray allowlisted_data_info_list, bool mount_data_dirs,
1751 bool mount_storage_dirs) {
1752 const char* process_name = is_system_server ? "system_server" : "zygote";
1753 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
1754 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
1755
1756 auto se_info = extract_fn(managed_se_info);
1757 auto nice_name = extract_fn(managed_nice_name);
1758 auto instruction_set = extract_fn(managed_instruction_set);
1759 auto app_data_dir = extract_fn(managed_app_data_dir);
1760
1761 // Keep capabilities across UID change, unless we're staying root.
1762 if (uid != 0) {
1763 EnableKeepCapabilities(fail_fn);
1764 }
1765
1766 SetInheritable(permitted_capabilities, fail_fn);
1767
1768 DropCapabilitiesBoundingSet(fail_fn);
1769
1770 bool need_pre_initialize_native_bridge = !is_system_server && instruction_set.has_value() &&
1771 android::NativeBridgeAvailable() &&
1772 // Native bridge may be already initialized if this
1773 // is an app forked from app-zygote.
1774 !android::NativeBridgeInitialized() &&
1775 android::NeedsNativeBridge(instruction_set.value().c_str());
1776
1777 MountEmulatedStorage(uid, mount_external, need_pre_initialize_native_bridge, fail_fn);
1778
1779 // Make sure app is running in its own mount namespace before isolating its data directories.
1780 ensureInAppMountNamespace(fail_fn);
1781
1782 // Isolate app data, jit profile and sandbox data directories by overlaying a tmpfs on those
1783 // dirs and bind mount all related packages separately.
1784 if (mount_data_dirs) {
1785 // Sdk sandbox data isolation does not need to occur for app processes since sepolicy
1786 // prevents access to sandbox data anyway.
1787 appid_t appId = multiuser_get_app_id(uid);
1788 if (appId >= AID_SDK_SANDBOX_PROCESS_START && appId <= AID_SDK_SANDBOX_PROCESS_END) {
1789 isolateSdkSandboxData(env, pkg_data_info_list, uid, process_name, managed_nice_name,
1790 fail_fn);
1791 }
1792 isolateAppData(env, pkg_data_info_list, allowlisted_data_info_list, uid, process_name,
1793 managed_nice_name, fail_fn);
1794 isolateJitProfile(env, pkg_data_info_list, uid, process_name, managed_nice_name, fail_fn);
1795 }
1796 // MOUNT_EXTERNAL_INSTALLER, MOUNT_EXTERNAL_PASS_THROUGH, MOUNT_EXTERNAL_ANDROID_WRITABLE apps
1797 // will have mount_storage_dirs == false here (set by ProcessList.needsStorageDataIsolation()),
1798 // and hence they won't bind mount storage dirs.
1799 if (mount_storage_dirs) {
1800 BindMountStorageDirs(env, pkg_data_info_list, uid, process_name, managed_nice_name,
1801 fail_fn);
1802 }
1803
1804 // If this zygote isn't root, it won't be able to create a process group,
1805 // since the directory is owned by root.
1806 if (!is_system_server && getuid() == 0) {
1807 const int rc = createProcessGroup(uid, getpid());
1808 if (rc != 0) {
1809 fail_fn(rc == -EROFS ? CREATE_ERROR("createProcessGroup failed, kernel missing "
1810 "CONFIG_CGROUP_CPUACCT?")
1811 : CREATE_ERROR("createProcessGroup(%d, %d) failed: %s", uid,
1812 /* pid= */ 0, strerror(-rc)));
1813 }
1814 }
1815
1816 SetGids(env, gids, is_child_zygote, fail_fn);
1817 SetRLimits(env, rlimits, fail_fn);
1818
1819 if (need_pre_initialize_native_bridge) {
1820 // Due to the logic behind need_pre_initialize_native_bridge we know that
1821 // instruction_set contains a value.
1822 android::PreInitializeNativeBridge(app_data_dir.has_value() ? app_data_dir.value().c_str()
1823 : nullptr,
1824 instruction_set.value().c_str());
1825 }
1826
1827 if (is_system_server && !(runtime_flags & RuntimeFlags::PROFILE_SYSTEM_SERVER)) {
1828 // Prefetch the classloader for the system server. This is done early to
1829 // allow a tie-down of the proper system server selinux domain.
1830 // We don't prefetch when the system server is being profiled to avoid
1831 // loading AOT code.
1832 env->CallStaticObjectMethod(gZygoteInitClass, gGetOrCreateSystemServerClassLoader);
1833 if (env->ExceptionCheck()) {
1834 // Be robust here. The Java code will attempt to create the classloader
1835 // at a later point (but may not have rights to use AoT artifacts).
1836 env->ExceptionClear();
1837 }
1838 // Also prefetch standalone system server jars. The reason for doing this here is the same
1839 // as above.
1840 env->CallStaticVoidMethod(gZygoteInitClass, gPrefetchStandaloneSystemServerJars);
1841 if (env->ExceptionCheck()) {
1842 env->ExceptionClear();
1843 }
1844 }
1845
1846 if (setresgid(gid, gid, gid) == -1) {
1847 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
1848 }
1849
1850 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
1851 // before changing uid from 0, which clears capabilities. The other
1852 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
1853 // breaks SELinux domain transition (see b/71859146). As the result,
1854 // privileged syscalls used below still need to be accessible in app process.
1855 SetUpSeccompFilter(uid, is_child_zygote);
1856
1857 // Must be called before losing the permission to set scheduler policy.
1858 SetSchedulerPolicy(fail_fn, is_top_app);
1859
1860 if (setresuid(uid, uid, uid) == -1) {
1861 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1862 }
1863
1864 // The "dumpable" flag of a process, which controls core dump generation, is
1865 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1866 // user or group ID changes. See proc(5) for possible values. In most cases,
1867 // the value is 0, so core dumps are disabled for zygote children. However,
1868 // when running in a Chrome OS container, the value is already set to 2,
1869 // which allows the external crash reporter to collect all core dumps. Since
1870 // only system crashes are interested, core dump is disabled for app
1871 // processes. This also ensures compliance with CTS.
1872 int dumpable = prctl(PR_GET_DUMPABLE);
1873 if (dumpable == -1) {
1874 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1875 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1876 }
1877
1878 if (dumpable == 2 && uid >= AID_APP) {
1879 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1880 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1881 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1882 }
1883 }
1884
1885 // Set process properties to enable debugging if required.
1886 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_PTRACE) != 0) {
1887 EnableDebugger();
1888 // Don't pass unknown flag to the ART runtime.
1889 runtime_flags &= ~RuntimeFlags::DEBUG_ENABLE_PTRACE;
1890 }
1891 if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
1892 // simpleperf needs the process to be dumpable to profile it.
1893 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
1894 ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
1895 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
1896 }
1897 }
1898
1899 HeapTaggingLevel heap_tagging_level;
1900 switch (runtime_flags & RuntimeFlags::MEMORY_TAG_LEVEL_MASK) {
1901 case RuntimeFlags::MEMORY_TAG_LEVEL_TBI:
1902 heap_tagging_level = M_HEAP_TAGGING_LEVEL_TBI;
1903 break;
1904 case RuntimeFlags::MEMORY_TAG_LEVEL_ASYNC:
1905 heap_tagging_level = M_HEAP_TAGGING_LEVEL_ASYNC;
1906 break;
1907 case RuntimeFlags::MEMORY_TAG_LEVEL_SYNC:
1908 heap_tagging_level = M_HEAP_TAGGING_LEVEL_SYNC;
1909 break;
1910 default:
1911 heap_tagging_level = M_HEAP_TAGGING_LEVEL_NONE;
1912 break;
1913 }
1914 mallopt(M_BIONIC_SET_HEAP_TAGGING_LEVEL, heap_tagging_level);
1915
1916 // Now that we've used the flag, clear it so that we don't pass unknown flags to the ART
1917 // runtime.
1918 runtime_flags &= ~RuntimeFlags::MEMORY_TAG_LEVEL_MASK;
1919
1920 // Avoid heap zero initialization for applications without MTE. Zero init may
1921 // cause app compat problems, use more memory, or reduce performance. While it
1922 // would be nice to have them for apps, we will have to wait until they are
1923 // proven out, have more efficient hardware, and/or apply them only to new
1924 // applications.
1925 if (!(runtime_flags & RuntimeFlags::NATIVE_HEAP_ZERO_INIT_ENABLED)) {
1926 mallopt(M_BIONIC_ZERO_INIT, 0);
1927 }
1928
1929 // Now that we've used the flag, clear it so that we don't pass unknown flags to the ART
1930 // runtime.
1931 runtime_flags &= ~RuntimeFlags::NATIVE_HEAP_ZERO_INIT_ENABLED;
1932
1933 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1934 android_mallopt_gwp_asan_options_t gwp_asan_options;
1935 const char* kGwpAsanAppRecoverableSysprop =
1936 "persist.device_config.memory_safety_native.gwp_asan_recoverable_apps";
1937 // The system server doesn't have its nice name set by the time SpecializeCommon is called.
1938 gwp_asan_options.program_name = nice_name_ptr ?: process_name;
1939 switch (runtime_flags & RuntimeFlags::GWP_ASAN_LEVEL_MASK) {
1940 default:
1941 case RuntimeFlags::GWP_ASAN_LEVEL_DEFAULT:
1942 gwp_asan_options.desire = GetBoolProperty(kGwpAsanAppRecoverableSysprop, true)
1943 ? Action::TURN_ON_FOR_APP_SAMPLED_NON_CRASHING
1944 : Action::DONT_TURN_ON_UNLESS_OVERRIDDEN;
1945 android_mallopt(M_INITIALIZE_GWP_ASAN, &gwp_asan_options, sizeof(gwp_asan_options));
1946 break;
1947 case RuntimeFlags::GWP_ASAN_LEVEL_NEVER:
1948 gwp_asan_options.desire = Action::DONT_TURN_ON_UNLESS_OVERRIDDEN;
1949 android_mallopt(M_INITIALIZE_GWP_ASAN, &gwp_asan_options, sizeof(gwp_asan_options));
1950 break;
1951 case RuntimeFlags::GWP_ASAN_LEVEL_ALWAYS:
1952 gwp_asan_options.desire = Action::TURN_ON_FOR_APP;
1953 android_mallopt(M_INITIALIZE_GWP_ASAN, &gwp_asan_options, sizeof(gwp_asan_options));
1954 break;
1955 case RuntimeFlags::GWP_ASAN_LEVEL_LOTTERY:
1956 gwp_asan_options.desire = Action::TURN_ON_WITH_SAMPLING;
1957 android_mallopt(M_INITIALIZE_GWP_ASAN, &gwp_asan_options, sizeof(gwp_asan_options));
1958 break;
1959 }
1960 // Now that we've used the flag, clear it so that we don't pass unknown flags to the ART
1961 // runtime.
1962 runtime_flags &= ~RuntimeFlags::GWP_ASAN_LEVEL_MASK;
1963
1964 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities,
1965 fail_fn);
1966
1967 __android_log_close();
1968 AStatsSocket_close();
1969
1970 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1971
1972 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1973 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
1974 is_system_server, se_info_ptr, nice_name_ptr));
1975 }
1976
1977 // Make it easier to debug audit logs by setting the main thread's name to the
1978 // nice name rather than "app_process".
1979 if (nice_name.has_value()) {
1980 SetThreadName(nice_name.value());
1981 } else if (is_system_server) {
1982 SetThreadName("system_server");
1983 }
1984
1985 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1986 UnsetChldSignalHandler();
1987
1988 if (is_system_server) {
1989 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks, runtime_flags);
1990 if (env->ExceptionCheck()) {
1991 fail_fn("Error calling post fork system server hooks.");
1992 }
1993
1994 // TODO(b/117874058): Remove hardcoded label here.
1995 static const char* kSystemServerLabel = "u:r:system_server:s0";
1996 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1997 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1998 }
1999 }
2000
2001 if (is_child_zygote) {
2002 initUnsolSocketToSystemServer();
2003 }
2004
2005 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
2006 is_system_server, is_child_zygote, managed_instruction_set);
2007
2008 // Reset the process priority to the default value.
2009 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_DEFAULT);
2010
2011 if (env->ExceptionCheck()) {
2012 fail_fn("Error calling post fork hooks.");
2013 }
2014 }
2015
GetEffectiveCapabilityMask(JNIEnv * env)2016 static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
2017 __user_cap_header_struct capheader;
2018 memset(&capheader, 0, sizeof(capheader));
2019 capheader.version = _LINUX_CAPABILITY_VERSION_3;
2020 capheader.pid = 0;
2021
2022 __user_cap_data_struct capdata[2];
2023 if (capget(&capheader, &capdata[0]) == -1) {
2024 ALOGE("capget failed: %s", strerror(errno));
2025 RuntimeAbort(env, __LINE__, "capget failed");
2026 }
2027
2028 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
2029 }
2030
CalculateCapabilities(JNIEnv * env,jint uid,jint gid,jintArray gids,bool is_child_zygote)2031 static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
2032 bool is_child_zygote) {
2033 jlong capabilities = 0;
2034
2035 /*
2036 * Grant the following capabilities to the Bluetooth user:
2037 * - CAP_WAKE_ALARM
2038 * - CAP_NET_ADMIN
2039 * - CAP_NET_RAW
2040 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
2041 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
2042 */
2043
2044 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
2045 capabilities |= (1LL << CAP_WAKE_ALARM);
2046 capabilities |= (1LL << CAP_NET_ADMIN);
2047 capabilities |= (1LL << CAP_NET_RAW);
2048 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
2049 capabilities |= (1LL << CAP_SYS_NICE);
2050 }
2051
2052 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
2053 capabilities |= (1LL << CAP_NET_ADMIN);
2054 capabilities |= (1LL << CAP_NET_BROADCAST);
2055 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
2056 capabilities |= (1LL << CAP_NET_RAW);
2057 }
2058
2059 /*
2060 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
2061 */
2062
2063 bool gid_wakelock_found = false;
2064 if (gid == AID_WAKELOCK) {
2065 gid_wakelock_found = true;
2066 } else if (gids != nullptr) {
2067 jsize gids_num = env->GetArrayLength(gids);
2068 ScopedIntArrayRO native_gid_proxy(env, gids);
2069
2070 if (native_gid_proxy.get() == nullptr) {
2071 RuntimeAbort(env, __LINE__, "Bad gids array");
2072 }
2073
2074 for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
2075 if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
2076 gid_wakelock_found = true;
2077 break;
2078 }
2079 }
2080 }
2081
2082 if (gid_wakelock_found) {
2083 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
2084 }
2085
2086 /*
2087 * Grant child Zygote processes the following capabilities:
2088 * - CAP_SETUID (change UID of child processes)
2089 * - CAP_SETGID (change GID of child processes)
2090 * - CAP_SETPCAP (change capabilities of child processes)
2091 */
2092
2093 if (is_child_zygote) {
2094 capabilities |= (1LL << CAP_SETUID);
2095 capabilities |= (1LL << CAP_SETGID);
2096 capabilities |= (1LL << CAP_SETPCAP);
2097 }
2098
2099 /*
2100 * Containers run without some capabilities, so drop any caps that are not
2101 * available.
2102 */
2103
2104 return capabilities & GetEffectiveCapabilityMask(env);
2105 }
2106
2107 /**
2108 * Adds the given information about a newly created unspecialized app
2109 * processes to the Zygote's USAP table.
2110 *
2111 * @param usap_pid Process ID of the newly created USAP
2112 * @param read_pipe_fd File descriptor for the read end of the USAP
2113 * reporting pipe. Used in the ZygoteServer poll loop to track USAP
2114 * specialization.
2115 */
AddUsapTableEntry(pid_t usap_pid,int read_pipe_fd)2116 static void AddUsapTableEntry(pid_t usap_pid, int read_pipe_fd) {
2117 static int sUsapTableInsertIndex = 0;
2118
2119 int search_index = sUsapTableInsertIndex;
2120 do {
2121 if (gUsapTable[search_index].SetIfInvalid(usap_pid, read_pipe_fd)) {
2122 ++gUsapPoolCount;
2123
2124 // Start our next search right after where we finished this one.
2125 sUsapTableInsertIndex = (search_index + 1) % gUsapTable.size();
2126
2127 return;
2128 }
2129
2130 search_index = (search_index + 1) % gUsapTable.size();
2131 } while (search_index != sUsapTableInsertIndex);
2132
2133 // Much like money in the banana stand, there should always be an entry
2134 // in the USAP table.
2135 __builtin_unreachable();
2136 }
2137
2138 /**
2139 * Invalidates the entry in the USAPTable corresponding to the provided
2140 * process ID if it is present. If an entry was removed the USAP pool
2141 * count is decremented. May be called from signal handler.
2142 *
2143 * @param usap_pid Process ID of the USAP entry to invalidate
2144 * @return True if an entry was invalidated; false otherwise
2145 */
RemoveUsapTableEntry(pid_t usap_pid)2146 static bool RemoveUsapTableEntry(pid_t usap_pid) {
2147 for (UsapTableEntry& entry : gUsapTable) {
2148 if (entry.ClearForPID(usap_pid)) {
2149 --gUsapPoolCount;
2150 return true;
2151 }
2152 }
2153
2154 return false;
2155 }
2156
2157 /**
2158 * @return A vector of the read pipe FDs for each of the active USAPs.
2159 */
MakeUsapPipeReadFDVector()2160 std::vector<int> MakeUsapPipeReadFDVector() {
2161 std::vector<int> fd_vec;
2162 fd_vec.reserve(gUsapTable.size());
2163
2164 for (UsapTableEntry& entry : gUsapTable) {
2165 auto entry_values = entry.GetValues();
2166
2167 if (entry_values.has_value()) {
2168 fd_vec.push_back(entry_values.value().read_pipe_fd);
2169 }
2170 }
2171
2172 return fd_vec;
2173 }
2174
UnmountStorageOnInit(JNIEnv * env)2175 static void UnmountStorageOnInit(JNIEnv* env) {
2176 // Zygote process unmount root storage space initially before every child processes are forked.
2177 // Every forked child processes (include SystemServer) only mount their own root storage space
2178 // and no need unmount storage operation in MountEmulatedStorage method.
2179 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
2180
2181 // See storage config details at http://source.android.com/tech/storage/
2182 // Create private mount namespace shared by all children
2183 if (unshare(CLONE_NEWNS) == -1) {
2184 RuntimeAbort(env, __LINE__, "Failed to unshare()");
2185 return;
2186 }
2187
2188 // Mark rootfs as being MS_SLAVE so that changes from default
2189 // namespace only flow into our children.
2190 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
2191 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
2192 return;
2193 }
2194
2195 // Create a staging tmpfs that is shared by our children; they will
2196 // bind mount storage into their respective private namespaces, which
2197 // are isolated from each other.
2198 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
2199 if (target_base != nullptr) {
2200 #define STRINGIFY_UID(x) __STRING(x)
2201 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
2202 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
2203 ALOGE("Failed to mount tmpfs to %s", target_base);
2204 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
2205 return;
2206 }
2207 #undef STRINGIFY_UID
2208 }
2209
2210 UnmountTree("/storage");
2211 }
2212
2213 } // anonymous namespace
2214
2215 namespace android {
2216
2217 /**
2218 * A failure function used to report fatal errors to the managed runtime. This
2219 * function is often curried with the process name information and then passed
2220 * to called functions.
2221 *
2222 * @param env Managed runtime environment
2223 * @param process_name A native representation of the process name
2224 * @param managed_process_name A managed representation of the process name
2225 * @param msg The error message to be reported
2226 */
2227 [[noreturn]]
ZygoteFailure(JNIEnv * env,const char * process_name,jstring managed_process_name,const std::string & msg)2228 void zygote::ZygoteFailure(JNIEnv* env,
2229 const char* process_name,
2230 jstring managed_process_name,
2231 const std::string& msg) {
2232 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
2233 if (managed_process_name != nullptr) {
2234 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
2235 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
2236 process_name = scoped_managed_process_name_ptr->c_str();
2237 }
2238 }
2239
2240 const std::string& error_msg =
2241 (process_name == nullptr || process_name[0] == '\0') ?
2242 msg : StringPrintf("(%s) %s", process_name, msg.c_str());
2243
2244 env->FatalError(error_msg.c_str());
2245 __builtin_unreachable();
2246 }
2247
2248 static std::set<int>* gPreloadFds = nullptr;
2249 static bool gPreloadFdsExtracted = false;
2250
2251 // Utility routine to fork a process from the zygote.
2252 NO_STACK_PROTECTOR
ForkCommon(JNIEnv * env,bool is_system_server,const std::vector<int> & fds_to_close,const std::vector<int> & fds_to_ignore,bool is_priority_fork,bool purge)2253 pid_t zygote::ForkCommon(JNIEnv* env, bool is_system_server,
2254 const std::vector<int>& fds_to_close,
2255 const std::vector<int>& fds_to_ignore,
2256 bool is_priority_fork,
2257 bool purge) {
2258 SetSignalHandlers();
2259
2260 // Curry a failure function.
2261 auto fail_fn = std::bind(zygote::ZygoteFailure, env,
2262 is_system_server ? "system_server" : "zygote",
2263 nullptr, _1);
2264
2265 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
2266 // log, which would result in the logging FDs we close being reopened.
2267 // This would cause failures because the FDs are not allowlisted.
2268 //
2269 // Note that the zygote process is single threaded at this point.
2270 BlockSignal(SIGCHLD, fail_fn);
2271
2272 // Close any logging related FDs before we start evaluating the list of
2273 // file descriptors.
2274 __android_log_close();
2275 AStatsSocket_close();
2276
2277 // If this is the first fork for this zygote, create the open FD table,
2278 // verifying that files are of supported type and allowlisted. Otherwise (not
2279 // the first fork), check that the open files have not changed. Newly open
2280 // files are not expected, and will be disallowed in the future. Currently
2281 // they are allowed if they pass the same checks as in the
2282 // FileDescriptorTable::Create() above.
2283 if (gOpenFdTable == nullptr) {
2284 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
2285 } else {
2286 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
2287 }
2288
2289 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
2290
2291 if (purge) {
2292 // Purge unused native memory in an attempt to reduce the amount of false
2293 // sharing with the child process. By reducing the size of the libc_malloc
2294 // region shared with the child process we reduce the number of pages that
2295 // transition to the private-dirty state when malloc adjusts the meta-data
2296 // on each of the pages it is managing after the fork.
2297 if (mallopt(M_PURGE_ALL, 0) != 1) {
2298 mallopt(M_PURGE, 0);
2299 }
2300 }
2301
2302 pid_t pid = fork();
2303
2304 if (pid == 0) {
2305 if (is_priority_fork) {
2306 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
2307 } else {
2308 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MIN);
2309 }
2310
2311 #if defined(__BIONIC__) && !defined(NO_RESET_STACK_PROTECTOR)
2312 // Reset the stack guard for the new process.
2313 android_reset_stack_guards();
2314 #endif
2315
2316 // The child process.
2317 PreApplicationInit();
2318
2319 // Clean up any descriptors which must be closed immediately
2320 DetachDescriptors(env, fds_to_close, fail_fn);
2321
2322 // Invalidate the entries in the USAP table.
2323 ClearUsapTable();
2324
2325 // Re-open all remaining open file descriptors so that they aren't shared
2326 // with the zygote across a fork.
2327 gOpenFdTable->ReopenOrDetach(fail_fn);
2328
2329 // Turn fdsan back on.
2330 android_fdsan_set_error_level(fdsan_error_level);
2331
2332 // Reset the fd to the unsolicited zygote socket
2333 gSystemServerSocketFd = -1;
2334 } else if (pid == -1) {
2335 ALOGE("Failed to fork child process: %s (%d)", strerror(errno), errno);
2336 } else {
2337 ALOGD("Forked child process %d", pid);
2338 }
2339
2340 // We blocked SIGCHLD prior to a fork, we unblock it here.
2341 UnblockSignal(SIGCHLD, fail_fn);
2342
2343 return pid;
2344 }
2345
com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv *,jclass)2346 static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
2347 PreApplicationInit();
2348 }
2349
2350 NO_STACK_PROTECTOR
com_android_internal_os_Zygote_nativeForkAndSpecialize(JNIEnv * env,jclass,jint uid,jint gid,jintArray gids,jint runtime_flags,jobjectArray rlimits,jint mount_external,jstring se_info,jstring nice_name,jintArray managed_fds_to_close,jintArray managed_fds_to_ignore,jboolean is_child_zygote,jstring instruction_set,jstring app_data_dir,jboolean is_top_app,jobjectArray pkg_data_info_list,jobjectArray allowlisted_data_info_list,jboolean mount_data_dirs,jboolean mount_storage_dirs)2351 static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
2352 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids, jint runtime_flags,
2353 jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name,
2354 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
2355 jstring instruction_set, jstring app_data_dir, jboolean is_top_app,
2356 jobjectArray pkg_data_info_list, jobjectArray allowlisted_data_info_list,
2357 jboolean mount_data_dirs, jboolean mount_storage_dirs) {
2358 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
2359
2360 if (UNLIKELY(managed_fds_to_close == nullptr)) {
2361 zygote::ZygoteFailure(env, "zygote", nice_name,
2362 "Zygote received a null fds_to_close vector.");
2363 }
2364
2365 std::vector<int> fds_to_close =
2366 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
2367 std::vector<int> fds_to_ignore =
2368 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
2369 .value_or(std::vector<int>());
2370
2371 std::vector<int> usap_pipes = MakeUsapPipeReadFDVector();
2372
2373 fds_to_close.insert(fds_to_close.end(), usap_pipes.begin(), usap_pipes.end());
2374 fds_to_ignore.insert(fds_to_ignore.end(), usap_pipes.begin(), usap_pipes.end());
2375
2376 fds_to_close.push_back(gUsapPoolSocketFD);
2377
2378 if (gUsapPoolEventFD != -1) {
2379 fds_to_close.push_back(gUsapPoolEventFD);
2380 fds_to_ignore.push_back(gUsapPoolEventFD);
2381 }
2382
2383 if (gSystemServerSocketFd != -1) {
2384 fds_to_close.push_back(gSystemServerSocketFd);
2385 fds_to_ignore.push_back(gSystemServerSocketFd);
2386 }
2387
2388 if (gPreloadFds && gPreloadFdsExtracted) {
2389 fds_to_ignore.insert(fds_to_ignore.end(), gPreloadFds->begin(), gPreloadFds->end());
2390 }
2391
2392 pid_t pid = zygote::ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore,
2393 true);
2394
2395 if (pid == 0) {
2396 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, capabilities, capabilities,
2397 mount_external, se_info, nice_name, false, is_child_zygote == JNI_TRUE,
2398 instruction_set, app_data_dir, is_top_app == JNI_TRUE, pkg_data_info_list,
2399 allowlisted_data_info_list, mount_data_dirs == JNI_TRUE,
2400 mount_storage_dirs == JNI_TRUE);
2401 }
2402 return pid;
2403 }
2404
2405 NO_STACK_PROTECTOR
com_android_internal_os_Zygote_nativeForkSystemServer(JNIEnv * env,jclass,uid_t uid,gid_t gid,jintArray gids,jint runtime_flags,jobjectArray rlimits,jlong permitted_capabilities,jlong effective_capabilities)2406 static jint com_android_internal_os_Zygote_nativeForkSystemServer(
2407 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
2408 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
2409 jlong effective_capabilities) {
2410 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
2411 fds_to_ignore(fds_to_close);
2412
2413 fds_to_close.push_back(gUsapPoolSocketFD);
2414
2415 if (gUsapPoolEventFD != -1) {
2416 fds_to_close.push_back(gUsapPoolEventFD);
2417 fds_to_ignore.push_back(gUsapPoolEventFD);
2418 }
2419
2420 if (gSystemServerSocketFd != -1) {
2421 fds_to_close.push_back(gSystemServerSocketFd);
2422 fds_to_ignore.push_back(gSystemServerSocketFd);
2423 }
2424
2425 pid_t pid = zygote::ForkCommon(env, true,
2426 fds_to_close,
2427 fds_to_ignore,
2428 true);
2429 if (pid == 0) {
2430 // System server prcoess does not need data isolation so no need to
2431 // know pkg_data_info_list.
2432 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, permitted_capabilities,
2433 effective_capabilities, MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
2434 false, nullptr, nullptr, /* is_top_app= */ false,
2435 /* pkg_data_info_list */ nullptr,
2436 /* allowlisted_data_info_list */ nullptr, false, false);
2437 } else if (pid > 0) {
2438 // The zygote process checks whether the child process has died or not.
2439 ALOGI("System server process %d has been created", pid);
2440 gSystemServerPid = pid;
2441 // There is a slight window that the system server process has crashed
2442 // but it went unnoticed because we haven't published its pid yet. So
2443 // we recheck here just to make sure that all is well.
2444 int status;
2445 if (waitpid(pid, &status, WNOHANG) == pid) {
2446 ALOGE("System server process %d has died. Restarting Zygote!", pid);
2447 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
2448 }
2449
2450 if (UsePerAppMemcg()) {
2451 // Assign system_server to the correct memory cgroup.
2452 // Not all devices mount memcg so check if it is mounted first
2453 // to avoid unnecessarily printing errors and denials in the logs.
2454 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
2455 ALOGE("couldn't add process %d into system memcg group", pid);
2456 }
2457 }
2458 }
2459 return pid;
2460 }
2461
2462 /**
2463 * A JNI function that forks an unspecialized app process from the Zygote while
2464 * ensuring proper file descriptor hygiene.
2465 *
2466 * @param env Managed runtime environment
2467 * @param read_pipe_fd The read FD for the USAP reporting pipe. Manually closed by the child
2468 * in managed code. -1 indicates none.
2469 * @param write_pipe_fd The write FD for the USAP reporting pipe. Manually closed by the
2470 * zygote in managed code. -1 indicates none.
2471 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
2472 * the FD hygiene code and automatically "closed" in the new USAP.
2473 * @param args_known Arguments for specialization are available; no need to read from a socket
2474 * @param is_priority_fork Controls the nice level assigned to the newly created process
2475 * @return child pid in the parent, 0 in the child
2476 */
2477 NO_STACK_PROTECTOR
com_android_internal_os_Zygote_nativeForkApp(JNIEnv * env,jclass,jint read_pipe_fd,jint write_pipe_fd,jintArray managed_session_socket_fds,jboolean args_known,jboolean is_priority_fork)2478 static jint com_android_internal_os_Zygote_nativeForkApp(JNIEnv* env,
2479 jclass,
2480 jint read_pipe_fd,
2481 jint write_pipe_fd,
2482 jintArray managed_session_socket_fds,
2483 jboolean args_known,
2484 jboolean is_priority_fork) {
2485 std::vector<int> session_socket_fds =
2486 ExtractJIntArray(env, "USAP", nullptr, managed_session_socket_fds)
2487 .value_or(std::vector<int>());
2488 return zygote::forkApp(env, read_pipe_fd, write_pipe_fd, session_socket_fds,
2489 args_known == JNI_TRUE, is_priority_fork == JNI_TRUE, true);
2490 }
2491
2492 NO_STACK_PROTECTOR
forkApp(JNIEnv * env,int read_pipe_fd,int write_pipe_fd,const std::vector<int> & session_socket_fds,bool args_known,bool is_priority_fork,bool purge)2493 int zygote::forkApp(JNIEnv* env,
2494 int read_pipe_fd,
2495 int write_pipe_fd,
2496 const std::vector<int>& session_socket_fds,
2497 bool args_known,
2498 bool is_priority_fork,
2499 bool purge) {
2500
2501 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
2502 fds_to_ignore(fds_to_close);
2503
2504 fds_to_close.push_back(gZygoteSocketFD);
2505 if (gSystemServerSocketFd != -1) {
2506 fds_to_close.push_back(gSystemServerSocketFd);
2507 }
2508 if (args_known) {
2509 fds_to_close.push_back(gUsapPoolSocketFD);
2510 }
2511 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
2512
2513 fds_to_ignore.push_back(gUsapPoolSocketFD);
2514 fds_to_ignore.push_back(gZygoteSocketFD);
2515 if (read_pipe_fd != -1) {
2516 fds_to_ignore.push_back(read_pipe_fd);
2517 }
2518 if (write_pipe_fd != -1) {
2519 fds_to_ignore.push_back(write_pipe_fd);
2520 }
2521 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
2522
2523 if (gUsapPoolEventFD != -1) {
2524 fds_to_close.push_back(gUsapPoolEventFD);
2525 fds_to_ignore.push_back(gUsapPoolEventFD);
2526 }
2527 if (gSystemServerSocketFd != -1) {
2528 if (args_known) {
2529 fds_to_close.push_back(gSystemServerSocketFd);
2530 }
2531 fds_to_ignore.push_back(gSystemServerSocketFd);
2532 }
2533 if (gPreloadFds && gPreloadFdsExtracted) {
2534 fds_to_ignore.insert(fds_to_ignore.end(), gPreloadFds->begin(), gPreloadFds->end());
2535 }
2536
2537 return zygote::ForkCommon(env, /* is_system_server= */ false, fds_to_close,
2538 fds_to_ignore, is_priority_fork == JNI_TRUE, purge);
2539 }
2540
com_android_internal_os_Zygote_nativeAllowFileAcrossFork(JNIEnv * env,jclass,jstring path)2541 static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
2542 JNIEnv* env, jclass, jstring path) {
2543 ScopedUtfChars path_native(env, path);
2544 const char* path_cstr = path_native.c_str();
2545 if (!path_cstr) {
2546 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
2547 }
2548 FileDescriptorAllowlist::Get()->Allow(path_cstr);
2549 }
2550
com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(JNIEnv * env,jclass,jint uidGidMin,jint uidGidMax)2551 static void com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(
2552 JNIEnv* env, jclass, jint uidGidMin, jint uidGidMax) {
2553 if (!gIsSecurityEnforced) {
2554 ALOGI("seccomp disabled by setenforce 0");
2555 return;
2556 }
2557
2558 bool installed = install_setuidgid_seccomp_filter(uidGidMin, uidGidMax);
2559 if (!installed) {
2560 RuntimeAbort(env, __LINE__, "Could not install setuid/setgid seccomp filter.");
2561 }
2562 }
2563
2564 /**
2565 * Called from an unspecialized app process to specialize the process for a
2566 * given application.
2567 *
2568 * @param env Managed runtime environment
2569 * @param uid User ID of the new application
2570 * @param gid Group ID of the new application
2571 * @param gids Extra groups that the process belongs to
2572 * @param runtime_flags Flags for changing the behavior of the managed runtime
2573 * @param rlimits Resource limits
2574 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
2575 * @param se_info SELinux policy information
2576 * @param nice_name New name for this process
2577 * @param is_child_zygote If the process is to become a WebViewZygote
2578 * @param instruction_set The instruction set expected/requested by the new application
2579 * @param app_data_dir Path to the application's data directory
2580 * @param is_top_app If the process is for top (high priority) application
2581 */
com_android_internal_os_Zygote_nativeSpecializeAppProcess(JNIEnv * env,jclass,jint uid,jint gid,jintArray gids,jint runtime_flags,jobjectArray rlimits,jint mount_external,jstring se_info,jstring nice_name,jboolean is_child_zygote,jstring instruction_set,jstring app_data_dir,jboolean is_top_app,jobjectArray pkg_data_info_list,jobjectArray allowlisted_data_info_list,jboolean mount_data_dirs,jboolean mount_storage_dirs)2582 static void com_android_internal_os_Zygote_nativeSpecializeAppProcess(
2583 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids, jint runtime_flags,
2584 jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name,
2585 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir,
2586 jboolean is_top_app, jobjectArray pkg_data_info_list,
2587 jobjectArray allowlisted_data_info_list, jboolean mount_data_dirs,
2588 jboolean mount_storage_dirs) {
2589 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
2590
2591 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, capabilities, capabilities,
2592 mount_external, se_info, nice_name, false, is_child_zygote == JNI_TRUE,
2593 instruction_set, app_data_dir, is_top_app == JNI_TRUE, pkg_data_info_list,
2594 allowlisted_data_info_list, mount_data_dirs == JNI_TRUE,
2595 mount_storage_dirs == JNI_TRUE);
2596 }
2597
2598 /**
2599 * A helper method for fetching socket file descriptors that were opened by init from the
2600 * environment.
2601 *
2602 * @param env Managed runtime environment
2603 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
2604 * of the environment variable storing the file descriptors.
2605 */
com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv * env,jclass,jboolean is_primary)2606 static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv* env, jclass,
2607 jboolean is_primary) {
2608 /*
2609 * Obtain file descriptors created by init from the environment.
2610 */
2611
2612 gZygoteSocketFD =
2613 android_get_control_socket(is_primary ? "zygote" : "zygote_secondary");
2614 if (gZygoteSocketFD >= 0) {
2615 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
2616 } else {
2617 ALOGE("Unable to fetch Zygote socket file descriptor");
2618 }
2619
2620 gUsapPoolSocketFD =
2621 android_get_control_socket(is_primary ? "usap_pool_primary" : "usap_pool_secondary");
2622 if (gUsapPoolSocketFD >= 0) {
2623 ALOGV("Zygote:usapPoolSocketFD = %d", gUsapPoolSocketFD);
2624 } else {
2625 ALOGE("Unable to fetch USAP pool socket file descriptor");
2626 }
2627
2628 initUnsolSocketToSystemServer();
2629
2630 /*
2631 * Security Initialization
2632 */
2633
2634 // security_getenforce is not allowed on app process. Initialize and cache
2635 // the value before zygote forks.
2636 gIsSecurityEnforced = security_getenforce();
2637
2638 selinux_android_seapp_context_init();
2639
2640 /*
2641 * Storage Initialization
2642 */
2643
2644 UnmountStorageOnInit(env);
2645
2646 /*
2647 * Performance Initialization
2648 */
2649
2650 if (!SetTaskProfiles(0, {})) {
2651 zygote::ZygoteFailure(env, "zygote", nullptr, "Zygote SetTaskProfiles failed");
2652 }
2653 }
2654
2655 /**
2656 * @param env Managed runtime environment
2657 * @return A managed array of raw file descriptors for the read ends of the USAP reporting
2658 * pipes.
2659 */
com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv * env,jclass)2660 static jintArray com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv* env, jclass) {
2661 std::vector<int> usap_fds = MakeUsapPipeReadFDVector();
2662
2663 jintArray managed_usap_fds = env->NewIntArray(usap_fds.size());
2664 env->SetIntArrayRegion(managed_usap_fds, 0, usap_fds.size(), usap_fds.data());
2665
2666 return managed_usap_fds;
2667 }
2668
2669 /*
2670 * Add the given pid and file descriptor to the Usap table. CriticalNative method.
2671 */
com_android_internal_os_Zygote_nativeAddUsapTableEntry(jint pid,jint read_pipe_fd)2672 static void com_android_internal_os_Zygote_nativeAddUsapTableEntry(jint pid, jint read_pipe_fd) {
2673 AddUsapTableEntry(pid, read_pipe_fd);
2674 }
2675
2676 /**
2677 * A JNI wrapper around RemoveUsapTableEntry. CriticalNative method.
2678 *
2679 * @param env Managed runtime environment
2680 * @param usap_pid Process ID of the USAP entry to invalidate
2681 * @return True if an entry was invalidated; false otherwise.
2682 */
com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(jint usap_pid)2683 static jboolean com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(jint usap_pid) {
2684 return RemoveUsapTableEntry(usap_pid);
2685 }
2686
2687 /**
2688 * Creates the USAP pool event FD if it doesn't exist and returns it. This is used by the
2689 * ZygoteServer poll loop to know when to re-fill the USAP pool.
2690 *
2691 * @param env Managed runtime environment
2692 * @return A raw event file descriptor used to communicate (from the signal handler) when the
2693 * Zygote receives a SIGCHLD for a USAP
2694 */
com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv * env,jclass)2695 static jint com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv* env, jclass) {
2696 if (gUsapPoolEventFD == -1) {
2697 if ((gUsapPoolEventFD = eventfd(0, 0)) == -1) {
2698 zygote::ZygoteFailure(env, "zygote", nullptr,
2699 StringPrintf("Unable to create eventfd: %s", strerror(errno)));
2700 }
2701 }
2702
2703 return gUsapPoolEventFD;
2704 }
2705
2706 /**
2707 * @param env Managed runtime environment
2708 * @return The number of USAPs currently in the USAP pool
2709 */
com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv * env,jclass)2710 static jint com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv* env, jclass) {
2711 return gUsapPoolCount;
2712 }
2713
2714 /**
2715 * Kills all processes currently in the USAP pool and closes their read pipe
2716 * FDs.
2717 *
2718 * @param env Managed runtime environment
2719 */
com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv * env,jclass)2720 static void com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv* env, jclass) {
2721 for (auto& entry : gUsapTable) {
2722 auto entry_storage = entry.GetValues();
2723
2724 if (entry_storage.has_value()) {
2725 kill(entry_storage.value().pid, SIGTERM);
2726
2727 // Clean up the USAP table entry here. This avoids a potential race
2728 // where a newly created USAP might not be able to find a valid table
2729 // entry if signal handler (which would normally do the cleanup) doesn't
2730 // run between now and when the new process is created.
2731
2732 close(entry_storage.value().read_pipe_fd);
2733
2734 // Avoid a second atomic load by invalidating instead of clearing.
2735 entry.Invalidate();
2736 --gUsapPoolCount;
2737 }
2738 }
2739 }
2740
com_android_internal_os_Zygote_nativeBlockSigTerm(JNIEnv * env,jclass)2741 static void com_android_internal_os_Zygote_nativeBlockSigTerm(JNIEnv* env, jclass) {
2742 auto fail_fn = std::bind(zygote::ZygoteFailure, env, "usap", nullptr, _1);
2743 BlockSignal(SIGTERM, fail_fn);
2744 }
2745
com_android_internal_os_Zygote_nativeUnblockSigTerm(JNIEnv * env,jclass)2746 static void com_android_internal_os_Zygote_nativeUnblockSigTerm(JNIEnv* env, jclass) {
2747 auto fail_fn = std::bind(zygote::ZygoteFailure, env, "usap", nullptr, _1);
2748 UnblockSignal(SIGTERM, fail_fn);
2749 }
2750
com_android_internal_os_Zygote_nativeBoostUsapPriority(JNIEnv * env,jclass)2751 static void com_android_internal_os_Zygote_nativeBoostUsapPriority(JNIEnv* env, jclass) {
2752 setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
2753 }
2754
com_android_internal_os_Zygote_nativeParseSigChld(JNIEnv * env,jclass,jbyteArray in,jint length,jintArray out)2755 static jint com_android_internal_os_Zygote_nativeParseSigChld(JNIEnv* env, jclass, jbyteArray in,
2756 jint length, jintArray out) {
2757 if (length != sizeof(struct UnsolicitedZygoteMessageSigChld)) {
2758 // Apparently it's not the message we are expecting.
2759 return -1;
2760 }
2761 if (in == nullptr || out == nullptr) {
2762 // Invalid parameter
2763 jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2764 return -1;
2765 }
2766 ScopedByteArrayRO source(env, in);
2767 if (source.size() < length) {
2768 // Invalid parameter
2769 jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2770 return -1;
2771 }
2772 const struct UnsolicitedZygoteMessageSigChld* msg =
2773 reinterpret_cast<const struct UnsolicitedZygoteMessageSigChld*>(source.get());
2774
2775 switch (msg->header.type) {
2776 case UNSOLICITED_ZYGOTE_MESSAGE_TYPE_SIGCHLD: {
2777 ScopedIntArrayRW buf(env, out);
2778 if (buf.size() != 3) {
2779 jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2780 return UNSOLICITED_ZYGOTE_MESSAGE_TYPE_RESERVED;
2781 }
2782 buf[0] = msg->payload.pid;
2783 buf[1] = msg->payload.uid;
2784 buf[2] = msg->payload.status;
2785 return 3;
2786 }
2787 default:
2788 break;
2789 }
2790 return -1;
2791 }
2792
com_android_internal_os_Zygote_nativeSupportsMemoryTagging(JNIEnv * env,jclass)2793 static jboolean com_android_internal_os_Zygote_nativeSupportsMemoryTagging(JNIEnv* env, jclass) {
2794 #if defined(__aarch64__)
2795 return mte_supported();
2796 #else
2797 return false;
2798 #endif
2799 }
2800
com_android_internal_os_Zygote_nativeSupportsTaggedPointers(JNIEnv * env,jclass)2801 static jboolean com_android_internal_os_Zygote_nativeSupportsTaggedPointers(JNIEnv* env, jclass) {
2802 #ifdef __aarch64__
2803 int res = prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0);
2804 return res >= 0 && res & PR_TAGGED_ADDR_ENABLE;
2805 #else
2806 return false;
2807 #endif
2808 }
2809
com_android_internal_os_Zygote_nativeCurrentTaggingLevel(JNIEnv * env,jclass)2810 static jint com_android_internal_os_Zygote_nativeCurrentTaggingLevel(JNIEnv* env, jclass) {
2811 #if defined(__aarch64__)
2812 int level = prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0);
2813 if (level < 0) {
2814 ALOGE("Failed to get memory tag level: %s", strerror(errno));
2815 return 0;
2816 } else if (!(level & PR_TAGGED_ADDR_ENABLE)) {
2817 return 0;
2818 }
2819 // TBI is only possible on non-MTE hardware.
2820 if (!mte_supported()) {
2821 return MEMORY_TAG_LEVEL_TBI;
2822 }
2823
2824 switch (level & PR_MTE_TCF_MASK) {
2825 case PR_MTE_TCF_NONE:
2826 return 0;
2827 case PR_MTE_TCF_SYNC:
2828 return MEMORY_TAG_LEVEL_SYNC;
2829 case PR_MTE_TCF_ASYNC:
2830 case PR_MTE_TCF_ASYNC | PR_MTE_TCF_SYNC:
2831 return MEMORY_TAG_LEVEL_ASYNC;
2832 default:
2833 ALOGE("Unknown memory tagging level: %i", level);
2834 return 0;
2835 }
2836 #else // defined(__aarch64__)
2837 return 0;
2838 #endif // defined(__aarch64__)
2839 }
2840
com_android_internal_os_Zygote_nativeMarkOpenedFilesBeforePreload(JNIEnv * env,jclass)2841 static void com_android_internal_os_Zygote_nativeMarkOpenedFilesBeforePreload(JNIEnv* env, jclass) {
2842 // Ignore invocations when too early or too late.
2843 if (gPreloadFds) {
2844 return;
2845 }
2846
2847 // App Zygote Preload starts soon. Save FDs remaining open. After the
2848 // preload finishes newly open files will be determined.
2849 auto fail_fn = std::bind(zygote::ZygoteFailure, env, "zygote", nullptr, _1);
2850 gPreloadFds = GetOpenFds(fail_fn).release();
2851 }
2852
com_android_internal_os_Zygote_nativeAllowFilesOpenedByPreload(JNIEnv * env,jclass)2853 static void com_android_internal_os_Zygote_nativeAllowFilesOpenedByPreload(JNIEnv* env, jclass) {
2854 // Ignore invocations when too early or too late.
2855 if (!gPreloadFds || gPreloadFdsExtracted) {
2856 return;
2857 }
2858
2859 // Find the newly open FDs, if any.
2860 auto fail_fn = std::bind(zygote::ZygoteFailure, env, "zygote", nullptr, _1);
2861 std::unique_ptr<std::set<int>> current_fds = GetOpenFds(fail_fn);
2862 auto difference = std::make_unique<std::set<int>>();
2863 std::set_difference(current_fds->begin(), current_fds->end(), gPreloadFds->begin(),
2864 gPreloadFds->end(), std::inserter(*difference, difference->end()));
2865 delete gPreloadFds;
2866 gPreloadFds = difference.release();
2867 gPreloadFdsExtracted = true;
2868 }
2869
2870 static const JNINativeMethod gMethods[] = {
2871 {"nativeForkAndSpecialize",
2872 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/"
2873 "String;Z[Ljava/lang/String;[Ljava/lang/String;ZZ)I",
2874 (void*)com_android_internal_os_Zygote_nativeForkAndSpecialize},
2875 {"nativeForkSystemServer", "(II[II[[IJJ)I",
2876 (void*)com_android_internal_os_Zygote_nativeForkSystemServer},
2877 {"nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
2878 (void*)com_android_internal_os_Zygote_nativeAllowFileAcrossFork},
2879 {"nativePreApplicationInit", "()V",
2880 (void*)com_android_internal_os_Zygote_nativePreApplicationInit},
2881 {"nativeInstallSeccompUidGidFilter", "(II)V",
2882 (void*)com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter},
2883 {"nativeForkApp", "(II[IZZ)I", (void*)com_android_internal_os_Zygote_nativeForkApp},
2884 // @CriticalNative
2885 {"nativeAddUsapTableEntry", "(II)V",
2886 (void*)com_android_internal_os_Zygote_nativeAddUsapTableEntry},
2887 {"nativeSpecializeAppProcess",
2888 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/"
2889 "String;Z[Ljava/lang/String;[Ljava/lang/String;ZZ)V",
2890 (void*)com_android_internal_os_Zygote_nativeSpecializeAppProcess},
2891 {"nativeInitNativeState", "(Z)V",
2892 (void*)com_android_internal_os_Zygote_nativeInitNativeState},
2893 {"nativeGetUsapPipeFDs", "()[I",
2894 (void*)com_android_internal_os_Zygote_nativeGetUsapPipeFDs},
2895 // @CriticalNative
2896 {"nativeAddUsapTableEntry", "(II)V",
2897 (void*)com_android_internal_os_Zygote_nativeAddUsapTableEntry},
2898 // @CriticalNative
2899 {"nativeRemoveUsapTableEntry", "(I)Z",
2900 (void*)com_android_internal_os_Zygote_nativeRemoveUsapTableEntry},
2901 {"nativeGetUsapPoolEventFD", "()I",
2902 (void*)com_android_internal_os_Zygote_nativeGetUsapPoolEventFD},
2903 {"nativeGetUsapPoolCount", "()I",
2904 (void*)com_android_internal_os_Zygote_nativeGetUsapPoolCount},
2905 {"nativeEmptyUsapPool", "()V", (void*)com_android_internal_os_Zygote_nativeEmptyUsapPool},
2906 {"nativeBlockSigTerm", "()V", (void*)com_android_internal_os_Zygote_nativeBlockSigTerm},
2907 {"nativeUnblockSigTerm", "()V", (void*)com_android_internal_os_Zygote_nativeUnblockSigTerm},
2908 {"nativeBoostUsapPriority", "()V",
2909 (void*)com_android_internal_os_Zygote_nativeBoostUsapPriority},
2910 {"nativeParseSigChld", "([BI[I)I",
2911 (void*)com_android_internal_os_Zygote_nativeParseSigChld},
2912 {"nativeSupportsMemoryTagging", "()Z",
2913 (void*)com_android_internal_os_Zygote_nativeSupportsMemoryTagging},
2914 {"nativeSupportsTaggedPointers", "()Z",
2915 (void*)com_android_internal_os_Zygote_nativeSupportsTaggedPointers},
2916 {"nativeCurrentTaggingLevel", "()I",
2917 (void*)com_android_internal_os_Zygote_nativeCurrentTaggingLevel},
2918 {"nativeMarkOpenedFilesBeforePreload", "()V",
2919 (void*)com_android_internal_os_Zygote_nativeMarkOpenedFilesBeforePreload},
2920 {"nativeAllowFilesOpenedByPreload", "()V",
2921 (void*)com_android_internal_os_Zygote_nativeAllowFilesOpenedByPreload},
2922 };
2923
register_com_android_internal_os_Zygote(JNIEnv * env)2924 int register_com_android_internal_os_Zygote(JNIEnv* env) {
2925 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
2926 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
2927 "callPostForkSystemServerHooks",
2928 "(I)V");
2929 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
2930 "(IZZLjava/lang/String;)V");
2931
2932 gZygoteInitClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteInitClassName));
2933 gGetOrCreateSystemServerClassLoader =
2934 GetStaticMethodIDOrDie(env, gZygoteInitClass, "getOrCreateSystemServerClassLoader",
2935 "()Ljava/lang/ClassLoader;");
2936 gPrefetchStandaloneSystemServerJars =
2937 GetStaticMethodIDOrDie(env, gZygoteInitClass, "prefetchStandaloneSystemServerJars",
2938 "()V");
2939
2940 RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
2941
2942 return JNI_OK;
2943 }
2944 } // namespace android
2945