Debian Codegraph @

core/jni/com_android_internal_os_Zygote.cpp

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