blob: 8216b616915c5ae79c9ad5bbcf8b40c81de49bcc [file] [log] [blame]
Narayan Kamath973b4662014-03-31 13:41:26 +01001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Chris Wailes30f16ca2019-01-17 14:57:10 -080017/*
18 * Disable optimization of this file if we are compiling with the address
19 * sanitizer. This is a mitigation for b/122921367 and can be removed once the
20 * bug is fixed.
21 */
22#if __has_feature(address_sanitizer)
23#pragma clang optimize off
24#endif
25
Colin Cross18cd9f52014-06-13 12:58:55 -070026#define LOG_TAG "Zygote"
Narayan Kamath973b4662014-03-31 13:41:26 +010027
wangmingming16d0dd1a2018-11-14 10:43:36 +080028#include <async_safe/log.h>
29
Narayan Kamath973b4662014-03-31 13:41:26 +010030// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
31#include <sys/mount.h>
32#include <linux/fs.h>
33
Chris Wailes8b35ba22019-01-10 16:55:32 -080034#include <array>
35#include <atomic>
Chris Wailesefc65b22018-10-26 12:41:54 -070036#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070037#include <list>
Chris Wailesefc65b22018-10-26 12:41:54 -070038#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080039#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070040#include <string>
Chris Wailes8b35ba22019-01-10 16:55:32 -080041#include <string_view>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070042
Josh Gaod7951102018-06-26 16:05:12 -070043#include <android/fdsan.h>
Chris Wailes8b35ba22019-01-10 16:55:32 -080044#include <arpa/inet.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070045#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080046#include <grp.h>
47#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070048#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070049#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010050#include <paths.h>
51#include <signal.h>
52#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070053#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040054#include <sys/cdefs.h>
Chris Wailes8b35ba22019-01-10 16:55:32 -080055#include <sys/eventfd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070056#include <sys/personality.h>
57#include <sys/prctl.h>
58#include <sys/resource.h>
Chris Wailes8b35ba22019-01-10 16:55:32 -080059#include <sys/socket.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070060#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070061#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070062#include <sys/types.h>
63#include <sys/utsname.h>
64#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080065#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070066
Chris Wailes8b35ba22019-01-10 16:55:32 -080067#include <android-base/logging.h>
Minchan Kim696873e2018-06-27 11:32:40 +090068#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080069#include <android-base/file.h>
70#include <android-base/stringprintf.h>
Chris Wailes8b35ba22019-01-10 16:55:32 -080071#include <android-base/unique_fd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070072#include <cutils/fs.h>
73#include <cutils/multiuser.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070074#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070075#include <utils/String8.h>
76#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080077#include <seccomp_policy.h>
Howard Ro65e48ec2018-10-02 12:08:28 -070078#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070079#include <processgroup/processgroup.h>
Suren Baghdasaryan5d445ad2019-01-25 05:23:40 +000080#include <processgroup/sched_policy.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070081
Andreas Gampeed6b9df2014-11-20 22:02:20 -080082#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070083#include <nativehelper/JNIHelp.h>
84#include <nativehelper/ScopedLocalRef.h>
85#include <nativehelper/ScopedPrimitiveArray.h>
86#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050087#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010088
jgu212eacd062014-09-10 06:55:07 -040089#include "nativebridge/native_bridge.h"
90
Narayan Kamath973b4662014-03-31 13:41:26 +010091namespace {
92
Chris Wailes8b35ba22019-01-10 16:55:32 -080093// TODO (chriswailes): Add a function to initialize native Zygote data.
94// TODO (chriswailes): Fix mixed indentation style (2 and 4 spaces).
95
Chris Wailesefc65b22018-10-26 12:41:54 -070096using namespace std::placeholders;
97
Narayan Kamath973b4662014-03-31 13:41:26 +010098using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080099using android::base::StringPrintf;
100using android::base::WriteStringToFile;
Minchan Kim696873e2018-06-27 11:32:40 +0900101using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +0100102
Andreas Gamped5758f62018-03-12 12:08:55 -0700103#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
104 append(StringPrintf(__VA_ARGS__))
105
Chris Wailes8b35ba22019-01-10 16:55:32 -0800106// This type is duplicated in fd_utils.h
107typedef const std::function<void(std::string)>& fail_fn_t;
108
Narayan Kamath973b4662014-03-31 13:41:26 +0100109static pid_t gSystemServerPid = 0;
110
111static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
112static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +0100113static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +0100114static jmethodID gCallPostForkChildHooks;
115
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800116static bool g_is_security_enforced = true;
117
Chris Wailes8b35ba22019-01-10 16:55:32 -0800118/**
119 * The maximum number of characters (not including a null terminator) that a
120 * process name may contain.
121 */
122static constexpr size_t MAX_NAME_LENGTH = 15;
123
124/**
125 * The prefix string for environmental variables storing socket FDs created by
126 * init.
127 */
128
129static constexpr std::string_view ANDROID_SOCKET_PREFIX("ANDROID_SOCKET_");
130
131/**
132 * The file descriptor for the Zygote socket opened by init.
133 */
134
135static int gZygoteSocketFD = -1;
136
137/**
138 * The file descriptor for the Blastula pool socket opened by init.
139 */
140
141static int gBlastulaPoolSocketFD = -1;
142
143/**
144 * The number of Blastulas currently in this Zygote's pool.
145 */
146static std::atomic_uint32_t gBlastulaPoolCount = 0;
147
148/**
149 * Event file descriptor used to communicate reaped blastulas to the
150 * ZygoteServer.
151 */
152static int gBlastulaPoolEventFD = -1;
153
154/**
155 * The maximum value that the gBlastulaPoolMax variable may take. This value
156 * is a mirror of Zygote.BLASTULA_POOL_MAX_LIMIT
157 */
158static constexpr int BLASTULA_POOL_MAX_LIMIT = 10;
159
160/**
161 * A helper class containing accounting information for Blastulas.
162 */
163class BlastulaTableEntry {
164 public:
165 struct EntryStorage {
166 int32_t pid;
167 int32_t read_pipe_fd;
168
169 bool operator!=(const EntryStorage& other) {
170 return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
171 }
172 };
173
174 private:
175 static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
176
177 std::atomic<EntryStorage> mStorage;
178 static_assert(decltype(mStorage)::is_always_lock_free);
179
180 public:
181 constexpr BlastulaTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
182
183 /**
184 * If the provided PID matches the one stored in this entry, the entry will
185 * be invalidated and the associated file descriptor will be closed. If the
186 * PIDs don't match nothing will happen.
187 *
188 * @param pid The ID of the process who's entry we want to clear.
189 * @return True if the entry was cleared; false otherwise
190 */
191 bool ClearForPID(int32_t pid) {
192 EntryStorage storage = mStorage.load();
193
194 if (storage.pid == pid) {
195 /*
196 * There are three possible outcomes from this compare-and-exchange:
197 * 1) It succeeds, in which case we close the FD
198 * 2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
199 * the entry has already been cleared.
200 * 3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
201 * case the entry has already been cleared and re-used.
202 *
203 * In all three cases the goal of the caller has been met and we can
204 * return true.
205 */
206 if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
207 close(storage.read_pipe_fd);
208 }
209
210 return true;
211 } else {
212 return false;
213 }
214 }
215
216 /**
217 * @return A copy of the data stored in this entry.
218 */
219 std::optional<EntryStorage> GetValues() {
220 EntryStorage storage = mStorage.load();
221
222 if (storage != INVALID_ENTRY_VALUE) {
223 return storage;
224 } else {
225 return std::nullopt;
226 }
227 }
228
229 /**
230 * Sets the entry to the given values if it is currently invalid.
231 *
232 * @param pid The process ID for the new entry.
233 * @param read_pipe_fd The read end of the blastula control pipe for this
234 * process.
235 * @return True if the entry was set; false otherwise.
236 */
237 bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
238 EntryStorage new_value_storage;
239
240 new_value_storage.pid = pid;
241 new_value_storage.read_pipe_fd = read_pipe_fd;
242
243 EntryStorage expected = INVALID_ENTRY_VALUE;
244
245 return mStorage.compare_exchange_strong(expected, new_value_storage);
246 }
247};
248
249/**
250 * A table containing information about the Blastulas currently in the pool.
251 *
252 * Multiple threads may be attempting to modify the table, either from the
253 * signal handler or from the ZygoteServer poll loop. Atomic loads/stores in
254 * the BlastulaTableEntry class prevent data races during these concurrent
255 * operations.
256 */
257static std::array<BlastulaTableEntry, BLASTULA_POOL_MAX_LIMIT> gBlastulaTable;
258
259/**
260 * The list of open zygote file descriptors.
261 */
262static FileDescriptorTable* gOpenFdTable = nullptr;
263
Narayan Kamath973b4662014-03-31 13:41:26 +0100264// Must match values in com.android.internal.os.Zygote.
265enum MountExternalKind {
266 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700267 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700268 MOUNT_EXTERNAL_READ = 2,
269 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +0100270};
271
Orion Hodson8d005a62018-12-05 12:28:53 +0000272// Must match values in com.android.internal.os.Zygote.
273enum RuntimeFlags : uint32_t {
274 DEBUG_ENABLE_JDWP = 1,
275};
276
Chris Wailes8b35ba22019-01-10 16:55:32 -0800277// Forward declaration so we don't have to move the signal handler.
278static bool RemoveBlastulaTableEntry(pid_t blastula_pid);
279
Andreas Gampeb053cce2015-11-17 16:38:59 -0800280static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
281 std::ostringstream oss;
282 oss << __FILE__ << ":" << line << ": " << msg;
283 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100284}
285
286// This signal handler is for zygote mode, since the zygote must reap its children
287static void SigChldHandler(int /*signal_number*/) {
288 pid_t pid;
289 int status;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800290 int64_t blastulas_removed = 0;
Narayan Kamath973b4662014-03-31 13:41:26 +0100291
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700292 // It's necessary to save and restore the errno during this function.
293 // Since errno is stored per thread, changing it here modifies the errno
294 // on the thread on which this signal handler executes. If a signal occurs
295 // between a call and an errno check, it's possible to get the errno set
296 // here.
297 // See b/23572286 for extra information.
298 int saved_errno = errno;
299
Narayan Kamath973b4662014-03-31 13:41:26 +0100300 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800301 // Log process-death status that we care about.
Narayan Kamath973b4662014-03-31 13:41:26 +0100302 if (WIFEXITED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800303 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
304 "Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100305 } else if (WIFSIGNALED(status)) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800306 async_safe_format_log(ANDROID_LOG_INFO, LOG_TAG,
307 "Process %d exited due to signal %d (%s)%s", pid,
308 WTERMSIG(status), strsignal(WTERMSIG(status)),
309 WCOREDUMP(status) ? "; core dumped" : "");
Narayan Kamath973b4662014-03-31 13:41:26 +0100310 }
311
312 // If the just-crashed process is the system_server, bring down zygote
313 // so that it is restarted by init and system server will be restarted
314 // from there.
315 if (pid == gSystemServerPid) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800316 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
317 "Exit zygote because system server (pid %d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100318 kill(getpid(), SIGKILL);
319 }
Chris Wailes8b35ba22019-01-10 16:55:32 -0800320
321 // Check to see if the PID is in the blastula pool and remove it if it is.
322 if (RemoveBlastulaTableEntry(pid)) {
323 ++blastulas_removed;
324 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100325 }
326
Narayan Kamath160992d2014-04-14 14:46:07 +0100327 // Note that we shouldn't consider ECHILD an error because
328 // the secondary zygote might have no children left to wait for.
329 if (pid < 0 && errno != ECHILD) {
wangmingming16d0dd1a2018-11-14 10:43:36 +0800330 async_safe_format_log(ANDROID_LOG_WARN, LOG_TAG,
331 "Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100332 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700333
Chris Wailes8b35ba22019-01-10 16:55:32 -0800334 if (blastulas_removed > 0) {
335 if (write(gBlastulaPoolEventFD, &blastulas_removed, sizeof(blastulas_removed)) == -1) {
336 // If this write fails something went terribly wrong. We will now kill
337 // the zygote and let the system bring it back up.
wangmingming16d0dd1a2018-11-14 10:43:36 +0800338 async_safe_format_log(ANDROID_LOG_ERROR, LOG_TAG,
339 "Zygote failed to write to blastula pool event FD: %s",
340 strerror(errno));
Chris Wailes8b35ba22019-01-10 16:55:32 -0800341 kill(getpid(), SIGKILL);
342 }
343 }
344
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700345 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100346}
347
yuanhao435e84b2018-01-15 15:37:02 +0800348// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
349// configured very late, because earlier in the runtime we may fork() and
350// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100351// have them be harvested immediately.
352//
yuanhao435e84b2018-01-15 15:37:02 +0800353// Ignore SIGHUP because all processes forked by the zygote are in the same
354// process group as the zygote and we don't want to be notified if we become
355// an orphaned group and have one or more stopped processes. This is not a
356// theoretical concern :
357// - we can become an orphaned group if one of our direct descendants forks
358// and is subsequently killed before its children.
359// - crash_dump routinely STOPs the process it's tracing.
360//
361// See issues b/71965619 and b/25567761 for further details.
362//
Narayan Kamath973b4662014-03-31 13:41:26 +0100363// This ends up being called repeatedly before each fork(), but there's
364// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800365static void SetSignalHandlers() {
366 struct sigaction sig_chld = {};
367 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100368
Chris Wailes8b35ba22019-01-10 16:55:32 -0800369 if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700370 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100371 }
yuanhao435e84b2018-01-15 15:37:02 +0800372
373 struct sigaction sig_hup = {};
374 sig_hup.sa_handler = SIG_IGN;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800375 if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
yuanhao435e84b2018-01-15 15:37:02 +0800376 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
377 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100378}
379
380// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800381static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100382 struct sigaction sa;
383 memset(&sa, 0, sizeof(sa));
384 sa.sa_handler = SIG_DFL;
385
Chris Wailes8b35ba22019-01-10 16:55:32 -0800386 if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700387 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100388 }
389}
390
391// Calls POSIX setgroups() using the int[] object as an argument.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800392// A nullptr argument is tolerated.
393static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) {
394 if (managed_gids == nullptr) {
395 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100396 }
397
Chris Wailes8b35ba22019-01-10 16:55:32 -0800398 ScopedIntArrayRO gids(env, managed_gids);
399 if (gids.get() == nullptr) {
400 fail_fn(CREATE_ERROR("Getting gids int array failed"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100401 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700402
Chris Wailes8b35ba22019-01-10 16:55:32 -0800403 if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
404 fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
405 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100406}
407
408// Sets the resource limits via setrlimit(2) for the values in the
409// two-dimensional array of integers that's passed in. The second dimension
Chris Wailes8b35ba22019-01-10 16:55:32 -0800410// contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
Narayan Kamath973b4662014-03-31 13:41:26 +0100411// treated as an empty array.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800412static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
413 if (managed_rlimits == nullptr) {
414 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100415 }
416
417 rlimit rlim;
418 memset(&rlim, 0, sizeof(rlim));
419
Chris Wailes8b35ba22019-01-10 16:55:32 -0800420 for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
421 ScopedLocalRef<jobject>
422 managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
423 ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
424
425 if (rlimit_handle.size() != 3) {
426 fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100427 }
428
Chris Wailes8b35ba22019-01-10 16:55:32 -0800429 rlim.rlim_cur = rlimit_handle[1];
430 rlim.rlim_max = rlimit_handle[2];
Narayan Kamath973b4662014-03-31 13:41:26 +0100431
Chris Wailes8b35ba22019-01-10 16:55:32 -0800432 if (setrlimit(rlimit_handle[0], &rlim) == -1) {
433 fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
434 rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
Narayan Kamath973b4662014-03-31 13:41:26 +0100435 }
436 }
437}
438
Orion Hodson8d005a62018-12-05 12:28:53 +0000439static void EnableDebugger() {
440 // To let a non-privileged gdbserver attach to this
441 // process, we must set our dumpable flag.
442 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
443 ALOGE("prctl(PR_SET_DUMPABLE) failed");
444 }
445
446 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
447 // is enabled (see kernel/Documentation/security/Yama.txt).
448 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
449 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
450 // case since it's expected behaviour.
451 if (errno != EINVAL) {
452 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
453 }
454 }
455
Orion Hodson2b71ad02018-12-07 16:44:33 +0000456 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
457 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
458 // Set the soft limit on core dump size to 0 without changing the hard limit.
459 rlimit rl;
460 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
461 ALOGE("getrlimit(RLIMIT_CORE) failed");
462 } else {
463 rl.rlim_cur = 0;
464 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
465 ALOGE("setrlimit(RLIMIT_CORE) failed");
466 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000467 }
468 }
469}
470
Narayan Kamath973b4662014-03-31 13:41:26 +0100471// The debug malloc library needs to know whether it's the zygote or a child.
472extern "C" int gMallocLeakZygoteChild;
473
Christopher Ferris76de39e2017-06-20 16:13:40 -0700474static void PreApplicationInit() {
475 // The child process sets this to indicate it's not the zygote.
476 gMallocLeakZygoteChild = 1;
477
478 // Set the jemalloc decay time to 1.
479 mallopt(M_DECAY_TIME, 1);
480}
481
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800482static void SetUpSeccompFilter(uid_t uid) {
483 if (!g_is_security_enforced) {
484 ALOGI("seccomp disabled by setenforce 0");
485 return;
486 }
487
488 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700489 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800490 set_app_seccomp_filter();
491 } else {
492 set_system_seccomp_filter();
493 }
494}
495
Chris Wailes8b35ba22019-01-10 16:55:32 -0800496static void EnableKeepCapabilities(fail_fn_t fail_fn) {
497 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
498 fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100499 }
500}
501
Chris Wailes8b35ba22019-01-10 16:55:32 -0800502static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
503 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
504 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100505 if (errno == EINVAL) {
506 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
507 "your kernel is compiled with file capabilities support");
508 } else {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800509 fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100510 }
511 }
512 }
513}
514
Chris Wailes8b35ba22019-01-10 16:55:32 -0800515static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
Josh Gao45dab782017-02-01 14:56:09 -0800516 __user_cap_header_struct capheader;
517 memset(&capheader, 0, sizeof(capheader));
518 capheader.version = _LINUX_CAPABILITY_VERSION_3;
519 capheader.pid = 0;
520
521 __user_cap_data_struct capdata[2];
522 if (capget(&capheader, &capdata[0]) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800523 fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800524 }
525
526 capdata[0].inheritable = inheritable;
527 capdata[1].inheritable = inheritable >> 32;
528
529 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800530 fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800531 }
532}
533
Chris Wailes8b35ba22019-01-10 16:55:32 -0800534static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
535 fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100536 __user_cap_header_struct capheader;
537 memset(&capheader, 0, sizeof(capheader));
538 capheader.version = _LINUX_CAPABILITY_VERSION_3;
539 capheader.pid = 0;
540
541 __user_cap_data_struct capdata[2];
542 memset(&capdata, 0, sizeof(capdata));
543 capdata[0].effective = effective;
544 capdata[1].effective = effective >> 32;
545 capdata[0].permitted = permitted;
546 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800547 capdata[0].inheritable = inheritable;
548 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100549
550 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800551 fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
552 "failed: %s", permitted, effective, inheritable, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100553 }
554}
555
Chris Wailes8b35ba22019-01-10 16:55:32 -0800556static void SetSchedulerPolicy(fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100557 errno = -set_sched_policy(0, SP_DEFAULT);
558 if (errno != 0) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800559 fail_fn(CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100560 }
561}
562
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700563static int UnmountTree(const char* path) {
564 size_t path_len = strlen(path);
565
566 FILE* fp = setmntent("/proc/mounts", "r");
Chris Wailes8b35ba22019-01-10 16:55:32 -0800567 if (fp == nullptr) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700568 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
569 return -errno;
570 }
571
572 // Some volumes can be stacked on each other, so force unmount in
573 // reverse order to give us the best chance of success.
574 std::list<std::string> toUnmount;
575 mntent* mentry;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800576 while ((mentry = getmntent(fp)) != nullptr) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700577 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
578 toUnmount.push_front(std::string(mentry->mnt_dir));
579 }
580 }
581 endmntent(fp);
582
Chih-Hung Hsieha1b644e2018-12-11 11:09:20 -0800583 for (const auto& path : toUnmount) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700584 if (umount2(path.c_str(), MNT_DETACH)) {
585 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
586 }
587 }
588 return 0;
589}
590
Narayan Kamath973b4662014-03-31 13:41:26 +0100591// Create a private mount namespace and bind mount appropriate emulated
592// storage for the given user.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800593static void MountEmulatedStorage(uid_t uid, jint mount_mode,
594 bool force_mount_namespace, fail_fn_t fail_fn) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700595 // See storage config details at http://source.android.com/tech/storage/
596
Jeff Sharkey9527b222015-06-24 15:24:48 -0700597 String8 storageSource;
598 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700599 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700600 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700601 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700602 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700603 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500604 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700605 // Sane default of no storage visible
Chris Wailes8b35ba22019-01-10 16:55:32 -0800606 return;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700607 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400608
609 // Create a second private mount namespace for our process
610 if (unshare(CLONE_NEWNS) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800611 fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400612 }
613
Robert Sesek06f39302017-03-20 17:30:05 -0400614 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
615 if (mount_mode == MOUNT_EXTERNAL_NONE) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800616 return;
Robert Sesek06f39302017-03-20 17:30:05 -0400617 }
618
Jeff Sharkey9527b222015-06-24 15:24:48 -0700619 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
Chris Wailes8b35ba22019-01-10 16:55:32 -0800620 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
621 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
622 storageSource.string(),
623 strerror(errno)));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700624 }
625
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700626 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700627 userid_t user_id = multiuser_get_user_id(uid);
628 const String8 userSource(String8::format("/mnt/user/%d", user_id));
629 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800630 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s (%s)",
631 userSource.string(), strerror(errno)));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700632 }
633
Chris Wailes8b35ba22019-01-10 16:55:32 -0800634 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
635 nullptr, MS_BIND, nullptr)) == -1) {
636 fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
637 userSource.string(), strerror(errno)));
638 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100639}
640
Narayan Kamath973b4662014-03-31 13:41:26 +0100641static bool NeedsNoRandomizeWorkaround() {
642#if !defined(__arm__)
643 return false;
644#else
645 int major;
646 int minor;
647 struct utsname uts;
648 if (uname(&uts) == -1) {
649 return false;
650 }
651
652 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
653 return false;
654 }
655
656 // Kernels before 3.4.* need the workaround.
657 return (major < 3) || ((major == 3) && (minor < 4));
658#endif
659}
Narayan Kamath973b4662014-03-31 13:41:26 +0100660
661// Utility to close down the Zygote socket file descriptors while
662// the child is still running as root with Zygote's privileges. Each
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800663// descriptor (if any) is closed via dup3(), replacing it with a valid
Narayan Kamath973b4662014-03-31 13:41:26 +0100664// (open) descriptor to /dev/null.
665
Chris Wailes8b35ba22019-01-10 16:55:32 -0800666static void DetachDescriptors(JNIEnv* env,
667 const std::vector<int>& fds_to_close,
668 fail_fn_t fail_fn) {
669
670 if (fds_to_close.size() > 0) {
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800671 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
Chris Wailes8b35ba22019-01-10 16:55:32 -0800672 if (devnull_fd == -1) {
673 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100674 }
Chris Wailes8b35ba22019-01-10 16:55:32 -0800675
676 for (int fd : fds_to_close) {
677 ALOGV("Switching descriptor %d to /dev/null", fd);
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800678 if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
679 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
Chris Wailes8b35ba22019-01-10 16:55:32 -0800680 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100681 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100682 }
683}
684
Chris Wailes8b35ba22019-01-10 16:55:32 -0800685void SetThreadName(const std::string& thread_name) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100686 bool hasAt = false;
687 bool hasDot = false;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800688
689 for (const char str_el : thread_name) {
690 if (str_el == '.') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100691 hasDot = true;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800692 } else if (str_el == '@') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100693 hasAt = true;
694 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100695 }
Chris Wailes8b35ba22019-01-10 16:55:32 -0800696
697 const char* name_start_ptr = thread_name.c_str();
698 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
699 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
Narayan Kamath973b4662014-03-31 13:41:26 +0100700 }
Chris Wailes8b35ba22019-01-10 16:55:32 -0800701
Narayan Kamath973b4662014-03-31 13:41:26 +0100702 // pthread_setname_np fails rather than truncating long strings.
703 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
Chris Wailes8b35ba22019-01-10 16:55:32 -0800704 strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
Narayan Kamath973b4662014-03-31 13:41:26 +0100705 errno = pthread_setname_np(pthread_self(), buf);
706 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700707 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100708 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800709 // Update base::logging default tag.
710 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100711}
712
Chris Wailes8b35ba22019-01-10 16:55:32 -0800713/**
714 * A failure function used to report fatal errors to the managed runtime. This
715 * function is often curried with the process name information and then passed
716 * to called functions.
717 *
718 * @param env Managed runtime environment
719 * @param process_name A native representation of the process name
720 * @param managed_process_name A managed representation of the process name
721 * @param msg The error message to be reported
722 */
Chris Wailesefc65b22018-10-26 12:41:54 -0700723[[noreturn]]
724static void ZygoteFailure(JNIEnv* env,
725 const char* process_name,
726 jstring managed_process_name,
727 const std::string& msg) {
728 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
729 if (managed_process_name != nullptr) {
730 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
731 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
732 process_name = scoped_managed_process_name_ptr->c_str();
733 }
734 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700735
Chris Wailesefc65b22018-10-26 12:41:54 -0700736 const std::string& error_msg =
737 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
738
739 env->FatalError(error_msg.c_str());
740 __builtin_unreachable();
741}
742
Chris Wailes8b35ba22019-01-10 16:55:32 -0800743/**
744 * A helper method for converting managed strings to native strings. A fatal
745 * error is generated if a problem is encountered in extracting a non-null
746 * string.
747 *
748 * @param env Managed runtime environment
749 * @param process_name A native representation of the process name
750 * @param managed_process_name A managed representation of the process name
751 * @param managed_string The managed string to extract
752 *
753 * @return An empty option if the managed string is null. A optional-wrapped
754 * string otherwise.
755 */
Chris Wailesefc65b22018-10-26 12:41:54 -0700756static std::optional<std::string> ExtractJString(JNIEnv* env,
757 const char* process_name,
758 jstring managed_process_name,
759 jstring managed_string) {
760 if (managed_string == nullptr) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800761 return std::nullopt;
Chris Wailesefc65b22018-10-26 12:41:54 -0700762 } else {
763 ScopedUtfChars scoped_string_chars(env, managed_string);
764
765 if (scoped_string_chars.c_str() != nullptr) {
766 return std::optional<std::string>(scoped_string_chars.c_str());
767 } else {
768 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700769 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700770 }
771}
772
Chris Wailes8b35ba22019-01-10 16:55:32 -0800773/**
774 * A helper method for converting managed integer arrays to native vectors. A
775 * fatal error is generated if a problem is encountered in extracting a non-null array.
776 *
777 * @param env Managed runtime environment
778 * @param process_name A native representation of the process name
779 * @param managed_process_name A managed representation of the process name
780 * @param managed_array The managed integer array to extract
781 *
782 * @return An empty option if the managed array is null. A optional-wrapped
783 * vector otherwise.
784 */
785static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
786 const char* process_name,
787 jstring managed_process_name,
788 jintArray managed_array) {
789 if (managed_array == nullptr) {
790 return std::nullopt;
791 } else {
792 ScopedIntArrayRO managed_array_handle(env, managed_array);
Chris Wailesefc65b22018-10-26 12:41:54 -0700793
Chris Wailes8b35ba22019-01-10 16:55:32 -0800794 if (managed_array_handle.get() != nullptr) {
795 std::vector<int> native_array;
796 native_array.reserve(managed_array_handle.size());
797
798 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
799 native_array.push_back(managed_array_handle[array_index]);
800 }
801
802 return std::move(native_array);
803
804 } else {
805 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
806 }
807 }
808}
809
810/**
811 * A utility function for blocking signals.
812 *
813 * @param signum Signal number to block
814 * @param fail_fn Fatal error reporting function
815 *
816 * @see ZygoteFailure
817 */
818static void BlockSignal(int signum, fail_fn_t fail_fn) {
819 sigset_t sigs;
820 sigemptyset(&sigs);
821 sigaddset(&sigs, signum);
822
823 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
824 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
825 }
826}
827
828
829/**
830 * A utility function for unblocking signals.
831 *
832 * @param signum Signal number to unblock
833 * @param fail_fn Fatal error reporting function
834 *
835 * @see ZygoteFailure
836 */
837static void UnblockSignal(int signum, fail_fn_t fail_fn) {
838 sigset_t sigs;
839 sigemptyset(&sigs);
840 sigaddset(&sigs, signum);
841
842 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
843 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
844 }
845}
846
847// Utility routine to fork a process from the zygote.
848static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
849 const std::vector<int>& fds_to_close,
850 const std::vector<int>& fds_to_ignore) {
851 SetSignalHandlers();
Chris Wailesefc65b22018-10-26 12:41:54 -0700852
853 // Curry a failure function.
854 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
855 nullptr, _1);
856
857 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
858 // log, which would result in the logging FDs we close being reopened.
859 // This would cause failures because the FDs are not whitelisted.
860 //
861 // Note that the zygote process is single threaded at this point.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800862 BlockSignal(SIGCHLD, fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700863
864 // Close any logging related FDs before we start evaluating the list of
865 // file descriptors.
866 __android_log_close();
867 stats_log_close();
868
869 // If this is the first fork for this zygote, create the open FD table. If
870 // it isn't, we just need to check whether the list of open files has changed
871 // (and it shouldn't in the normal case).
Chris Wailesefc65b22018-10-26 12:41:54 -0700872 if (gOpenFdTable == nullptr) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800873 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
874 } else {
875 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700876 }
877
878 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
879
880 pid_t pid = fork();
881
882 if (pid == 0) {
883 // The child process.
884 PreApplicationInit();
885
886 // Clean up any descriptors which must be closed immediately
Chris Wailes8b35ba22019-01-10 16:55:32 -0800887 DetachDescriptors(env, fds_to_close, fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700888
889 // Re-open all remaining open file descriptors so that they aren't shared
890 // with the zygote across a fork.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800891 gOpenFdTable->ReopenOrDetach(fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700892
893 // Turn fdsan back on.
894 android_fdsan_set_error_level(fdsan_error_level);
Martin Stjernholma9bd8c32019-02-23 02:35:07 +0000895 } else {
896 ALOGD("Forked child process %d", pid);
Chris Wailesefc65b22018-10-26 12:41:54 -0700897 }
898
899 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800900 UnblockSignal(SIGCHLD, fail_fn);
901
Chris Wailesefc65b22018-10-26 12:41:54 -0700902 return pid;
903}
904
905// Utility routine to specialize a zygote child process.
906static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
907 jint runtime_flags, jobjectArray rlimits,
908 jlong permitted_capabilities, jlong effective_capabilities,
909 jint mount_external, jstring managed_se_info,
910 jstring managed_nice_name, bool is_system_server,
911 bool is_child_zygote, jstring managed_instruction_set,
912 jstring managed_app_data_dir) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800913 const char* process_name = is_system_server ? "system_server" : "zygote";
914 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
915 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesefc65b22018-10-26 12:41:54 -0700916
917 auto se_info = extract_fn(managed_se_info);
918 auto nice_name = extract_fn(managed_nice_name);
919 auto instruction_set = extract_fn(managed_instruction_set);
920 auto app_data_dir = extract_fn(managed_app_data_dir);
921
David Sehrde8d0bd2018-06-22 10:45:36 -0700922 // Keep capabilities across UID change, unless we're staying root.
923 if (uid != 0) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800924 EnableKeepCapabilities(fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700925 }
926
Chris Wailes8b35ba22019-01-10 16:55:32 -0800927 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700928
Chris Wailes8b35ba22019-01-10 16:55:32 -0800929 DropCapabilitiesBoundingSet(fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700930
Chris Wailesefc65b22018-10-26 12:41:54 -0700931 bool use_native_bridge = !is_system_server &&
932 instruction_set.has_value() &&
933 android::NativeBridgeAvailable() &&
934 android::NeedsNativeBridge(instruction_set.value().c_str());
935
936 if (use_native_bridge && !app_data_dir.has_value()) {
937 // The app_data_dir variable should never be empty if we need to use a
938 // native bridge. In general, app_data_dir will never be empty for normal
939 // applications. It can only happen in special cases (for isolated
940 // processes which are not associated with any app). These are launched by
941 // the framework and should not be emulated anyway.
David Sehrde8d0bd2018-06-22 10:45:36 -0700942 use_native_bridge = false;
Chris Wailesefc65b22018-10-26 12:41:54 -0700943 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700944 }
945
Chris Wailes8b35ba22019-01-10 16:55:32 -0800946 MountEmulatedStorage(uid, mount_external, use_native_bridge, fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700947
948 // If this zygote isn't root, it won't be able to create a process group,
949 // since the directory is owned by root.
950 if (!is_system_server && getuid() == 0) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800951 const int rc = createProcessGroup(uid, getpid());
David Sehrde8d0bd2018-06-22 10:45:36 -0700952 if (rc != 0) {
953 if (rc == -EROFS) {
954 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
955 } else {
956 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
957 }
958 }
959 }
960
Chris Wailes8b35ba22019-01-10 16:55:32 -0800961 SetGids(env, gids, fail_fn);
962 SetRLimits(env, rlimits, fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700963
964 if (use_native_bridge) {
Chris Wailesefc65b22018-10-26 12:41:54 -0700965 // Due to the logic behind use_native_bridge we know that both app_data_dir
966 // and instruction_set contain values.
967 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
968 instruction_set.value().c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700969 }
970
Chris Wailesefc65b22018-10-26 12:41:54 -0700971 if (setresgid(gid, gid, gid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700972 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
973 }
974
Chris Wailesefc65b22018-10-26 12:41:54 -0700975 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
976 // before changing uid from 0, which clears capabilities. The other
977 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
978 // breaks SELinux domain transition (see b/71859146). As the result,
979 // privileged syscalls used below still need to be accessible in app process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700980 SetUpSeccompFilter(uid);
981
Chris Wailesefc65b22018-10-26 12:41:54 -0700982 if (setresuid(uid, uid, uid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700983 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
984 }
985
986 // The "dumpable" flag of a process, which controls core dump generation, is
987 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
988 // user or group ID changes. See proc(5) for possible values. In most cases,
989 // the value is 0, so core dumps are disabled for zygote children. However,
990 // when running in a Chrome OS container, the value is already set to 2,
991 // which allows the external crash reporter to collect all core dumps. Since
992 // only system crashes are interested, core dump is disabled for app
993 // processes. This also ensures compliance with CTS.
994 int dumpable = prctl(PR_GET_DUMPABLE);
995 if (dumpable == -1) {
996 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
997 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
998 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700999
David Sehrde8d0bd2018-06-22 10:45:36 -07001000 if (dumpable == 2 && uid >= AID_APP) {
1001 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1002 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1003 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1004 }
1005 }
1006
Orion Hodson8d005a62018-12-05 12:28:53 +00001007 // Set process properties to enable debugging if required.
1008 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1009 EnableDebugger();
1010 }
1011
David Sehrde8d0bd2018-06-22 10:45:36 -07001012 if (NeedsNoRandomizeWorkaround()) {
1013 // Work around ARM kernel ASLR lossage (http://b/5817320).
1014 int old_personality = personality(0xffffffff);
1015 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1016 if (new_personality == -1) {
1017 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1018 }
1019 }
1020
Chris Wailes8b35ba22019-01-10 16:55:32 -08001021 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -07001022
Chris Wailes8b35ba22019-01-10 16:55:32 -08001023 SetSchedulerPolicy(fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -07001024
Chris Wailesefc65b22018-10-26 12:41:54 -07001025 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1026 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1027
1028 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1029 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1030 uid, is_system_server, se_info_ptr, nice_name_ptr));
David Sehrde8d0bd2018-06-22 10:45:36 -07001031 }
1032
1033 // Make it easier to debug audit logs by setting the main thread's name to the
1034 // nice name rather than "app_process".
Chris Wailesefc65b22018-10-26 12:41:54 -07001035 if (nice_name.has_value()) {
Chris Wailes8b35ba22019-01-10 16:55:32 -08001036 SetThreadName(nice_name.value());
Chris Wailesefc65b22018-10-26 12:41:54 -07001037 } else if (is_system_server) {
1038 SetThreadName("system_server");
David Sehrde8d0bd2018-06-22 10:45:36 -07001039 }
David Sehrde8d0bd2018-06-22 10:45:36 -07001040
1041 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1042 UnsetChldSignalHandler();
1043
Orion Hodson46724e72018-10-19 13:05:33 +01001044 if (is_system_server) {
1045 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1046 if (env->ExceptionCheck()) {
1047 fail_fn("Error calling post fork system server hooks.");
1048 }
Chris Wailes8b35ba22019-01-10 16:55:32 -08001049
Orion Hodson46724e72018-10-19 13:05:33 +01001050 // TODO(oth): Remove hardcoded label here (b/117874058).
1051 static const char* kSystemServerLabel = "u:r:system_server:s0";
1052 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1053 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1054 }
1055 }
1056
David Sehrde8d0bd2018-06-22 10:45:36 -07001057 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
Chris Wailesefc65b22018-10-26 12:41:54 -07001058 is_system_server, is_child_zygote, managed_instruction_set);
1059
David Sehrde8d0bd2018-06-22 10:45:36 -07001060 if (env->ExceptionCheck()) {
1061 fail_fn("Error calling post fork hooks.");
1062 }
1063}
1064
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001065static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1066 __user_cap_header_struct capheader;
1067 memset(&capheader, 0, sizeof(capheader));
1068 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1069 capheader.pid = 0;
1070
1071 __user_cap_data_struct capdata[2];
1072 if (capget(&capheader, &capdata[0]) == -1) {
1073 ALOGE("capget failed: %s", strerror(errno));
1074 RuntimeAbort(env, __LINE__, "capget failed");
1075 }
1076
Chris Wailesefc65b22018-10-26 12:41:54 -07001077 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1078}
1079
1080static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1081 bool is_child_zygote) {
1082 jlong capabilities = 0;
1083
1084 /*
1085 * Grant the following capabilities to the Bluetooth user:
1086 * - CAP_WAKE_ALARM
1087 * - CAP_NET_RAW
1088 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1089 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1090 */
1091
1092 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1093 capabilities |= (1LL << CAP_WAKE_ALARM);
1094 capabilities |= (1LL << CAP_NET_RAW);
1095 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1096 capabilities |= (1LL << CAP_SYS_NICE);
1097 }
1098
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001099 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1100 capabilities |= (1LL << CAP_NET_ADMIN);
1101 capabilities |= (1LL << CAP_NET_BROADCAST);
1102 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1103 capabilities |= (1LL << CAP_NET_RAW);
1104 }
1105
Chris Wailesefc65b22018-10-26 12:41:54 -07001106 /*
1107 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1108 */
1109
1110 bool gid_wakelock_found = false;
1111 if (gid == AID_WAKELOCK) {
1112 gid_wakelock_found = true;
1113 } else if (gids != nullptr) {
1114 jsize gids_num = env->GetArrayLength(gids);
1115 ScopedIntArrayRO native_gid_proxy(env, gids);
1116
1117 if (native_gid_proxy.get() == nullptr) {
1118 RuntimeAbort(env, __LINE__, "Bad gids array");
1119 }
1120
Chris Wailes31c52c92019-02-14 11:20:02 -08001121 for (int gids_index = 0; gids_index < gids_num; ++gids_index) {
1122 if (native_gid_proxy[gids_index] == AID_WAKELOCK) {
Chris Wailesefc65b22018-10-26 12:41:54 -07001123 gid_wakelock_found = true;
1124 break;
1125 }
1126 }
1127 }
1128
1129 if (gid_wakelock_found) {
1130 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1131 }
1132
1133 /*
1134 * Grant child Zygote processes the following capabilities:
1135 * - CAP_SETUID (change UID of child processes)
1136 * - CAP_SETGID (change GID of child processes)
1137 * - CAP_SETPCAP (change capabilities of child processes)
1138 */
1139
1140 if (is_child_zygote) {
1141 capabilities |= (1LL << CAP_SETUID);
1142 capabilities |= (1LL << CAP_SETGID);
1143 capabilities |= (1LL << CAP_SETPCAP);
1144 }
1145
1146 /*
1147 * Containers run without some capabilities, so drop any caps that are not
1148 * available.
1149 */
1150
1151 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001152}
Chris Wailes8b35ba22019-01-10 16:55:32 -08001153
1154/**
1155 * Adds the given information about a newly created blastula to the Zygote's
1156 * blastula table.
1157 *
1158 * @param blastula_pid Process ID of the newly created blastula
1159 * @param read_pipe_fd File descriptor for the read end of the blastula
1160 * reporting pipe. Used in the ZygoteServer poll loop to track blastula
1161 * specialization.
1162 */
1163static void AddBlastulaTableEntry(pid_t blastula_pid, int read_pipe_fd) {
1164 static int sBlastulaTableInsertIndex = 0;
1165
1166 int search_index = sBlastulaTableInsertIndex;
1167
1168 do {
1169 if (gBlastulaTable[search_index].SetIfInvalid(blastula_pid, read_pipe_fd)) {
1170 // Start our next search right after where we finished this one.
1171 sBlastulaTableInsertIndex = (search_index + 1) % gBlastulaTable.size();
1172
1173 return;
1174 }
1175
1176 search_index = (search_index + 1) % gBlastulaTable.size();
1177 } while (search_index != sBlastulaTableInsertIndex);
1178
1179 // Much like money in the banana stand, there should always be an entry
1180 // in the blastula table.
1181 __builtin_unreachable();
1182}
1183
1184/**
1185 * Invalidates the entry in the BlastulaTable corresponding to the provided
1186 * process ID if it is present. If an entry was removed the blastula pool
1187 * count is decremented.
1188 *
1189 * @param blastula_pid Process ID of the blastula entry to invalidate
1190 * @return True if an entry was invalidated; false otherwise
1191 */
1192static bool RemoveBlastulaTableEntry(pid_t blastula_pid) {
1193 for (BlastulaTableEntry& entry : gBlastulaTable) {
1194 if (entry.ClearForPID(blastula_pid)) {
1195 --gBlastulaPoolCount;
1196 return true;
1197 }
1198 }
1199
1200 return false;
1201}
1202
1203/**
1204 * @return A vector of the read pipe FDs for each of the active blastulas.
1205 */
1206std::vector<int> MakeBlastulaPipeReadFDVector() {
1207 std::vector<int> fd_vec;
1208 fd_vec.reserve(gBlastulaTable.size());
1209
1210 for (BlastulaTableEntry& entry : gBlastulaTable) {
1211 auto entry_values = entry.GetValues();
1212
1213 if (entry_values.has_value()) {
1214 fd_vec.push_back(entry_values.value().read_pipe_fd);
1215 }
1216 }
1217
1218 return fd_vec;
1219}
1220
Narayan Kamath973b4662014-03-31 13:41:26 +01001221} // anonymous namespace
1222
1223namespace android {
1224
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001225static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesefc65b22018-10-26 12:41:54 -07001226 // security_getenforce is not allowed on app process. Initialize and cache
1227 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001228 g_is_security_enforced = security_getenforce();
1229}
1230
Christopher Ferris76de39e2017-06-20 16:13:40 -07001231static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1232 PreApplicationInit();
1233}
1234
Narayan Kamath973b4662014-03-31 13:41:26 +01001235static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1236 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001237 jint runtime_flags, jobjectArray rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -07001238 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailes8b35ba22019-01-10 16:55:32 -08001239 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Chris Wailesefc65b22018-10-26 12:41:54 -07001240 jstring instruction_set, jstring app_data_dir) {
1241 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001242
Chris Wailes8b35ba22019-01-10 16:55:32 -08001243 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1244 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1245 }
1246
1247 std::vector<int> fds_to_close =
1248 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1249 std::vector<int> fds_to_ignore =
1250 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1251 .value_or(std::vector<int>());
1252
1253 std::vector<int> blastula_pipes = MakeBlastulaPipeReadFDVector();
1254
1255 fds_to_close.insert(fds_to_close.end(), blastula_pipes.begin(), blastula_pipes.end());
1256 fds_to_ignore.insert(fds_to_ignore.end(), blastula_pipes.begin(), blastula_pipes.end());
1257
Chris Wailescffbf1c2019-01-11 17:13:00 -08001258 fds_to_close.push_back(gBlastulaPoolSocketFD);
Chris Wailes8b35ba22019-01-10 16:55:32 -08001259
1260 if (gBlastulaPoolEventFD != -1) {
1261 fds_to_close.push_back(gBlastulaPoolEventFD);
1262 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1263 }
1264
Chris Wailesefc65b22018-10-26 12:41:54 -07001265 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
Chris Wailes8b35ba22019-01-10 16:55:32 -08001266
David Sehrde8d0bd2018-06-22 10:45:36 -07001267 if (pid == 0) {
1268 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1269 capabilities, capabilities,
Chris Wailesefc65b22018-10-26 12:41:54 -07001270 mount_external, se_info, nice_name, false,
1271 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
David Sehrde8d0bd2018-06-22 10:45:36 -07001272 }
1273 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001274}
1275
1276static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1277 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesefc65b22018-10-26 12:41:54 -07001278 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1279 jlong effective_capabilities) {
Chris Wailes8b35ba22019-01-10 16:55:32 -08001280 std::vector<int> fds_to_close(MakeBlastulaPipeReadFDVector()),
1281 fds_to_ignore(fds_to_close);
1282
Chris Wailescffbf1c2019-01-11 17:13:00 -08001283 fds_to_close.push_back(gBlastulaPoolSocketFD);
Chris Wailes8b35ba22019-01-10 16:55:32 -08001284
1285 if (gBlastulaPoolEventFD != -1) {
1286 fds_to_close.push_back(gBlastulaPoolEventFD);
1287 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1288 }
1289
Chris Wailesefc65b22018-10-26 12:41:54 -07001290 pid_t pid = ForkCommon(env, true,
Chris Wailes8b35ba22019-01-10 16:55:32 -08001291 fds_to_close,
1292 fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001293 if (pid == 0) {
1294 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -07001295 permitted_capabilities, effective_capabilities,
1296 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1297 false, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001298 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001299 // The zygote process checks whether the child process has died or not.
1300 ALOGI("System server process %d has been created", pid);
1301 gSystemServerPid = pid;
1302 // There is a slight window that the system server process has crashed
1303 // but it went unnoticed because we haven't published its pid yet. So
1304 // we recheck here just to make sure that all is well.
1305 int status;
1306 if (waitpid(pid, &status, WNOHANG) == pid) {
1307 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001308 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001309 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001310
Suren Baghdasaryan9c9b0252018-12-14 10:32:22 -08001311 if (UsePerAppMemcg()) {
Minchan Kim696873e2018-06-27 11:32:40 +09001312 // Assign system_server to the correct memory cgroup.
Suren Baghdasaryan9c9b0252018-12-14 10:32:22 -08001313 // Not all devices mount memcg so check if it is mounted first
Minchan Kim696873e2018-06-27 11:32:40 +09001314 // to avoid unnecessarily printing errors and denials in the logs.
Suren Baghdasaryan9c9b0252018-12-14 10:32:22 -08001315 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
1316 ALOGE("couldn't add process %d into system memcg group", pid);
Minchan Kim696873e2018-06-27 11:32:40 +09001317 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001318 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001319 }
1320 return pid;
1321}
1322
Chris Wailes8b35ba22019-01-10 16:55:32 -08001323/**
1324 * A JNI function that forks a blastula from the Zygote while ensuring proper
1325 * file descriptor hygiene.
1326 *
1327 * @param env Managed runtime environment
1328 * @param read_pipe_fd The read FD for the blastula reporting pipe. Manually closed by blastlas
1329 * in managed code.
1330 * @param write_pipe_fd The write FD for the blastula reporting pipe. Manually closed by the
1331 * zygote in managed code.
1332 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
1333 * the FD hygiene code and automatically "closed" in the new blastula.
1334 * @return
1335 */
1336static jint com_android_internal_os_Zygote_nativeForkBlastula(JNIEnv* env, jclass,
1337 jint read_pipe_fd, jint write_pipe_fd, jintArray managed_session_socket_fds) {
1338 std::vector<int> fds_to_close(MakeBlastulaPipeReadFDVector()),
1339 fds_to_ignore(fds_to_close);
1340
1341 std::vector<int> session_socket_fds =
1342 ExtractJIntArray(env, "blastula", nullptr, managed_session_socket_fds)
1343 .value_or(std::vector<int>());
1344
1345 // The Blastula Pool Event FD is created during the initialization of the
1346 // blastula pool and should always be valid here.
1347
1348 fds_to_close.push_back(gZygoteSocketFD);
1349 fds_to_close.push_back(gBlastulaPoolEventFD);
1350 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
1351
1352 fds_to_ignore.push_back(gZygoteSocketFD);
1353 fds_to_ignore.push_back(gBlastulaPoolSocketFD);
1354 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1355 fds_to_ignore.push_back(read_pipe_fd);
1356 fds_to_ignore.push_back(write_pipe_fd);
1357 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
1358
1359 pid_t blastula_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore);
1360
1361 if (blastula_pid != 0) {
1362 ++gBlastulaPoolCount;
1363 AddBlastulaTableEntry(blastula_pid, read_pipe_fd);
1364 }
1365
1366 return blastula_pid;
1367}
1368
Robert Sesek54e387d2016-12-02 17:27:50 -05001369static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1370 JNIEnv* env, jclass, jstring path) {
1371 ScopedUtfChars path_native(env, path);
1372 const char* path_cstr = path_native.c_str();
1373 if (!path_cstr) {
Chris Wailesefc65b22018-10-26 12:41:54 -07001374 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001375 }
1376 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1377}
1378
doheon1.lee885b7422016-01-20 13:07:27 +09001379static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1380 // Zygote process unmount root storage space initially before every child processes are forked.
1381 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001382 // and no need unmount storage operation in MountEmulatedStorage method.
1383 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1384
1385 // See storage config details at http://source.android.com/tech/storage/
1386 // Create private mount namespace shared by all children
1387 if (unshare(CLONE_NEWNS) == -1) {
1388 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1389 return;
1390 }
1391
1392 // Mark rootfs as being a slave so that changes from default
1393 // namespace only flow into our children.
1394 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1395 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1396 return;
1397 }
1398
1399 // Create a staging tmpfs that is shared by our children; they will
1400 // bind mount storage into their respective private namespaces, which
1401 // are isolated from each other.
1402 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1403 if (target_base != nullptr) {
1404#define STRINGIFY_UID(x) __STRING(x)
1405 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1406 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1407 ALOGE("Failed to mount tmpfs to %s", target_base);
1408 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1409 return;
1410 }
1411#undef STRINGIFY_UID
1412 }
doheon1.lee885b7422016-01-20 13:07:27 +09001413
1414 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001415}
1416
Chris Wailes8b35ba22019-01-10 16:55:32 -08001417/**
1418 * Called from a blastula to specialize the process for a specific application.
1419 *
1420 * @param env Managed runtime environment
1421 * @param uid User ID of the new application
1422 * @param gid Group ID of the new application
1423 * @param gids Extra groups that the process belongs to
1424 * @param runtime_flags Flags for changing the behavior of the managed runtime
1425 * @param rlimits Resource limits
1426 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
1427 * @param se_info SELinux policy information
1428 * @param nice_name New name for this process
1429 * @param is_child_zygote If the process is to become a WebViewZygote
1430 * @param instruction_set The instruction set expected/requested by the new application
1431 * @param app_data_dir Path to the application's data directory
1432 */
1433static void com_android_internal_os_Zygote_nativeSpecializeBlastula(
1434 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
1435 jint runtime_flags, jobjectArray rlimits,
1436 jint mount_external, jstring se_info, jstring nice_name,
1437 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
1438 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
1439
1440 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1441 capabilities, capabilities,
1442 mount_external, se_info, nice_name, false,
1443 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
1444}
1445
1446/**
1447 * A helper method for fetching socket file descriptors that were opened by init from the
1448 * environment.
1449 *
1450 * @param env Managed runtime environment
1451 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
1452 * of the environment variable storing the file descriptors.
1453 */
1454static void com_android_internal_os_Zygote_nativeGetSocketFDs(JNIEnv* env, jclass,
1455 jboolean is_primary) {
1456 std::string android_socket_prefix(ANDROID_SOCKET_PREFIX);
1457 std::string env_var_name = android_socket_prefix + (is_primary ? "zygote" : "zygote_secondary");
1458 char* env_var_val = getenv(env_var_name.c_str());
1459
1460 if (env_var_val != nullptr) {
1461 gZygoteSocketFD = atoi(env_var_val);
1462 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
1463 } else {
1464 ALOGE("Unable to fetch Zygote socket file descriptor");
1465 }
1466
1467 env_var_name = android_socket_prefix + (is_primary ? "blastula_pool" : "blastula_pool_secondary");
1468 env_var_val = getenv(env_var_name.c_str());
1469
1470 if (env_var_val != nullptr) {
1471 gBlastulaPoolSocketFD = atoi(env_var_val);
1472 ALOGV("Zygote:blastulaPoolSocketFD = %d", gBlastulaPoolSocketFD);
1473 } else {
1474 ALOGE("Unable to fetch Blastula pool socket file descriptor");
1475 }
1476}
1477
1478/**
1479 * @param env Managed runtime environment
1480 * @return A managed array of raw file descriptors for the read ends of the blastula reporting
1481 * pipes.
1482 */
1483static jintArray com_android_internal_os_Zygote_nativeGetBlastulaPipeFDs(JNIEnv* env, jclass) {
1484 std::vector<int> blastula_fds = MakeBlastulaPipeReadFDVector();
1485
1486 jintArray managed_blastula_fds = env->NewIntArray(blastula_fds.size());
1487 env->SetIntArrayRegion(managed_blastula_fds, 0, blastula_fds.size(), blastula_fds.data());
1488
1489 return managed_blastula_fds;
1490}
1491
1492/**
1493 * A JNI wrapper around RemoveBlastulaTableEntry.
1494 *
1495 * @param env Managed runtime environment
1496 * @param blastula_pid Process ID of the blastula entry to invalidate
1497 * @return True if an entry was invalidated; false otherwise.
1498 */
1499static jboolean com_android_internal_os_Zygote_nativeRemoveBlastulaTableEntry(JNIEnv* env, jclass,
1500 jint blastula_pid) {
1501 return RemoveBlastulaTableEntry(blastula_pid);
1502}
1503
1504/**
1505 * Creates the blastula pool event FD if it doesn't exist and returns it. This is used by the
1506 * ZygoteServer poll loop to know when to re-fill the blastula pool.
1507 *
1508 * @param env Managed runtime environment
1509 * @return A raw event file descriptor used to communicate (from the signal handler) when the
1510 * Zygote receives a SIGCHLD for a blastula
1511 */
1512static jint com_android_internal_os_Zygote_nativeGetBlastulaPoolEventFD(JNIEnv* env, jclass) {
1513 if (gBlastulaPoolEventFD == -1) {
1514 if ((gBlastulaPoolEventFD = eventfd(0, 0)) == -1) {
1515 ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
1516 }
1517 }
1518
1519 return gBlastulaPoolEventFD;
1520}
1521
1522/**
1523 * @param env Managed runtime environment
1524 * @return The number of blastulas currently in the blastula pool
1525 */
1526static jint com_android_internal_os_Zygote_nativeGetBlastulaPoolCount(JNIEnv* env, jclass) {
1527 return gBlastulaPoolCount;
1528}
1529
Daniel Micay76f6a862015-09-19 17:31:01 -04001530static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001531 { "nativeSecurityInit", "()V",
1532 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001533 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001534 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001535 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1536 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001537 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001538 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1539 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001540 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001541 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1542 { "nativePreApplicationInit", "()V",
Chris Wailes8b35ba22019-01-10 16:55:32 -08001543 (void *) com_android_internal_os_Zygote_nativePreApplicationInit },
1544 { "nativeForkBlastula", "(II[I)I",
1545 (void *) com_android_internal_os_Zygote_nativeForkBlastula },
1546 { "nativeSpecializeBlastula",
1547 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V",
1548 (void *) com_android_internal_os_Zygote_nativeSpecializeBlastula },
1549 { "nativeGetSocketFDs", "(Z)V",
1550 (void *) com_android_internal_os_Zygote_nativeGetSocketFDs },
1551 { "nativeGetBlastulaPipeFDs", "()[I",
1552 (void *) com_android_internal_os_Zygote_nativeGetBlastulaPipeFDs },
1553 { "nativeRemoveBlastulaTableEntry", "(I)Z",
1554 (void *) com_android_internal_os_Zygote_nativeRemoveBlastulaTableEntry },
1555 { "nativeGetBlastulaPoolEventFD", "()I",
1556 (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolEventFD },
1557 { "nativeGetBlastulaPoolCount", "()I",
1558 (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolCount }
Narayan Kamath973b4662014-03-31 13:41:26 +01001559};
1560
1561int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001562 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001563 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1564 "callPostForkSystemServerHooks",
1565 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001566 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001567 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001568
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001569 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001570}
1571} // namespace android