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 /*
18  * Disable optimization of this file if we are compiling with the address
19  * sanitizer.  This is a mitigation for b/122921367 and can be removed once the
20  * bug is fixed.
21  */
22 #if __has_feature(address_sanitizer)
23 #pragma clang optimize off
24 #endif
25 
26 #define LOG_TAG "Zygote"
27 #define ATRACE_TAG ATRACE_TAG_DALVIK
28 
29 #include <async_safe/log.h>
30 
31 // sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
32 #include <sys/mount.h>
33 #include <linux/fs.h>
34 
35 #include <array>
36 #include <atomic>
37 #include <functional>
38 #include <list>
39 #include <optional>
40 #include <sstream>
41 #include <string>
42 #include <string_view>
43 
44 #include <android/fdsan.h>
45 #include <arpa/inet.h>
46 #include <fcntl.h>
47 #include <grp.h>
48 #include <inttypes.h>
49 #include <link.h>
50 #include <malloc.h>
51 #include <mntent.h>
52 #include <paths.h>
53 #include <signal.h>
54 #include <stdlib.h>
55 #include <sys/capability.h>
56 #include <sys/cdefs.h>
57 #include <sys/eventfd.h>
58 #include <sys/mman.h>
59 #include <sys/personality.h>
60 #include <sys/prctl.h>
61 #include <sys/resource.h>
62 #include <sys/socket.h>
63 #include <sys/stat.h>
64 #include <sys/time.h>
65 #include <sys/types.h>
66 #include <sys/utsname.h>
67 #include <sys/wait.h>
68 #include <unistd.h>
69 
70 #include <android-base/logging.h>
71 #include <android-base/properties.h>
72 #include <android-base/file.h>
73 #include <android-base/stringprintf.h>
74 #include <android-base/strings.h>
75 #include <android-base/unique_fd.h>
76 #include <bionic_malloc.h>
77 #include <cutils/ashmem.h>
78 #include <cutils/fs.h>
79 #include <cutils/multiuser.h>
80 #include <private/android_filesystem_config.h>
81 #include <utils/String8.h>
82 #include <utils/Trace.h>
83 #include <selinux/android.h>
84 #include <seccomp_policy.h>
85 #include <stats_event_list.h>
86 #include <processgroup/processgroup.h>
87 #include <processgroup/sched_policy.h>
88 
89 #include "core_jni_helpers.h"
90 #include <nativehelper/JNIHelp.h>
91 #include <nativehelper/ScopedLocalRef.h>
92 #include <nativehelper/ScopedPrimitiveArray.h>
93 #include <nativehelper/ScopedUtfChars.h>
94 #include "fd_utils.h"
95 
96 #include "nativebridge/native_bridge.h"
97 
98 namespace {
99 
100 // TODO (chriswailes): Add a function to initialize native Zygote data.
101 // TODO (chriswailes): Fix mixed indentation style (2 and 4 spaces).
102 
103 using namespace std::placeholders;
104 
105 using android::String8;
106 using android::base::StringAppendF;
107 using android::base::StringPrintf;
108 using android::base::WriteStringToFile;
109 using android::base::GetBoolProperty;
110 
111 #define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
112                               append(StringPrintf(__VA_ARGS__))
113 
114 // This type is duplicated in fd_utils.h
115 typedef const std::function<void(std::string)>& fail_fn_t;
116 
117 static pid_t gSystemServerPid = 0;
118 
119 static constexpr const char* kZygoteClassName = "com/android/internal/os/Zygote";
120 static jclass gZygoteClass;
121 static jmethodID gCallPostForkSystemServerHooks;
122 static jmethodID gCallPostForkChildHooks;
123 
124 static constexpr const char* kZygoteInitClassName = "com/android/internal/os/ZygoteInit";
125 static jclass gZygoteInitClass;
126 static jmethodID gCreateSystemServerClassLoader;
127 
128 static bool gIsSecurityEnforced = true;
129 
130 /**
131  * The maximum number of characters (not including a null terminator) that a
132  * process name may contain.
133  */
134 static constexpr size_t MAX_NAME_LENGTH = 15;
135 
136 /**
137  * The prefix string for environmental variables storing socket FDs created by
138  * init.
139  */
140 
141 static constexpr std::string_view ANDROID_SOCKET_PREFIX("ANDROID_SOCKET_");
142 
143 /**
144  * The file descriptor for the Zygote socket opened by init.
145  */
146 
147 static int gZygoteSocketFD = -1;
148 
149 /**
150  * The file descriptor for the unspecialized app process (USAP) pool socket opened by init.
151  */
152 
153 static int gUsapPoolSocketFD = -1;
154 
155 /**
156  * The number of USAPs currently in this Zygote's pool.
157  */
158 static std::atomic_uint32_t gUsapPoolCount = 0;
159 
160 /**
161  * Event file descriptor used to communicate reaped USAPs to the
162  * ZygoteServer.
163  */
164 static int gUsapPoolEventFD = -1;
165 
166 /**
167  * The maximum value that the gUSAPPoolSizeMax variable may take.  This value
168  * is a mirror of ZygoteServer.USAP_POOL_SIZE_MAX_LIMIT
169  */
170 static constexpr int USAP_POOL_SIZE_MAX_LIMIT = 100;
171 
172 /**
173  * A helper class containing accounting information for USAPs.
174  */
175 class UsapTableEntry {
176  public:
177   struct EntryStorage {
178     int32_t pid;
179     int32_t read_pipe_fd;
180 
operator !=__anon6123840f0111::UsapTableEntry::EntryStorage181     bool operator!=(const EntryStorage& other) {
182       return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
183     }
184   };
185 
186  private:
187   static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
188 
189   std::atomic<EntryStorage> mStorage;
190   static_assert(decltype(mStorage)::is_always_lock_free);
191 
192  public:
UsapTableEntry()193   constexpr UsapTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
194 
195   /**
196    * If the provided PID matches the one stored in this entry, the entry will
197    * be invalidated and the associated file descriptor will be closed.  If the
198    * PIDs don't match nothing will happen.
199    *
200    * @param pid The ID of the process who's entry we want to clear.
201    * @return True if the entry was cleared by this call; false otherwise
202    */
ClearForPID(int32_t pid)203   bool ClearForPID(int32_t pid) {
204     EntryStorage storage = mStorage.load();
205 
206     if (storage.pid == pid) {
207       /*
208        * There are three possible outcomes from this compare-and-exchange:
209        *   1) It succeeds, in which case we close the FD
210        *   2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
211        *      the entry has already been cleared.
212        *   3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
213        *      case the entry has already been cleared and re-used.
214        *
215        * In all three cases the goal of the caller has been met, but only in
216        * the first case do we need to decrement the pool count.
217        */
218       if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
219         close(storage.read_pipe_fd);
220         return true;
221       } else {
222         return false;
223       }
224 
225     } else {
226       return false;
227     }
228   }
229 
Clear()230   void Clear() {
231     EntryStorage storage = mStorage.load();
232 
233     if (storage != INVALID_ENTRY_VALUE) {
234       close(storage.read_pipe_fd);
235       mStorage.store(INVALID_ENTRY_VALUE);
236     }
237   }
238 
Invalidate()239   void Invalidate() {
240     mStorage.store(INVALID_ENTRY_VALUE);
241   }
242 
243   /**
244    * @return A copy of the data stored in this entry.
245    */
GetValues()246   std::optional<EntryStorage> GetValues() {
247     EntryStorage storage = mStorage.load();
248 
249     if (storage != INVALID_ENTRY_VALUE) {
250       return storage;
251     } else {
252       return std::nullopt;
253     }
254   }
255 
256   /**
257    * Sets the entry to the given values if it is currently invalid.
258    *
259    * @param pid  The process ID for the new entry.
260    * @param read_pipe_fd  The read end of the USAP control pipe for this
261    * process.
262    * @return True if the entry was set; false otherwise.
263    */
SetIfInvalid(int32_t pid,int32_t read_pipe_fd)264   bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
265     EntryStorage new_value_storage;
266 
267     new_value_storage.pid = pid;
268     new_value_storage.read_pipe_fd = read_pipe_fd;
269 
270     EntryStorage expected = INVALID_ENTRY_VALUE;
271 
272     return mStorage.compare_exchange_strong(expected, new_value_storage);
273   }
274 };
275 
276 /**
277  * A table containing information about the USAPs currently in the pool.
278  *
279  * Multiple threads may be attempting to modify the table, either from the
280  * signal handler or from the ZygoteServer poll loop.  Atomic loads/stores in
281  * the USAPTableEntry class prevent data races during these concurrent
282  * operations.
283  */
284 static std::array<UsapTableEntry, USAP_POOL_SIZE_MAX_LIMIT> gUsapTable;
285 
286 /**
287  * The list of open zygote file descriptors.
288  */
289 static FileDescriptorTable* gOpenFdTable = nullptr;
290 
291 // Must match values in com.android.internal.os.Zygote.
292 enum MountExternalKind {
293   MOUNT_EXTERNAL_NONE = 0,
294   MOUNT_EXTERNAL_DEFAULT = 1,
295   MOUNT_EXTERNAL_READ = 2,
296   MOUNT_EXTERNAL_WRITE = 3,
297   MOUNT_EXTERNAL_LEGACY = 4,
298   MOUNT_EXTERNAL_INSTALLER = 5,
299   MOUNT_EXTERNAL_FULL = 6,
300 };
301 
302 // Must match values in com.android.internal.os.Zygote.
303 enum RuntimeFlags : uint32_t {
304   DEBUG_ENABLE_JDWP = 1,
305   PROFILE_FROM_SHELL = 1 << 15,
306 };
307 
308 // Forward declaration so we don't have to move the signal handler.
309 static bool RemoveUsapTableEntry(pid_t usap_pid);
310 
RuntimeAbort(JNIEnv * env,int line,const char * msg)311 static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
312   std::ostringstream oss;
313   oss << __FILE__ << ":" << line << ": " << msg;
314   env->FatalError(oss.str().c_str());
315 }
316 
317 // This signal handler is for zygote mode, since the zygote must reap its children
SigChldHandler(int)318 static void SigChldHandler(int /*signal_number*/) {
319   pid_t pid;
320   int status;
321   int64_t usaps_removed = 0;
322 
323   // It's necessary to save and restore the errno during this function.
324   // Since errno is stored per thread, changing it here modifies the errno
325   // on the thread on which this signal handler executes. If a signal occurs
326   // between a call and an errno check, it's possible to get the errno set
327   // here.
328   // See b/23572286 for extra information.
329   int saved_errno = errno;
330 
331   while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
332      // Log process-death status that we care about.
333     if (WIFEXITED(status)) {
334       async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
335                             "Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
336 
337       // Check to see if the PID is in the USAP pool and remove it if it is.
338       if (RemoveUsapTableEntry(pid)) {
339         ++usaps_removed;
340       }
341     } else if (WIFSIGNALED(status)) {
342       async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
343                             "Process %d exited due to signal %d (%s)%s", pid,
344                             WTERMSIG(status), strsignal(WTERMSIG(status)),
345                             WCOREDUMP(status) ? "; core dumped" : "");
346 
347       // If the process exited due to a signal other than SIGTERM, check to see
348       // if the PID is in the USAP pool and remove it if it is.  If the process
349       // was closed by the Zygote using SIGTERM then the USAP pool entry will
350       // have already been removed (see nativeEmptyUsapPool()).
351       if (WTERMSIG(status) != SIGTERM && RemoveUsapTableEntry(pid)) {
352         ++usaps_removed;
353       }
354     }
355 
356     // If the just-crashed process is the system_server, bring down zygote
357     // so that it is restarted by init and system server will be restarted
358     // from there.
359     if (pid == gSystemServerPid) {
360       async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
361                             "Exit zygote because system server (pid %d) has terminated", pid);
362       kill(getpid(), SIGKILL);
363     }
364   }
365 
366   // Note that we shouldn't consider ECHILD an error because
367   // the secondary zygote might have no children left to wait for.
368   if (pid < 0 && errno != ECHILD) {
369     async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG,
370                           "Zygote SIGCHLD error in waitpid: %s", strerror(errno));
371   }
372 
373   if (usaps_removed > 0) {
374     if (TEMP_FAILURE_RETRY(write(gUsapPoolEventFD, &usaps_removed, sizeof(usaps_removed))) == -1) {
375       // If this write fails something went terribly wrong.  We will now kill
376       // the zygote and let the system bring it back up.
377       async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
378                             "Zygote failed to write to USAP pool event FD: %s",
379                             strerror(errno));
380       kill(getpid(), SIGKILL);
381     }
382   }
383 
384   errno = saved_errno;
385 }
386 
387 // Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
388 // configured very late, because earlier in the runtime we may fork() and
389 // exec() other processes, and we want to waitpid() for those rather than
390 // have them be harvested immediately.
391 //
392 // Ignore SIGHUP because all processes forked by the zygote are in the same
393 // process group as the zygote and we don't want to be notified if we become
394 // an orphaned group and have one or more stopped processes. This is not a
395 // theoretical concern :
396 // - we can become an orphaned group if one of our direct descendants forks
397 //   and is subsequently killed before its children.
398 // - crash_dump routinely STOPs the process it's tracing.
399 //
400 // See issues b/71965619 and b/25567761 for further details.
401 //
402 // This ends up being called repeatedly before each fork(), but there's
403 // no real harm in that.
SetSignalHandlers()404 static void SetSignalHandlers() {
405   struct sigaction sig_chld = {};
406   sig_chld.sa_handler = SigChldHandler;
407 
408   if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
409     ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
410   }
411 
412   struct sigaction sig_hup = {};
413   sig_hup.sa_handler = SIG_IGN;
414   if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
415     ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
416   }
417 }
418 
419 // Sets the SIGCHLD handler back to default behavior in zygote children.
UnsetChldSignalHandler()420 static void UnsetChldSignalHandler() {
421   struct sigaction sa;
422   memset(&sa, 0, sizeof(sa));
423   sa.sa_handler = SIG_DFL;
424 
425   if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
426     ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
427   }
428 }
429 
430 // Calls POSIX setgroups() using the int[] object as an argument.
431 // A nullptr argument is tolerated.
SetGids(JNIEnv * env,jintArray managed_gids,fail_fn_t fail_fn)432 static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) {
433   if (managed_gids == nullptr) {
434     return;
435   }
436 
437   ScopedIntArrayRO gids(env, managed_gids);
438   if (gids.get() == nullptr) {
439     fail_fn(CREATE_ERROR("Getting gids int array failed"));
440   }
441 
442   if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
443     fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
444   }
445 }
446 
447 // Sets the resource limits via setrlimit(2) for the values in the
448 // two-dimensional array of integers that's passed in. The second dimension
449 // contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
450 // treated as an empty array.
SetRLimits(JNIEnv * env,jobjectArray managed_rlimits,fail_fn_t fail_fn)451 static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
452   if (managed_rlimits == nullptr) {
453     return;
454   }
455 
456   rlimit rlim;
457   memset(&rlim, 0, sizeof(rlim));
458 
459   for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
460     ScopedLocalRef<jobject>
461         managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
462     ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
463 
464     if (rlimit_handle.size() != 3) {
465       fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
466     }
467 
468     rlim.rlim_cur = rlimit_handle[1];
469     rlim.rlim_max = rlimit_handle[2];
470 
471     if (setrlimit(rlimit_handle[0], &rlim) == -1) {
472       fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
473                            rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
474     }
475   }
476 }
477 
EnableDebugger()478 static void EnableDebugger() {
479   // To let a non-privileged gdbserver attach to this
480   // process, we must set our dumpable flag.
481   if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
482     ALOGE("prctl(PR_SET_DUMPABLE) failed");
483   }
484 
485   // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
486   // is enabled (see kernel/Documentation/security/Yama.txt).
487   if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
488     // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
489     // case since it's expected behaviour.
490     if (errno != EINVAL) {
491       ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
492     }
493   }
494 
495   // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
496   if (!GetBoolProperty("persist.zygote.core_dump", false)) {
497     // Set the soft limit on core dump size to 0 without changing the hard limit.
498     rlimit rl;
499     if (getrlimit(RLIMIT_CORE, &rl) == -1) {
500       ALOGE("getrlimit(RLIMIT_CORE) failed");
501     } else {
502       rl.rlim_cur = 0;
503       if (setrlimit(RLIMIT_CORE, &rl) == -1) {
504         ALOGE("setrlimit(RLIMIT_CORE) failed");
505       }
506     }
507   }
508 }
509 
PreApplicationInit()510 static void PreApplicationInit() {
511   // The child process sets this to indicate it's not the zygote.
512   android_mallopt(M_SET_ZYGOTE_CHILD, nullptr, 0);
513 
514   // Set the jemalloc decay time to 1.
515   mallopt(M_DECAY_TIME, 1);
516 }
517 
SetUpSeccompFilter(uid_t uid,bool is_child_zygote)518 static void SetUpSeccompFilter(uid_t uid, bool is_child_zygote) {
519   if (!gIsSecurityEnforced) {
520     ALOGI("seccomp disabled by setenforce 0");
521     return;
522   }
523 
524   // Apply system or app filter based on uid.
525   if (uid >= AID_APP_START) {
526     if (is_child_zygote) {
527       set_app_zygote_seccomp_filter();
528     } else {
529       set_app_seccomp_filter();
530     }
531   } else {
532     set_system_seccomp_filter();
533   }
534 }
535 
EnableKeepCapabilities(fail_fn_t fail_fn)536 static void EnableKeepCapabilities(fail_fn_t fail_fn) {
537   if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
538     fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
539   }
540 }
541 
DropCapabilitiesBoundingSet(fail_fn_t fail_fn)542 static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
543   for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
544     if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
545       if (errno == EINVAL) {
546         ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
547               "your kernel is compiled with file capabilities support");
548       } else {
549         fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
550       }
551     }
552   }
553 }
554 
SetInheritable(uint64_t inheritable,fail_fn_t fail_fn)555 static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
556   __user_cap_header_struct capheader;
557   memset(&capheader, 0, sizeof(capheader));
558   capheader.version = _LINUX_CAPABILITY_VERSION_3;
559   capheader.pid = 0;
560 
561   __user_cap_data_struct capdata[2];
562   if (capget(&capheader, &capdata[0]) == -1) {
563     fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
564   }
565 
566   capdata[0].inheritable = inheritable;
567   capdata[1].inheritable = inheritable >> 32;
568 
569   if (capset(&capheader, &capdata[0]) == -1) {
570     fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
571   }
572 }
573 
SetCapabilities(uint64_t permitted,uint64_t effective,uint64_t inheritable,fail_fn_t fail_fn)574 static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
575                             fail_fn_t fail_fn) {
576   __user_cap_header_struct capheader;
577   memset(&capheader, 0, sizeof(capheader));
578   capheader.version = _LINUX_CAPABILITY_VERSION_3;
579   capheader.pid = 0;
580 
581   __user_cap_data_struct capdata[2];
582   memset(&capdata, 0, sizeof(capdata));
583   capdata[0].effective = effective;
584   capdata[1].effective = effective >> 32;
585   capdata[0].permitted = permitted;
586   capdata[1].permitted = permitted >> 32;
587   capdata[0].inheritable = inheritable;
588   capdata[1].inheritable = inheritable >> 32;
589 
590   if (capset(&capheader, &capdata[0]) == -1) {
591     fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
592                          "failed: %s", permitted, effective, inheritable, strerror(errno)));
593   }
594 }
595 
SetSchedulerPolicy(fail_fn_t fail_fn)596 static void SetSchedulerPolicy(fail_fn_t fail_fn) {
597   errno = -set_sched_policy(0, SP_DEFAULT);
598   if (errno != 0) {
599     fail_fn(CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno)));
600   }
601 }
602 
UnmountTree(const char * path)603 static int UnmountTree(const char* path) {
604   ATRACE_CALL();
605 
606   size_t path_len = strlen(path);
607 
608   FILE* fp = setmntent("/proc/mounts", "r");
609   if (fp == nullptr) {
610     ALOGE("Error opening /proc/mounts: %s", strerror(errno));
611     return -errno;
612   }
613 
614   // Some volumes can be stacked on each other, so force unmount in
615   // reverse order to give us the best chance of success.
616   std::list<std::string> to_unmount;
617   mntent* mentry;
618   while ((mentry = getmntent(fp)) != nullptr) {
619     if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
620       to_unmount.push_front(std::string(mentry->mnt_dir));
621     }
622   }
623   endmntent(fp);
624 
625   for (const auto& path : to_unmount) {
626     if (umount2(path.c_str(), MNT_DETACH)) {
627       ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
628     }
629   }
630   return 0;
631 }
632 
633 // Create a private mount namespace and bind mount appropriate emulated
634 // storage for the given user.
MountEmulatedStorage(uid_t uid,jint mount_mode,bool force_mount_namespace,fail_fn_t fail_fn)635 static void MountEmulatedStorage(uid_t uid, jint mount_mode,
636         bool force_mount_namespace,
637         fail_fn_t fail_fn) {
638   // See storage config details at http://source.android.com/tech/storage/
639   ATRACE_CALL();
640 
641   String8 storage_source;
642   if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
643     storage_source = "/mnt/runtime/default";
644   } else if (mount_mode == MOUNT_EXTERNAL_READ) {
645     storage_source = "/mnt/runtime/read";
646   } else if (mount_mode == MOUNT_EXTERNAL_WRITE
647       || mount_mode == MOUNT_EXTERNAL_LEGACY
648       || mount_mode == MOUNT_EXTERNAL_INSTALLER) {
649     storage_source = "/mnt/runtime/write";
650   } else if (mount_mode == MOUNT_EXTERNAL_FULL) {
651     storage_source = "/mnt/runtime/full";
652   } else if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
653     // Sane default of no storage visible
654     return;
655   }
656 
657   // Create a second private mount namespace for our process
658   if (unshare(CLONE_NEWNS) == -1) {
659     fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
660   }
661 
662   // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
663   if (mount_mode == MOUNT_EXTERNAL_NONE) {
664     return;
665   }
666 
667   if (TEMP_FAILURE_RETRY(mount(storage_source.string(), "/storage", nullptr,
668                                MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
669     fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
670                          storage_source.string(),
671                          strerror(errno)));
672   }
673 
674   // Mount user-specific symlink helper into place
675   userid_t user_id = multiuser_get_user_id(uid);
676   const String8 user_source(String8::format("/mnt/user/%d", user_id));
677   if (fs_prepare_dir(user_source.string(), 0751, 0, 0) == -1) {
678     fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s",
679                          user_source.string()));
680   }
681 
682   if (TEMP_FAILURE_RETRY(mount(user_source.string(), "/storage/self",
683                                nullptr, MS_BIND, nullptr)) == -1) {
684     fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
685                          user_source.string(), strerror(errno)));
686   }
687 }
688 
NeedsNoRandomizeWorkaround()689 static bool NeedsNoRandomizeWorkaround() {
690 #if !defined(__arm__)
691     return false;
692 #else
693     int major;
694     int minor;
695     struct utsname uts;
696     if (uname(&uts) == -1) {
697         return false;
698     }
699 
700     if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
701         return false;
702     }
703 
704     // Kernels before 3.4.* need the workaround.
705     return (major < 3) || ((major == 3) && (minor < 4));
706 #endif
707 }
708 
709 // Utility to close down the Zygote socket file descriptors while
710 // the child is still running as root with Zygote's privileges.  Each
711 // descriptor (if any) is closed via dup3(), replacing it with a valid
712 // (open) descriptor to /dev/null.
713 
DetachDescriptors(JNIEnv * env,const std::vector<int> & fds_to_close,fail_fn_t fail_fn)714 static void DetachDescriptors(JNIEnv* env,
715                               const std::vector<int>& fds_to_close,
716                               fail_fn_t fail_fn) {
717 
718   if (fds_to_close.size() > 0) {
719     android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
720     if (devnull_fd == -1) {
721       fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
722     }
723 
724     for (int fd : fds_to_close) {
725       ALOGV("Switching descriptor %d to /dev/null", fd);
726       if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
727         fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
728       }
729     }
730   }
731 }
732 
SetThreadName(const std::string & thread_name)733 void SetThreadName(const std::string& thread_name) {
734   bool hasAt = false;
735   bool hasDot = false;
736 
737   for (const char str_el : thread_name) {
738     if (str_el == '.') {
739       hasDot = true;
740     } else if (str_el == '@') {
741       hasAt = true;
742     }
743   }
744 
745   const char* name_start_ptr = thread_name.c_str();
746   if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
747     name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
748   }
749 
750   // pthread_setname_np fails rather than truncating long strings.
751   char buf[16];       // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
752   strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
753   errno = pthread_setname_np(pthread_self(), buf);
754   if (errno != 0) {
755     ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
756   }
757   // Update base::logging default tag.
758   android::base::SetDefaultTag(buf);
759 }
760 
761 /**
762  * A failure function used to report fatal errors to the managed runtime.  This
763  * function is often curried with the process name information and then passed
764  * to called functions.
765  *
766  * @param env  Managed runtime environment
767  * @param process_name  A native representation of the process name
768  * @param managed_process_name  A managed representation of the process name
769  * @param msg  The error message to be reported
770  */
771 [[noreturn]]
ZygoteFailure(JNIEnv * env,const char * process_name,jstring managed_process_name,const std::string & msg)772 static void ZygoteFailure(JNIEnv* env,
773                           const char* process_name,
774                           jstring managed_process_name,
775                           const std::string& msg) {
776   std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
777   if (managed_process_name != nullptr) {
778     scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
779     if (scoped_managed_process_name_ptr->c_str() != nullptr) {
780       process_name = scoped_managed_process_name_ptr->c_str();
781     }
782   }
783 
784   const std::string& error_msg =
785       (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
786 
787   env->FatalError(error_msg.c_str());
788   __builtin_unreachable();
789 }
790 
791 /**
792  * A helper method for converting managed strings to native strings.  A fatal
793  * error is generated if a problem is encountered in extracting a non-null
794  * string.
795  *
796  * @param env  Managed runtime environment
797  * @param process_name  A native representation of the process name
798  * @param managed_process_name  A managed representation of the process name
799  * @param managed_string  The managed string to extract
800  *
801  * @return An empty option if the managed string is null.  A optional-wrapped
802  * string otherwise.
803  */
ExtractJString(JNIEnv * env,const char * process_name,jstring managed_process_name,jstring managed_string)804 static std::optional<std::string> ExtractJString(JNIEnv* env,
805                                                  const char* process_name,
806                                                  jstring managed_process_name,
807                                                  jstring managed_string) {
808   if (managed_string == nullptr) {
809     return std::nullopt;
810   } else {
811     ScopedUtfChars scoped_string_chars(env, managed_string);
812 
813     if (scoped_string_chars.c_str() != nullptr) {
814       return std::optional<std::string>(scoped_string_chars.c_str());
815     } else {
816       ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
817     }
818   }
819 }
820 
821 /**
822  * A helper method for converting managed string arrays to native vectors.  A
823  * fatal error is generated if a problem is encountered in extracting a non-null array.
824  *
825  * @param env  Managed runtime environment
826  * @param process_name  A native representation of the process name
827  * @param managed_process_name  A managed representation of the process name
828  * @param managed_array  The managed integer array to extract
829  *
830  * @return An empty option if the managed array is null.  A optional-wrapped
831  * vector otherwise.
832  */
ExtractJIntArray(JNIEnv * env,const char * process_name,jstring managed_process_name,jintArray managed_array)833 static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
834                                                         const char* process_name,
835                                                         jstring managed_process_name,
836                                                         jintArray managed_array) {
837   if (managed_array == nullptr) {
838     return std::nullopt;
839   } else {
840     ScopedIntArrayRO managed_array_handle(env, managed_array);
841 
842     if (managed_array_handle.get() != nullptr) {
843       std::vector<int> native_array;
844       native_array.reserve(managed_array_handle.size());
845 
846       for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
847         native_array.push_back(managed_array_handle[array_index]);
848       }
849 
850       return std::move(native_array);
851 
852     } else {
853       ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
854     }
855   }
856 }
857 
858 /**
859  * A utility function for blocking signals.
860  *
861  * @param signum  Signal number to block
862  * @param fail_fn  Fatal error reporting function
863  *
864  * @see ZygoteFailure
865  */
BlockSignal(int signum,fail_fn_t fail_fn)866 static void BlockSignal(int signum, fail_fn_t fail_fn) {
867   sigset_t sigs;
868   sigemptyset(&sigs);
869   sigaddset(&sigs, signum);
870 
871   if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
872     fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
873   }
874 }
875 
876 
877 /**
878  * A utility function for unblocking signals.
879  *
880  * @param signum  Signal number to unblock
881  * @param fail_fn  Fatal error reporting function
882  *
883  * @see ZygoteFailure
884  */
UnblockSignal(int signum,fail_fn_t fail_fn)885 static void UnblockSignal(int signum, fail_fn_t fail_fn) {
886   sigset_t sigs;
887   sigemptyset(&sigs);
888   sigaddset(&sigs, signum);
889 
890   if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
891     fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
892   }
893 }
894 
ClearUsapTable()895 static void ClearUsapTable() {
896   for (UsapTableEntry& entry : gUsapTable) {
897     entry.Clear();
898   }
899 
900   gUsapPoolCount = 0;
901 }
902 
903 // Utility routine to fork a process from the zygote.
ForkCommon(JNIEnv * env,bool is_system_server,const std::vector<int> & fds_to_close,const std::vector<int> & fds_to_ignore)904 static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
905                         const std::vector<int>& fds_to_close,
906                         const std::vector<int>& fds_to_ignore) {
907   SetSignalHandlers();
908 
909   // Curry a failure function.
910   auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
911                            nullptr, _1);
912 
913   // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
914   // log, which would result in the logging FDs we close being reopened.
915   // This would cause failures because the FDs are not whitelisted.
916   //
917   // Note that the zygote process is single threaded at this point.
918   BlockSignal(SIGCHLD, fail_fn);
919 
920   // Close any logging related FDs before we start evaluating the list of
921   // file descriptors.
922   __android_log_close();
923   stats_log_close();
924 
925   // If this is the first fork for this zygote, create the open FD table.  If
926   // it isn't, we just need to check whether the list of open files has changed
927   // (and it shouldn't in the normal case).
928   if (gOpenFdTable == nullptr) {
929     gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
930   } else {
931     gOpenFdTable->Restat(fds_to_ignore, fail_fn);
932   }
933 
934   android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
935 
936   pid_t pid = fork();
937 
938   if (pid == 0) {
939     // The child process.
940     PreApplicationInit();
941 
942     // Clean up any descriptors which must be closed immediately
943     DetachDescriptors(env, fds_to_close, fail_fn);
944 
945     // Invalidate the entries in the USAP table.
946     ClearUsapTable();
947 
948     // Re-open all remaining open file descriptors so that they aren't shared
949     // with the zygote across a fork.
950     gOpenFdTable->ReopenOrDetach(fail_fn);
951 
952     // Turn fdsan back on.
953     android_fdsan_set_error_level(fdsan_error_level);
954   } else {
955     ALOGD("Forked child process %d", pid);
956   }
957 
958   // We blocked SIGCHLD prior to a fork, we unblock it here.
959   UnblockSignal(SIGCHLD, fail_fn);
960 
961   return pid;
962 }
963 
964 // Utility routine to specialize a zygote child process.
SpecializeCommon(JNIEnv * env,uid_t uid,gid_t gid,jintArray gids,jint runtime_flags,jobjectArray rlimits,jlong permitted_capabilities,jlong effective_capabilities,jint mount_external,jstring managed_se_info,jstring managed_nice_name,bool is_system_server,bool is_child_zygote,jstring managed_instruction_set,jstring managed_app_data_dir)965 static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
966                              jint runtime_flags, jobjectArray rlimits,
967                              jlong permitted_capabilities, jlong effective_capabilities,
968                              jint mount_external, jstring managed_se_info,
969                              jstring managed_nice_name, bool is_system_server,
970                              bool is_child_zygote, jstring managed_instruction_set,
971                              jstring managed_app_data_dir) {
972   const char* process_name = is_system_server ? "system_server" : "zygote";
973   auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
974   auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
975 
976   auto se_info = extract_fn(managed_se_info);
977   auto nice_name = extract_fn(managed_nice_name);
978   auto instruction_set = extract_fn(managed_instruction_set);
979   auto app_data_dir = extract_fn(managed_app_data_dir);
980 
981   // Keep capabilities across UID change, unless we're staying root.
982   if (uid != 0) {
983     EnableKeepCapabilities(fail_fn);
984   }
985 
986   SetInheritable(permitted_capabilities, fail_fn);
987 
988   DropCapabilitiesBoundingSet(fail_fn);
989 
990   bool use_native_bridge = !is_system_server &&
991                            instruction_set.has_value() &&
992                            android::NativeBridgeAvailable() &&
993                            android::NeedsNativeBridge(instruction_set.value().c_str());
994 
995   if (use_native_bridge && !app_data_dir.has_value()) {
996     // The app_data_dir variable should never be empty if we need to use a
997     // native bridge.  In general, app_data_dir will never be empty for normal
998     // applications.  It can only happen in special cases (for isolated
999     // processes which are not associated with any app).  These are launched by
1000     // the framework and should not be emulated anyway.
1001     use_native_bridge = false;
1002     ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
1003   }
1004 
1005   MountEmulatedStorage(uid, mount_external, use_native_bridge, fail_fn);
1006 
1007   // If this zygote isn't root, it won't be able to create a process group,
1008   // since the directory is owned by root.
1009   if (!is_system_server && getuid() == 0) {
1010     const int rc = createProcessGroup(uid, getpid());
1011     if (rc == -EROFS) {
1012       ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
1013     } else if (rc != 0) {
1014       ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
1015     }
1016   }
1017 
1018   SetGids(env, gids, fail_fn);
1019   SetRLimits(env, rlimits, fail_fn);
1020 
1021   if (use_native_bridge) {
1022     // Due to the logic behind use_native_bridge we know that both app_data_dir
1023     // and instruction_set contain values.
1024     android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
1025                                        instruction_set.value().c_str());
1026   }
1027 
1028   if (setresgid(gid, gid, gid) == -1) {
1029     fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
1030   }
1031 
1032   // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
1033   // before changing uid from 0, which clears capabilities.  The other
1034   // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
1035   // breaks SELinux domain transition (see b/71859146).  As the result,
1036   // privileged syscalls used below still need to be accessible in app process.
1037   SetUpSeccompFilter(uid, is_child_zygote);
1038 
1039   if (setresuid(uid, uid, uid) == -1) {
1040     fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
1041   }
1042 
1043   // The "dumpable" flag of a process, which controls core dump generation, is
1044   // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
1045   // user or group ID changes. See proc(5) for possible values. In most cases,
1046   // the value is 0, so core dumps are disabled for zygote children. However,
1047   // when running in a Chrome OS container, the value is already set to 2,
1048   // which allows the external crash reporter to collect all core dumps. Since
1049   // only system crashes are interested, core dump is disabled for app
1050   // processes. This also ensures compliance with CTS.
1051   int dumpable = prctl(PR_GET_DUMPABLE);
1052   if (dumpable == -1) {
1053     ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
1054     RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
1055   }
1056 
1057   if (dumpable == 2 && uid >= AID_APP) {
1058     if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1059       ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1060       RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1061     }
1062   }
1063 
1064   // Set process properties to enable debugging if required.
1065   if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1066     EnableDebugger();
1067   }
1068   if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
1069     // simpleperf needs the process to be dumpable to profile it.
1070     if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
1071       ALOGE("prctl(PR_SET_DUMPABLE) failed: %s", strerror(errno));
1072       RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 1) failed");
1073     }
1074   }
1075 
1076   if (NeedsNoRandomizeWorkaround()) {
1077     // Work around ARM kernel ASLR lossage (http://b/5817320).
1078     int old_personality = personality(0xffffffff);
1079     int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1080     if (new_personality == -1) {
1081       ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1082     }
1083   }
1084 
1085   SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
1086 
1087   SetSchedulerPolicy(fail_fn);
1088 
1089   __android_log_close();
1090   stats_log_close();
1091 
1092   const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1093   const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1094 
1095   if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1096     fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1097                          uid, is_system_server, se_info_ptr, nice_name_ptr));
1098   }
1099 
1100   // Make it easier to debug audit logs by setting the main thread's name to the
1101   // nice name rather than "app_process".
1102   if (nice_name.has_value()) {
1103     SetThreadName(nice_name.value());
1104   } else if (is_system_server) {
1105     SetThreadName("system_server");
1106   }
1107 
1108   // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1109   UnsetChldSignalHandler();
1110 
1111   if (is_system_server) {
1112     env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1113     if (env->ExceptionCheck()) {
1114       fail_fn("Error calling post fork system server hooks.");
1115     }
1116 
1117     // Prefetch the classloader for the system server. This is done early to
1118     // allow a tie-down of the proper system server selinux domain.
1119     env->CallStaticVoidMethod(gZygoteInitClass, gCreateSystemServerClassLoader);
1120     if (env->ExceptionCheck()) {
1121       // Be robust here. The Java code will attempt to create the classloader
1122       // at a later point (but may not have rights to use AoT artifacts).
1123       env->ExceptionClear();
1124     }
1125 
1126     // TODO(oth): Remove hardcoded label here (b/117874058).
1127     static const char* kSystemServerLabel = "u:r:system_server:s0";
1128     if (selinux_android_setcon(kSystemServerLabel) != 0) {
1129       fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1130     }
1131   }
1132 
1133   env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1134                             is_system_server, is_child_zygote, managed_instruction_set);
1135 
1136   if (env->ExceptionCheck()) {
1137     fail_fn("Error calling post fork hooks.");
1138   }
1139 }
1140 
GetEffectiveCapabilityMask(JNIEnv * env)1141 static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1142     __user_cap_header_struct capheader;
1143     memset(&capheader, 0, sizeof(capheader));
1144     capheader.version = _LINUX_CAPABILITY_VERSION_3;
1145     capheader.pid = 0;
1146 
1147     __user_cap_data_struct capdata[2];
1148     if (capget(&capheader, &capdata[0]) == -1) {
1149         ALOGE("capget failed: %s", strerror(errno));
1150         RuntimeAbort(env, __LINE__, "capget failed");
1151     }
1152 
1153     return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1154 }
1155 
CalculateCapabilities(JNIEnv * env,jint uid,jint gid,jintArray gids,bool is_child_zygote)1156 static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1157                                    bool is_child_zygote) {
1158   jlong capabilities = 0;
1159 
1160   /*
1161    *  Grant the following capabilities to the Bluetooth user:
1162    *    - CAP_WAKE_ALARM
1163    *    - CAP_NET_ADMIN
1164    *    - CAP_NET_RAW
1165    *    - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1166    *    - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1167    */
1168 
1169   if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1170     capabilities |= (1LL << CAP_WAKE_ALARM);
1171     capabilities |= (1LL << CAP_NET_ADMIN);
1172     capabilities |= (1LL << CAP_NET_RAW);
1173     capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1174     capabilities |= (1LL << CAP_SYS_NICE);
1175   }
1176 
1177   if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1178     capabilities |= (1LL << CAP_NET_ADMIN);
1179     capabilities |= (1LL << CAP_NET_BROADCAST);
1180     capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1181     capabilities |= (1LL << CAP_NET_RAW);
1182   }
1183 
1184   /*
1185    * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1186    */
1187 
1188   bool gid_wakelock_found = false;
1189   if (gid == AID_WAKELOCK) {
1190     gid_wakelock_found = true;
1191   } else if (gids != nullptr) {
1192     jsize gids_num = env->GetArrayLength(gids);
1193     ScopedIntArrayRO native_gid_proxy(env, gids);
1194 
1195     if (native_gid_proxy.get() == nullptr) {
1196       RuntimeAbort(env, __LINE__, "Bad gids array");
1197     }
1198 
1199     for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
1200       if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
1201         gid_wakelock_found = true;
1202         break;
1203       }
1204     }
1205   }
1206 
1207   if (gid_wakelock_found) {
1208     capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1209   }
1210 
1211   /*
1212    * Grant child Zygote processes the following capabilities:
1213    *   - CAP_SETUID (change UID of child processes)
1214    *   - CAP_SETGID (change GID of child processes)
1215    *   - CAP_SETPCAP (change capabilities of child processes)
1216    */
1217 
1218   if (is_child_zygote) {
1219     capabilities |= (1LL << CAP_SETUID);
1220     capabilities |= (1LL << CAP_SETGID);
1221     capabilities |= (1LL << CAP_SETPCAP);
1222   }
1223 
1224   /*
1225    * Containers run without some capabilities, so drop any caps that are not
1226    * available.
1227    */
1228 
1229   return capabilities & GetEffectiveCapabilityMask(env);
1230 }
1231 
1232 /**
1233  * Adds the given information about a newly created unspecialized app
1234  * processes to the Zygote's USAP table.
1235  *
1236  * @param usap_pid  Process ID of the newly created USAP
1237  * @param read_pipe_fd  File descriptor for the read end of the USAP
1238  * reporting pipe.  Used in the ZygoteServer poll loop to track USAP
1239  * specialization.
1240  */
AddUsapTableEntry(pid_t usap_pid,int read_pipe_fd)1241 static void AddUsapTableEntry(pid_t usap_pid, int read_pipe_fd) {
1242   static int sUsapTableInsertIndex = 0;
1243 
1244   int search_index = sUsapTableInsertIndex;
1245 
1246   do {
1247     if (gUsapTable[search_index].SetIfInvalid(usap_pid, read_pipe_fd)) {
1248       // Start our next search right after where we finished this one.
1249       sUsapTableInsertIndex = (search_index + 1) % gUsapTable.size();
1250 
1251       return;
1252     }
1253 
1254     search_index = (search_index + 1) % gUsapTable.size();
1255   } while (search_index != sUsapTableInsertIndex);
1256 
1257   // Much like money in the banana stand, there should always be an entry
1258   // in the USAP table.
1259   __builtin_unreachable();
1260 }
1261 
1262 /**
1263  * Invalidates the entry in the USAPTable corresponding to the provided
1264  * process ID if it is present.  If an entry was removed the USAP pool
1265  * count is decremented.
1266  *
1267  * @param usap_pid  Process ID of the USAP entry to invalidate
1268  * @return True if an entry was invalidated; false otherwise
1269  */
RemoveUsapTableEntry(pid_t usap_pid)1270 static bool RemoveUsapTableEntry(pid_t usap_pid) {
1271   for (UsapTableEntry& entry : gUsapTable) {
1272     if (entry.ClearForPID(usap_pid)) {
1273       --gUsapPoolCount;
1274       return true;
1275     }
1276   }
1277 
1278   return false;
1279 }
1280 
1281 /**
1282  * @return A vector of the read pipe FDs for each of the active USAPs.
1283  */
MakeUsapPipeReadFDVector()1284 std::vector<int> MakeUsapPipeReadFDVector() {
1285   std::vector<int> fd_vec;
1286   fd_vec.reserve(gUsapTable.size());
1287 
1288   for (UsapTableEntry& entry : gUsapTable) {
1289     auto entry_values = entry.GetValues();
1290 
1291     if (entry_values.has_value()) {
1292       fd_vec.push_back(entry_values.value().read_pipe_fd);
1293     }
1294   }
1295 
1296   return fd_vec;
1297 }
1298 
UnmountStorageOnInit(JNIEnv * env)1299 static void UnmountStorageOnInit(JNIEnv* env) {
1300   // Zygote process unmount root storage space initially before every child processes are forked.
1301   // Every forked child processes (include SystemServer) only mount their own root storage space
1302   // and no need unmount storage operation in MountEmulatedStorage method.
1303   // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1304 
1305   // See storage config details at http://source.android.com/tech/storage/
1306   // Create private mount namespace shared by all children
1307   if (unshare(CLONE_NEWNS) == -1) {
1308     RuntimeAbort(env, __LINE__, "Failed to unshare()");
1309     return;
1310   }
1311 
1312   // Mark rootfs as being a slave so that changes from default
1313   // namespace only flow into our children.
1314   if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1315     RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1316     return;
1317   }
1318 
1319   // Create a staging tmpfs that is shared by our children; they will
1320   // bind mount storage into their respective private namespaces, which
1321   // are isolated from each other.
1322   const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1323   if (target_base != nullptr) {
1324 #define STRINGIFY_UID(x) __STRING(x)
1325     if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1326               "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1327       ALOGE("Failed to mount tmpfs to %s", target_base);
1328       RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1329       return;
1330     }
1331 #undef STRINGIFY_UID
1332   }
1333 
1334   UnmountTree("/storage");
1335 }
1336 
1337 }  // anonymous namespace
1338 
1339 namespace android {
1340 
com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv *,jclass)1341 static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1342   PreApplicationInit();
1343 }
1344 
com_android_internal_os_Zygote_nativeForkAndSpecialize(JNIEnv * env,jclass,jint uid,jint gid,jintArray gids,jint runtime_flags,jobjectArray rlimits,jint mount_external,jstring se_info,jstring nice_name,jintArray managed_fds_to_close,jintArray managed_fds_to_ignore,jboolean is_child_zygote,jstring instruction_set,jstring app_data_dir)1345 static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1346         JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
1347         jint runtime_flags, jobjectArray rlimits,
1348         jint mount_external, jstring se_info, jstring nice_name,
1349         jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
1350         jstring instruction_set, jstring app_data_dir) {
1351     jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
1352 
1353     if (UNLIKELY(managed_fds_to_close == nullptr)) {
1354       ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1355     }
1356 
1357     std::vector<int> fds_to_close =
1358         ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1359     std::vector<int> fds_to_ignore =
1360         ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1361             .value_or(std::vector<int>());
1362 
1363     std::vector<int> usap_pipes = MakeUsapPipeReadFDVector();
1364 
1365     fds_to_close.insert(fds_to_close.end(), usap_pipes.begin(), usap_pipes.end());
1366     fds_to_ignore.insert(fds_to_ignore.end(), usap_pipes.begin(), usap_pipes.end());
1367 
1368     fds_to_close.push_back(gUsapPoolSocketFD);
1369 
1370     if (gUsapPoolEventFD != -1) {
1371       fds_to_close.push_back(gUsapPoolEventFD);
1372       fds_to_ignore.push_back(gUsapPoolEventFD);
1373     }
1374 
1375     pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
1376 
1377     if (pid == 0) {
1378       SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1379                        capabilities, capabilities,
1380                        mount_external, se_info, nice_name, false,
1381                        is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
1382     }
1383     return pid;
1384 }
1385 
com_android_internal_os_Zygote_nativeForkSystemServer(JNIEnv * env,jclass,uid_t uid,gid_t gid,jintArray gids,jint runtime_flags,jobjectArray rlimits,jlong permitted_capabilities,jlong effective_capabilities)1386 static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1387         JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
1388         jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1389         jlong effective_capabilities) {
1390   std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
1391                    fds_to_ignore(fds_to_close);
1392 
1393   fds_to_close.push_back(gUsapPoolSocketFD);
1394 
1395   if (gUsapPoolEventFD != -1) {
1396     fds_to_close.push_back(gUsapPoolEventFD);
1397     fds_to_ignore.push_back(gUsapPoolEventFD);
1398   }
1399 
1400   pid_t pid = ForkCommon(env, true,
1401                          fds_to_close,
1402                          fds_to_ignore);
1403   if (pid == 0) {
1404       SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1405                        permitted_capabilities, effective_capabilities,
1406                        MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1407                        false, nullptr, nullptr);
1408   } else if (pid > 0) {
1409       // The zygote process checks whether the child process has died or not.
1410       ALOGI("System server process %d has been created", pid);
1411       gSystemServerPid = pid;
1412       // There is a slight window that the system server process has crashed
1413       // but it went unnoticed because we haven't published its pid yet. So
1414       // we recheck here just to make sure that all is well.
1415       int status;
1416       if (waitpid(pid, &status, WNOHANG) == pid) {
1417           ALOGE("System server process %d has died. Restarting Zygote!", pid);
1418           RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
1419       }
1420 
1421       if (UsePerAppMemcg()) {
1422           // Assign system_server to the correct memory cgroup.
1423           // Not all devices mount memcg so check if it is mounted first
1424           // to avoid unnecessarily printing errors and denials in the logs.
1425           if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
1426               ALOGE("couldn't add process %d into system memcg group", pid);
1427           }
1428       }
1429   }
1430   return pid;
1431 }
1432 
1433 /**
1434  * A JNI function that forks an unspecialized app process from the Zygote while
1435  * ensuring proper file descriptor hygiene.
1436  *
1437  * @param env  Managed runtime environment
1438  * @param read_pipe_fd  The read FD for the USAP reporting pipe.  Manually closed by blastlas
1439  * in managed code.
1440  * @param write_pipe_fd  The write FD for the USAP reporting pipe.  Manually closed by the
1441  * zygote in managed code.
1442  * @param managed_session_socket_fds  A list of anonymous session sockets that must be ignored by
1443  * the FD hygiene code and automatically "closed" in the new USAP.
1444  * @return
1445  */
com_android_internal_os_Zygote_nativeForkUsap(JNIEnv * env,jclass,jint read_pipe_fd,jint write_pipe_fd,jintArray managed_session_socket_fds)1446 static jint com_android_internal_os_Zygote_nativeForkUsap(JNIEnv* env,
1447                                                           jclass,
1448                                                           jint read_pipe_fd,
1449                                                           jint write_pipe_fd,
1450                                                           jintArray managed_session_socket_fds) {
1451   std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
1452                    fds_to_ignore(fds_to_close);
1453 
1454   std::vector<int> session_socket_fds =
1455       ExtractJIntArray(env, "USAP", nullptr, managed_session_socket_fds)
1456           .value_or(std::vector<int>());
1457 
1458   // The USAP Pool Event FD is created during the initialization of the
1459   // USAP pool and should always be valid here.
1460 
1461   fds_to_close.push_back(gZygoteSocketFD);
1462   fds_to_close.push_back(gUsapPoolEventFD);
1463   fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
1464 
1465   fds_to_ignore.push_back(gZygoteSocketFD);
1466   fds_to_ignore.push_back(gUsapPoolSocketFD);
1467   fds_to_ignore.push_back(gUsapPoolEventFD);
1468   fds_to_ignore.push_back(read_pipe_fd);
1469   fds_to_ignore.push_back(write_pipe_fd);
1470   fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
1471 
1472   pid_t usap_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore);
1473 
1474   if (usap_pid != 0) {
1475     ++gUsapPoolCount;
1476     AddUsapTableEntry(usap_pid, read_pipe_fd);
1477   }
1478 
1479   return usap_pid;
1480 }
1481 
com_android_internal_os_Zygote_nativeAllowFileAcrossFork(JNIEnv * env,jclass,jstring path)1482 static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1483         JNIEnv* env, jclass, jstring path) {
1484     ScopedUtfChars path_native(env, path);
1485     const char* path_cstr = path_native.c_str();
1486     if (!path_cstr) {
1487         RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
1488     }
1489     FileDescriptorWhitelist::Get()->Allow(path_cstr);
1490 }
1491 
com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(JNIEnv * env,jclass,jint uidGidMin,jint uidGidMax)1492 static void com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter(
1493         JNIEnv* env, jclass, jint uidGidMin, jint uidGidMax) {
1494   if (!gIsSecurityEnforced) {
1495     ALOGI("seccomp disabled by setenforce 0");
1496     return;
1497   }
1498 
1499   bool installed = install_setuidgid_seccomp_filter(uidGidMin, uidGidMax);
1500   if (!installed) {
1501       RuntimeAbort(env, __LINE__, "Could not install setuid/setgid seccomp filter.");
1502   }
1503 }
1504 
1505 /**
1506  * Called from an unspecialized app process to specialize the process for a
1507  * given application.
1508  *
1509  * @param env  Managed runtime environment
1510  * @param uid  User ID of the new application
1511  * @param gid  Group ID of the new application
1512  * @param gids  Extra groups that the process belongs to
1513  * @param runtime_flags  Flags for changing the behavior of the managed runtime
1514  * @param rlimits  Resource limits
1515  * @param mount_external  The mode (read/write/normal) that external storage will be mounted with
1516  * @param se_info  SELinux policy information
1517  * @param nice_name  New name for this process
1518  * @param is_child_zygote  If the process is to become a WebViewZygote
1519  * @param instruction_set  The instruction set expected/requested by the new application
1520  * @param app_data_dir  Path to the application's data directory
1521  */
com_android_internal_os_Zygote_nativeSpecializeAppProcess(JNIEnv * env,jclass,jint uid,jint gid,jintArray gids,jint runtime_flags,jobjectArray rlimits,jint mount_external,jstring se_info,jstring nice_name,jboolean is_child_zygote,jstring instruction_set,jstring app_data_dir)1522 static void com_android_internal_os_Zygote_nativeSpecializeAppProcess(
1523     JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
1524     jint runtime_flags, jobjectArray rlimits,
1525     jint mount_external, jstring se_info, jstring nice_name,
1526     jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
1527   jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
1528 
1529   SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1530                    capabilities, capabilities,
1531                    mount_external, se_info, nice_name, false,
1532                    is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
1533 }
1534 
1535 /**
1536  * A helper method for fetching socket file descriptors that were opened by init from the
1537  * environment.
1538  *
1539  * @param env  Managed runtime environment
1540  * @param is_primary  If this process is the primary or secondary Zygote; used to compute the name
1541  * of the environment variable storing the file descriptors.
1542  */
com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv * env,jclass,jboolean is_primary)1543 static void com_android_internal_os_Zygote_nativeInitNativeState(JNIEnv* env, jclass,
1544                                                                  jboolean is_primary) {
1545   /*
1546    * Obtain file descriptors created by init from the environment.
1547    */
1548 
1549   std::string android_socket_prefix(ANDROID_SOCKET_PREFIX);
1550   std::string env_var_name = android_socket_prefix + (is_primary ? "zygote" : "zygote_secondary");
1551   char* env_var_val = getenv(env_var_name.c_str());
1552 
1553   if (env_var_val != nullptr) {
1554     gZygoteSocketFD = atoi(env_var_val);
1555     ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
1556   } else {
1557     ALOGE("Unable to fetch Zygote socket file descriptor");
1558   }
1559 
1560   env_var_name = android_socket_prefix + (is_primary ? "usap_pool_primary" : "usap_pool_secondary");
1561   env_var_val = getenv(env_var_name.c_str());
1562 
1563   if (env_var_val != nullptr) {
1564     gUsapPoolSocketFD = atoi(env_var_val);
1565     ALOGV("Zygote:usapPoolSocketFD = %d", gUsapPoolSocketFD);
1566   } else {
1567     ALOGE("Unable to fetch USAP pool socket file descriptor");
1568   }
1569 
1570   /*
1571    * Security Initialization
1572    */
1573 
1574   // security_getenforce is not allowed on app process. Initialize and cache
1575   // the value before zygote forks.
1576   gIsSecurityEnforced = security_getenforce();
1577 
1578   selinux_android_seapp_context_init();
1579 
1580   /*
1581    * Storage Initialization
1582    */
1583 
1584   UnmountStorageOnInit(env);
1585 
1586   /*
1587    * Performance Initialization
1588    */
1589 
1590   if (!SetTaskProfiles(0, {})) {
1591     ZygoteFailure(env, "zygote", nullptr, "Zygote SetTaskProfiles failed");
1592   }
1593 
1594   /*
1595    * ashmem initialization to avoid dlopen overhead
1596    */
1597   ashmem_init();
1598 }
1599 
1600 /**
1601  * @param env  Managed runtime environment
1602  * @return  A managed array of raw file descriptors for the read ends of the USAP reporting
1603  * pipes.
1604  */
com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv * env,jclass)1605 static jintArray com_android_internal_os_Zygote_nativeGetUsapPipeFDs(JNIEnv* env, jclass) {
1606   std::vector<int> usap_fds = MakeUsapPipeReadFDVector();
1607 
1608   jintArray managed_usap_fds = env->NewIntArray(usap_fds.size());
1609   env->SetIntArrayRegion(managed_usap_fds, 0, usap_fds.size(), usap_fds.data());
1610 
1611   return managed_usap_fds;
1612 }
1613 
1614 /**
1615  * A JNI wrapper around RemoveUsapTableEntry.
1616  *
1617  * @param env  Managed runtime environment
1618  * @param usap_pid  Process ID of the USAP entry to invalidate
1619  * @return  True if an entry was invalidated; false otherwise.
1620  */
com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(JNIEnv * env,jclass,jint usap_pid)1621 static jboolean com_android_internal_os_Zygote_nativeRemoveUsapTableEntry(JNIEnv* env, jclass,
1622                                                                           jint usap_pid) {
1623   return RemoveUsapTableEntry(usap_pid);
1624 }
1625 
1626 /**
1627  * Creates the USAP pool event FD if it doesn't exist and returns it.  This is used by the
1628  * ZygoteServer poll loop to know when to re-fill the USAP pool.
1629  *
1630  * @param env  Managed runtime environment
1631  * @return A raw event file descriptor used to communicate (from the signal handler) when the
1632  * Zygote receives a SIGCHLD for a USAP
1633  */
com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv * env,jclass)1634 static jint com_android_internal_os_Zygote_nativeGetUsapPoolEventFD(JNIEnv* env, jclass) {
1635   if (gUsapPoolEventFD == -1) {
1636     if ((gUsapPoolEventFD = eventfd(0, 0)) == -1) {
1637       ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
1638     }
1639   }
1640 
1641   return gUsapPoolEventFD;
1642 }
1643 
1644 /**
1645  * @param env  Managed runtime environment
1646  * @return The number of USAPs currently in the USAP pool
1647  */
com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv * env,jclass)1648 static jint com_android_internal_os_Zygote_nativeGetUsapPoolCount(JNIEnv* env, jclass) {
1649   return gUsapPoolCount;
1650 }
1651 
1652 /**
1653  * Kills all processes currently in the USAP pool and closes their read pipe
1654  * FDs.
1655  *
1656  * @param env  Managed runtime environment
1657  */
com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv * env,jclass)1658 static void com_android_internal_os_Zygote_nativeEmptyUsapPool(JNIEnv* env, jclass) {
1659   for (auto& entry : gUsapTable) {
1660     auto entry_storage = entry.GetValues();
1661 
1662     if (entry_storage.has_value()) {
1663       kill(entry_storage.value().pid, SIGTERM);
1664 
1665       // Clean up the USAP table entry here.  This avoids a potential race
1666       // where a newly created USAP might not be able to find a valid table
1667       // entry if signal handler (which would normally do the cleanup) doesn't
1668       // run between now and when the new process is created.
1669 
1670       close(entry_storage.value().read_pipe_fd);
1671 
1672       // Avoid a second atomic load by invalidating instead of clearing.
1673       entry.Invalidate();
1674       --gUsapPoolCount;
1675     }
1676   }
1677 }
1678 
disable_execute_only(struct dl_phdr_info * info,size_t size,void * data)1679 static int disable_execute_only(struct dl_phdr_info *info, size_t size, void *data) {
1680   // Search for any execute-only segments and mark them read+execute.
1681   for (int i = 0; i < info->dlpi_phnum; i++) {
1682     if ((info->dlpi_phdr[i].p_type == PT_LOAD) && (info->dlpi_phdr[i].p_flags == PF_X)) {
1683       mprotect(reinterpret_cast<void*>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr),
1684               info->dlpi_phdr[i].p_memsz, PROT_READ | PROT_EXEC);
1685     }
1686   }
1687   // Return non-zero to exit dl_iterate_phdr.
1688   return 0;
1689 }
1690 
1691 /**
1692  * @param env  Managed runtime environment
1693  * @return  True if disable was successful.
1694  */
com_android_internal_os_Zygote_nativeDisableExecuteOnly(JNIEnv * env,jclass)1695 static jboolean com_android_internal_os_Zygote_nativeDisableExecuteOnly(JNIEnv* env, jclass) {
1696   return dl_iterate_phdr(disable_execute_only, nullptr) == 0;
1697 }
1698 
com_android_internal_os_Zygote_nativeBlockSigTerm(JNIEnv * env,jclass)1699 static void com_android_internal_os_Zygote_nativeBlockSigTerm(JNIEnv* env, jclass) {
1700   auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
1701   BlockSignal(SIGTERM, fail_fn);
1702 }
1703 
com_android_internal_os_Zygote_nativeUnblockSigTerm(JNIEnv * env,jclass)1704 static void com_android_internal_os_Zygote_nativeUnblockSigTerm(JNIEnv* env, jclass) {
1705   auto fail_fn = std::bind(ZygoteFailure, env, "usap", nullptr, _1);
1706   UnblockSignal(SIGTERM, fail_fn);
1707 }
1708 
1709 static const JNINativeMethod gMethods[] = {
1710     { "nativeForkAndSpecialize",
1711       "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
1712       (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1713     { "nativeForkSystemServer", "(II[II[[IJJ)I",
1714       (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
1715     { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1716       (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
1717     { "nativePreApplicationInit", "()V",
1718       (void *) com_android_internal_os_Zygote_nativePreApplicationInit },
1719     { "nativeInstallSeccompUidGidFilter", "(II)V",
1720       (void *) com_android_internal_os_Zygote_nativeInstallSeccompUidGidFilter },
1721     { "nativeForkUsap", "(II[I)I",
1722       (void *) com_android_internal_os_Zygote_nativeForkUsap },
1723     { "nativeSpecializeAppProcess",
1724       "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V",
1725       (void *) com_android_internal_os_Zygote_nativeSpecializeAppProcess },
1726     { "nativeInitNativeState", "(Z)V",
1727       (void *) com_android_internal_os_Zygote_nativeInitNativeState },
1728     { "nativeGetUsapPipeFDs", "()[I",
1729       (void *) com_android_internal_os_Zygote_nativeGetUsapPipeFDs },
1730     { "nativeRemoveUsapTableEntry", "(I)Z",
1731       (void *) com_android_internal_os_Zygote_nativeRemoveUsapTableEntry },
1732     { "nativeGetUsapPoolEventFD", "()I",
1733       (void *) com_android_internal_os_Zygote_nativeGetUsapPoolEventFD },
1734     { "nativeGetUsapPoolCount", "()I",
1735       (void *) com_android_internal_os_Zygote_nativeGetUsapPoolCount },
1736     { "nativeEmptyUsapPool", "()V",
1737       (void *) com_android_internal_os_Zygote_nativeEmptyUsapPool },
1738     { "nativeDisableExecuteOnly", "()Z",
1739       (void *) com_android_internal_os_Zygote_nativeDisableExecuteOnly },
1740     { "nativeBlockSigTerm", "()V",
1741       (void* ) com_android_internal_os_Zygote_nativeBlockSigTerm },
1742     { "nativeUnblockSigTerm", "()V",
1743       (void* ) com_android_internal_os_Zygote_nativeUnblockSigTerm }
1744 };
1745 
register_com_android_internal_os_Zygote(JNIEnv * env)1746 int register_com_android_internal_os_Zygote(JNIEnv* env) {
1747   gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
1748   gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1749                                                           "callPostForkSystemServerHooks",
1750                                                           "()V");
1751   gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
1752                                                    "(IZZLjava/lang/String;)V");
1753 
1754   gZygoteInitClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteInitClassName));
1755   gCreateSystemServerClassLoader = GetStaticMethodIDOrDie(env, gZygoteInitClass,
1756                                                           "createSystemServerClassLoader",
1757                                                           "()V");
1758 
1759   RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
1760 
1761   return JNI_OK;
1762 }
1763 }  // namespace android
1764