blob: abf294ba9c5934880b7a7d4950e725e547a8c68d [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);
895 }
896
897 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800898 UnblockSignal(SIGCHLD, fail_fn);
899
Chris Wailesefc65b22018-10-26 12:41:54 -0700900 return pid;
901}
902
903// Utility routine to specialize a zygote child process.
904static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
905 jint runtime_flags, jobjectArray rlimits,
906 jlong permitted_capabilities, jlong effective_capabilities,
907 jint mount_external, jstring managed_se_info,
908 jstring managed_nice_name, bool is_system_server,
909 bool is_child_zygote, jstring managed_instruction_set,
910 jstring managed_app_data_dir) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800911 const char* process_name = is_system_server ? "system_server" : "zygote";
912 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
913 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesefc65b22018-10-26 12:41:54 -0700914
915 auto se_info = extract_fn(managed_se_info);
916 auto nice_name = extract_fn(managed_nice_name);
917 auto instruction_set = extract_fn(managed_instruction_set);
918 auto app_data_dir = extract_fn(managed_app_data_dir);
919
David Sehrde8d0bd2018-06-22 10:45:36 -0700920 // Keep capabilities across UID change, unless we're staying root.
921 if (uid != 0) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800922 EnableKeepCapabilities(fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700923 }
924
Chris Wailes8b35ba22019-01-10 16:55:32 -0800925 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700926
Chris Wailes8b35ba22019-01-10 16:55:32 -0800927 DropCapabilitiesBoundingSet(fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700928
Chris Wailesefc65b22018-10-26 12:41:54 -0700929 bool use_native_bridge = !is_system_server &&
930 instruction_set.has_value() &&
931 android::NativeBridgeAvailable() &&
932 android::NeedsNativeBridge(instruction_set.value().c_str());
933
934 if (use_native_bridge && !app_data_dir.has_value()) {
935 // The app_data_dir variable should never be empty if we need to use a
936 // native bridge. In general, app_data_dir will never be empty for normal
937 // applications. It can only happen in special cases (for isolated
938 // processes which are not associated with any app). These are launched by
939 // the framework and should not be emulated anyway.
David Sehrde8d0bd2018-06-22 10:45:36 -0700940 use_native_bridge = false;
Chris Wailesefc65b22018-10-26 12:41:54 -0700941 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700942 }
943
Chris Wailes8b35ba22019-01-10 16:55:32 -0800944 MountEmulatedStorage(uid, mount_external, use_native_bridge, fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700945
946 // If this zygote isn't root, it won't be able to create a process group,
947 // since the directory is owned by root.
948 if (!is_system_server && getuid() == 0) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800949 const int rc = createProcessGroup(uid, getpid());
David Sehrde8d0bd2018-06-22 10:45:36 -0700950 if (rc != 0) {
951 if (rc == -EROFS) {
952 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
953 } else {
954 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
955 }
956 }
957 }
958
Chris Wailes8b35ba22019-01-10 16:55:32 -0800959 SetGids(env, gids, fail_fn);
960 SetRLimits(env, rlimits, fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700961
962 if (use_native_bridge) {
Chris Wailesefc65b22018-10-26 12:41:54 -0700963 // Due to the logic behind use_native_bridge we know that both app_data_dir
964 // and instruction_set contain values.
965 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
966 instruction_set.value().c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700967 }
968
Chris Wailesefc65b22018-10-26 12:41:54 -0700969 if (setresgid(gid, gid, gid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700970 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
971 }
972
Chris Wailesefc65b22018-10-26 12:41:54 -0700973 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
974 // before changing uid from 0, which clears capabilities. The other
975 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
976 // breaks SELinux domain transition (see b/71859146). As the result,
977 // privileged syscalls used below still need to be accessible in app process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700978 SetUpSeccompFilter(uid);
979
Chris Wailesefc65b22018-10-26 12:41:54 -0700980 if (setresuid(uid, uid, uid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700981 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
982 }
983
984 // The "dumpable" flag of a process, which controls core dump generation, is
985 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
986 // user or group ID changes. See proc(5) for possible values. In most cases,
987 // the value is 0, so core dumps are disabled for zygote children. However,
988 // when running in a Chrome OS container, the value is already set to 2,
989 // which allows the external crash reporter to collect all core dumps. Since
990 // only system crashes are interested, core dump is disabled for app
991 // processes. This also ensures compliance with CTS.
992 int dumpable = prctl(PR_GET_DUMPABLE);
993 if (dumpable == -1) {
994 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
995 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
996 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700997
David Sehrde8d0bd2018-06-22 10:45:36 -0700998 if (dumpable == 2 && uid >= AID_APP) {
999 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
1000 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1001 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1002 }
1003 }
1004
Orion Hodson8d005a62018-12-05 12:28:53 +00001005 // Set process properties to enable debugging if required.
1006 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1007 EnableDebugger();
1008 }
1009
David Sehrde8d0bd2018-06-22 10:45:36 -07001010 if (NeedsNoRandomizeWorkaround()) {
1011 // Work around ARM kernel ASLR lossage (http://b/5817320).
1012 int old_personality = personality(0xffffffff);
1013 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1014 if (new_personality == -1) {
1015 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1016 }
1017 }
1018
Chris Wailes8b35ba22019-01-10 16:55:32 -08001019 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -07001020
Chris Wailes8b35ba22019-01-10 16:55:32 -08001021 SetSchedulerPolicy(fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -07001022
Chris Wailesefc65b22018-10-26 12:41:54 -07001023 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1024 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1025
1026 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1027 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1028 uid, is_system_server, se_info_ptr, nice_name_ptr));
David Sehrde8d0bd2018-06-22 10:45:36 -07001029 }
1030
1031 // Make it easier to debug audit logs by setting the main thread's name to the
1032 // nice name rather than "app_process".
Chris Wailesefc65b22018-10-26 12:41:54 -07001033 if (nice_name.has_value()) {
Chris Wailes8b35ba22019-01-10 16:55:32 -08001034 SetThreadName(nice_name.value());
Chris Wailesefc65b22018-10-26 12:41:54 -07001035 } else if (is_system_server) {
1036 SetThreadName("system_server");
David Sehrde8d0bd2018-06-22 10:45:36 -07001037 }
David Sehrde8d0bd2018-06-22 10:45:36 -07001038
1039 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1040 UnsetChldSignalHandler();
1041
Orion Hodson46724e72018-10-19 13:05:33 +01001042 if (is_system_server) {
1043 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1044 if (env->ExceptionCheck()) {
1045 fail_fn("Error calling post fork system server hooks.");
1046 }
Chris Wailes8b35ba22019-01-10 16:55:32 -08001047
Orion Hodson46724e72018-10-19 13:05:33 +01001048 // TODO(oth): Remove hardcoded label here (b/117874058).
1049 static const char* kSystemServerLabel = "u:r:system_server:s0";
1050 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1051 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1052 }
1053 }
1054
David Sehrde8d0bd2018-06-22 10:45:36 -07001055 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
Chris Wailesefc65b22018-10-26 12:41:54 -07001056 is_system_server, is_child_zygote, managed_instruction_set);
1057
David Sehrde8d0bd2018-06-22 10:45:36 -07001058 if (env->ExceptionCheck()) {
1059 fail_fn("Error calling post fork hooks.");
1060 }
1061}
1062
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001063static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1064 __user_cap_header_struct capheader;
1065 memset(&capheader, 0, sizeof(capheader));
1066 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1067 capheader.pid = 0;
1068
1069 __user_cap_data_struct capdata[2];
1070 if (capget(&capheader, &capdata[0]) == -1) {
1071 ALOGE("capget failed: %s", strerror(errno));
1072 RuntimeAbort(env, __LINE__, "capget failed");
1073 }
1074
Chris Wailesefc65b22018-10-26 12:41:54 -07001075 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1076}
1077
1078static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1079 bool is_child_zygote) {
1080 jlong capabilities = 0;
1081
1082 /*
1083 * Grant the following capabilities to the Bluetooth user:
1084 * - CAP_WAKE_ALARM
1085 * - CAP_NET_RAW
1086 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1087 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1088 */
1089
1090 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1091 capabilities |= (1LL << CAP_WAKE_ALARM);
1092 capabilities |= (1LL << CAP_NET_RAW);
1093 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1094 capabilities |= (1LL << CAP_SYS_NICE);
1095 }
1096
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001097 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1098 capabilities |= (1LL << CAP_NET_ADMIN);
1099 capabilities |= (1LL << CAP_NET_BROADCAST);
1100 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1101 capabilities |= (1LL << CAP_NET_RAW);
1102 }
1103
Chris Wailesefc65b22018-10-26 12:41:54 -07001104 /*
1105 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1106 */
1107
1108 bool gid_wakelock_found = false;
1109 if (gid == AID_WAKELOCK) {
1110 gid_wakelock_found = true;
1111 } else if (gids != nullptr) {
1112 jsize gids_num = env->GetArrayLength(gids);
1113 ScopedIntArrayRO native_gid_proxy(env, gids);
1114
1115 if (native_gid_proxy.get() == nullptr) {
1116 RuntimeAbort(env, __LINE__, "Bad gids array");
1117 }
1118
1119 for (int gid_index = gids_num; --gids_num >= 0;) {
1120 if (native_gid_proxy[gid_index] == AID_WAKELOCK) {
1121 gid_wakelock_found = true;
1122 break;
1123 }
1124 }
1125 }
1126
1127 if (gid_wakelock_found) {
1128 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1129 }
1130
1131 /*
1132 * Grant child Zygote processes the following capabilities:
1133 * - CAP_SETUID (change UID of child processes)
1134 * - CAP_SETGID (change GID of child processes)
1135 * - CAP_SETPCAP (change capabilities of child processes)
1136 */
1137
1138 if (is_child_zygote) {
1139 capabilities |= (1LL << CAP_SETUID);
1140 capabilities |= (1LL << CAP_SETGID);
1141 capabilities |= (1LL << CAP_SETPCAP);
1142 }
1143
1144 /*
1145 * Containers run without some capabilities, so drop any caps that are not
1146 * available.
1147 */
1148
1149 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001150}
Chris Wailes8b35ba22019-01-10 16:55:32 -08001151
1152/**
1153 * Adds the given information about a newly created blastula to the Zygote's
1154 * blastula table.
1155 *
1156 * @param blastula_pid Process ID of the newly created blastula
1157 * @param read_pipe_fd File descriptor for the read end of the blastula
1158 * reporting pipe. Used in the ZygoteServer poll loop to track blastula
1159 * specialization.
1160 */
1161static void AddBlastulaTableEntry(pid_t blastula_pid, int read_pipe_fd) {
1162 static int sBlastulaTableInsertIndex = 0;
1163
1164 int search_index = sBlastulaTableInsertIndex;
1165
1166 do {
1167 if (gBlastulaTable[search_index].SetIfInvalid(blastula_pid, read_pipe_fd)) {
1168 // Start our next search right after where we finished this one.
1169 sBlastulaTableInsertIndex = (search_index + 1) % gBlastulaTable.size();
1170
1171 return;
1172 }
1173
1174 search_index = (search_index + 1) % gBlastulaTable.size();
1175 } while (search_index != sBlastulaTableInsertIndex);
1176
1177 // Much like money in the banana stand, there should always be an entry
1178 // in the blastula table.
1179 __builtin_unreachable();
1180}
1181
1182/**
1183 * Invalidates the entry in the BlastulaTable corresponding to the provided
1184 * process ID if it is present. If an entry was removed the blastula pool
1185 * count is decremented.
1186 *
1187 * @param blastula_pid Process ID of the blastula entry to invalidate
1188 * @return True if an entry was invalidated; false otherwise
1189 */
1190static bool RemoveBlastulaTableEntry(pid_t blastula_pid) {
1191 for (BlastulaTableEntry& entry : gBlastulaTable) {
1192 if (entry.ClearForPID(blastula_pid)) {
1193 --gBlastulaPoolCount;
1194 return true;
1195 }
1196 }
1197
1198 return false;
1199}
1200
1201/**
1202 * @return A vector of the read pipe FDs for each of the active blastulas.
1203 */
1204std::vector<int> MakeBlastulaPipeReadFDVector() {
1205 std::vector<int> fd_vec;
1206 fd_vec.reserve(gBlastulaTable.size());
1207
1208 for (BlastulaTableEntry& entry : gBlastulaTable) {
1209 auto entry_values = entry.GetValues();
1210
1211 if (entry_values.has_value()) {
1212 fd_vec.push_back(entry_values.value().read_pipe_fd);
1213 }
1214 }
1215
1216 return fd_vec;
1217}
1218
Narayan Kamath973b4662014-03-31 13:41:26 +01001219} // anonymous namespace
1220
1221namespace android {
1222
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001223static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesefc65b22018-10-26 12:41:54 -07001224 // security_getenforce is not allowed on app process. Initialize and cache
1225 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001226 g_is_security_enforced = security_getenforce();
1227}
1228
Christopher Ferris76de39e2017-06-20 16:13:40 -07001229static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1230 PreApplicationInit();
1231}
1232
Narayan Kamath973b4662014-03-31 13:41:26 +01001233static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1234 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001235 jint runtime_flags, jobjectArray rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -07001236 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailes8b35ba22019-01-10 16:55:32 -08001237 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Chris Wailesefc65b22018-10-26 12:41:54 -07001238 jstring instruction_set, jstring app_data_dir) {
1239 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001240
Chris Wailes8b35ba22019-01-10 16:55:32 -08001241 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1242 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1243 }
1244
1245 std::vector<int> fds_to_close =
1246 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1247 std::vector<int> fds_to_ignore =
1248 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1249 .value_or(std::vector<int>());
1250
1251 std::vector<int> blastula_pipes = MakeBlastulaPipeReadFDVector();
1252
1253 fds_to_close.insert(fds_to_close.end(), blastula_pipes.begin(), blastula_pipes.end());
1254 fds_to_ignore.insert(fds_to_ignore.end(), blastula_pipes.begin(), blastula_pipes.end());
1255
Chris Wailescffbf1c2019-01-11 17:13:00 -08001256 fds_to_close.push_back(gBlastulaPoolSocketFD);
Chris Wailes8b35ba22019-01-10 16:55:32 -08001257
1258 if (gBlastulaPoolEventFD != -1) {
1259 fds_to_close.push_back(gBlastulaPoolEventFD);
1260 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1261 }
1262
Chris Wailesefc65b22018-10-26 12:41:54 -07001263 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
Chris Wailes8b35ba22019-01-10 16:55:32 -08001264
David Sehrde8d0bd2018-06-22 10:45:36 -07001265 if (pid == 0) {
1266 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1267 capabilities, capabilities,
Chris Wailesefc65b22018-10-26 12:41:54 -07001268 mount_external, se_info, nice_name, false,
1269 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
David Sehrde8d0bd2018-06-22 10:45:36 -07001270 }
1271 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001272}
1273
1274static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1275 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesefc65b22018-10-26 12:41:54 -07001276 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1277 jlong effective_capabilities) {
Chris Wailes8b35ba22019-01-10 16:55:32 -08001278 std::vector<int> fds_to_close(MakeBlastulaPipeReadFDVector()),
1279 fds_to_ignore(fds_to_close);
1280
Chris Wailescffbf1c2019-01-11 17:13:00 -08001281 fds_to_close.push_back(gBlastulaPoolSocketFD);
Chris Wailes8b35ba22019-01-10 16:55:32 -08001282
1283 if (gBlastulaPoolEventFD != -1) {
1284 fds_to_close.push_back(gBlastulaPoolEventFD);
1285 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1286 }
1287
Chris Wailesefc65b22018-10-26 12:41:54 -07001288 pid_t pid = ForkCommon(env, true,
Chris Wailes8b35ba22019-01-10 16:55:32 -08001289 fds_to_close,
1290 fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001291 if (pid == 0) {
1292 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -07001293 permitted_capabilities, effective_capabilities,
1294 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1295 false, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001296 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001297 // The zygote process checks whether the child process has died or not.
1298 ALOGI("System server process %d has been created", pid);
1299 gSystemServerPid = pid;
1300 // There is a slight window that the system server process has crashed
1301 // but it went unnoticed because we haven't published its pid yet. So
1302 // we recheck here just to make sure that all is well.
1303 int status;
1304 if (waitpid(pid, &status, WNOHANG) == pid) {
1305 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001306 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001307 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001308
Suren Baghdasaryan9c9b0252018-12-14 10:32:22 -08001309 if (UsePerAppMemcg()) {
Minchan Kim696873e2018-06-27 11:32:40 +09001310 // Assign system_server to the correct memory cgroup.
Suren Baghdasaryan9c9b0252018-12-14 10:32:22 -08001311 // Not all devices mount memcg so check if it is mounted first
Minchan Kim696873e2018-06-27 11:32:40 +09001312 // to avoid unnecessarily printing errors and denials in the logs.
Suren Baghdasaryan9c9b0252018-12-14 10:32:22 -08001313 if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
1314 ALOGE("couldn't add process %d into system memcg group", pid);
Minchan Kim696873e2018-06-27 11:32:40 +09001315 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001316 }
Narayan Kamath973b4662014-03-31 13:41:26 +01001317 }
1318 return pid;
1319}
1320
Chris Wailes8b35ba22019-01-10 16:55:32 -08001321/**
1322 * A JNI function that forks a blastula from the Zygote while ensuring proper
1323 * file descriptor hygiene.
1324 *
1325 * @param env Managed runtime environment
1326 * @param read_pipe_fd The read FD for the blastula reporting pipe. Manually closed by blastlas
1327 * in managed code.
1328 * @param write_pipe_fd The write FD for the blastula reporting pipe. Manually closed by the
1329 * zygote in managed code.
1330 * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by
1331 * the FD hygiene code and automatically "closed" in the new blastula.
1332 * @return
1333 */
1334static jint com_android_internal_os_Zygote_nativeForkBlastula(JNIEnv* env, jclass,
1335 jint read_pipe_fd, jint write_pipe_fd, jintArray managed_session_socket_fds) {
1336 std::vector<int> fds_to_close(MakeBlastulaPipeReadFDVector()),
1337 fds_to_ignore(fds_to_close);
1338
1339 std::vector<int> session_socket_fds =
1340 ExtractJIntArray(env, "blastula", nullptr, managed_session_socket_fds)
1341 .value_or(std::vector<int>());
1342
1343 // The Blastula Pool Event FD is created during the initialization of the
1344 // blastula pool and should always be valid here.
1345
1346 fds_to_close.push_back(gZygoteSocketFD);
1347 fds_to_close.push_back(gBlastulaPoolEventFD);
1348 fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end());
1349
1350 fds_to_ignore.push_back(gZygoteSocketFD);
1351 fds_to_ignore.push_back(gBlastulaPoolSocketFD);
1352 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1353 fds_to_ignore.push_back(read_pipe_fd);
1354 fds_to_ignore.push_back(write_pipe_fd);
1355 fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end());
1356
1357 pid_t blastula_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore);
1358
1359 if (blastula_pid != 0) {
1360 ++gBlastulaPoolCount;
1361 AddBlastulaTableEntry(blastula_pid, read_pipe_fd);
1362 }
1363
1364 return blastula_pid;
1365}
1366
Robert Sesek54e387d2016-12-02 17:27:50 -05001367static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork(
1368 JNIEnv* env, jclass, jstring path) {
1369 ScopedUtfChars path_native(env, path);
1370 const char* path_cstr = path_native.c_str();
1371 if (!path_cstr) {
Chris Wailesefc65b22018-10-26 12:41:54 -07001372 RuntimeAbort(env, __LINE__, "path_cstr == nullptr");
Robert Sesek54e387d2016-12-02 17:27:50 -05001373 }
1374 FileDescriptorWhitelist::Get()->Allow(path_cstr);
1375}
1376
doheon1.lee885b7422016-01-20 13:07:27 +09001377static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) {
1378 // Zygote process unmount root storage space initially before every child processes are forked.
1379 // Every forked child processes (include SystemServer) only mount their own root storage space
Robert Seseke4f8d692016-09-13 19:13:01 -04001380 // and no need unmount storage operation in MountEmulatedStorage method.
1381 // Zygote process does not utilize root storage spaces and unshares its mount namespace below.
1382
1383 // See storage config details at http://source.android.com/tech/storage/
1384 // Create private mount namespace shared by all children
1385 if (unshare(CLONE_NEWNS) == -1) {
1386 RuntimeAbort(env, __LINE__, "Failed to unshare()");
1387 return;
1388 }
1389
1390 // Mark rootfs as being a slave so that changes from default
1391 // namespace only flow into our children.
1392 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
1393 RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE");
1394 return;
1395 }
1396
1397 // Create a staging tmpfs that is shared by our children; they will
1398 // bind mount storage into their respective private namespaces, which
1399 // are isolated from each other.
1400 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
1401 if (target_base != nullptr) {
1402#define STRINGIFY_UID(x) __STRING(x)
1403 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
1404 "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) {
1405 ALOGE("Failed to mount tmpfs to %s", target_base);
1406 RuntimeAbort(env, __LINE__, "Failed to mount tmpfs");
1407 return;
1408 }
1409#undef STRINGIFY_UID
1410 }
doheon1.lee885b7422016-01-20 13:07:27 +09001411
1412 UnmountTree("/storage");
doheon1.lee885b7422016-01-20 13:07:27 +09001413}
1414
Chris Wailes8b35ba22019-01-10 16:55:32 -08001415/**
1416 * Called from a blastula to specialize the process for a specific application.
1417 *
1418 * @param env Managed runtime environment
1419 * @param uid User ID of the new application
1420 * @param gid Group ID of the new application
1421 * @param gids Extra groups that the process belongs to
1422 * @param runtime_flags Flags for changing the behavior of the managed runtime
1423 * @param rlimits Resource limits
1424 * @param mount_external The mode (read/write/normal) that external storage will be mounted with
1425 * @param se_info SELinux policy information
1426 * @param nice_name New name for this process
1427 * @param is_child_zygote If the process is to become a WebViewZygote
1428 * @param instruction_set The instruction set expected/requested by the new application
1429 * @param app_data_dir Path to the application's data directory
1430 */
1431static void com_android_internal_os_Zygote_nativeSpecializeBlastula(
1432 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
1433 jint runtime_flags, jobjectArray rlimits,
1434 jint mount_external, jstring se_info, jstring nice_name,
1435 jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
1436 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
1437
1438 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1439 capabilities, capabilities,
1440 mount_external, se_info, nice_name, false,
1441 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
1442}
1443
1444/**
1445 * A helper method for fetching socket file descriptors that were opened by init from the
1446 * environment.
1447 *
1448 * @param env Managed runtime environment
1449 * @param is_primary If this process is the primary or secondary Zygote; used to compute the name
1450 * of the environment variable storing the file descriptors.
1451 */
1452static void com_android_internal_os_Zygote_nativeGetSocketFDs(JNIEnv* env, jclass,
1453 jboolean is_primary) {
1454 std::string android_socket_prefix(ANDROID_SOCKET_PREFIX);
1455 std::string env_var_name = android_socket_prefix + (is_primary ? "zygote" : "zygote_secondary");
1456 char* env_var_val = getenv(env_var_name.c_str());
1457
1458 if (env_var_val != nullptr) {
1459 gZygoteSocketFD = atoi(env_var_val);
1460 ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD);
1461 } else {
1462 ALOGE("Unable to fetch Zygote socket file descriptor");
1463 }
1464
1465 env_var_name = android_socket_prefix + (is_primary ? "blastula_pool" : "blastula_pool_secondary");
1466 env_var_val = getenv(env_var_name.c_str());
1467
1468 if (env_var_val != nullptr) {
1469 gBlastulaPoolSocketFD = atoi(env_var_val);
1470 ALOGV("Zygote:blastulaPoolSocketFD = %d", gBlastulaPoolSocketFD);
1471 } else {
1472 ALOGE("Unable to fetch Blastula pool socket file descriptor");
1473 }
1474}
1475
1476/**
1477 * @param env Managed runtime environment
1478 * @return A managed array of raw file descriptors for the read ends of the blastula reporting
1479 * pipes.
1480 */
1481static jintArray com_android_internal_os_Zygote_nativeGetBlastulaPipeFDs(JNIEnv* env, jclass) {
1482 std::vector<int> blastula_fds = MakeBlastulaPipeReadFDVector();
1483
1484 jintArray managed_blastula_fds = env->NewIntArray(blastula_fds.size());
1485 env->SetIntArrayRegion(managed_blastula_fds, 0, blastula_fds.size(), blastula_fds.data());
1486
1487 return managed_blastula_fds;
1488}
1489
1490/**
1491 * A JNI wrapper around RemoveBlastulaTableEntry.
1492 *
1493 * @param env Managed runtime environment
1494 * @param blastula_pid Process ID of the blastula entry to invalidate
1495 * @return True if an entry was invalidated; false otherwise.
1496 */
1497static jboolean com_android_internal_os_Zygote_nativeRemoveBlastulaTableEntry(JNIEnv* env, jclass,
1498 jint blastula_pid) {
1499 return RemoveBlastulaTableEntry(blastula_pid);
1500}
1501
1502/**
1503 * Creates the blastula pool event FD if it doesn't exist and returns it. This is used by the
1504 * ZygoteServer poll loop to know when to re-fill the blastula pool.
1505 *
1506 * @param env Managed runtime environment
1507 * @return A raw event file descriptor used to communicate (from the signal handler) when the
1508 * Zygote receives a SIGCHLD for a blastula
1509 */
1510static jint com_android_internal_os_Zygote_nativeGetBlastulaPoolEventFD(JNIEnv* env, jclass) {
1511 if (gBlastulaPoolEventFD == -1) {
1512 if ((gBlastulaPoolEventFD = eventfd(0, 0)) == -1) {
1513 ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno)));
1514 }
1515 }
1516
1517 return gBlastulaPoolEventFD;
1518}
1519
1520/**
1521 * @param env Managed runtime environment
1522 * @return The number of blastulas currently in the blastula pool
1523 */
1524static jint com_android_internal_os_Zygote_nativeGetBlastulaPoolCount(JNIEnv* env, jclass) {
1525 return gBlastulaPoolCount;
1526}
1527
Daniel Micay76f6a862015-09-19 17:31:01 -04001528static const JNINativeMethod gMethods[] = {
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001529 { "nativeSecurityInit", "()V",
1530 (void *) com_android_internal_os_Zygote_nativeSecurityInit },
Andreas Gampeaec67dc2014-09-02 21:23:06 -07001531 { "nativeForkAndSpecialize",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001532 "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
Narayan Kamath973b4662014-03-31 13:41:26 +01001533 (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
1534 { "nativeForkSystemServer", "(II[II[[IJJ)I",
doheon1.lee885b7422016-01-20 13:07:27 +09001535 (void *) com_android_internal_os_Zygote_nativeForkSystemServer },
Robert Sesek54e387d2016-12-02 17:27:50 -05001536 { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V",
1537 (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork },
doheon1.lee885b7422016-01-20 13:07:27 +09001538 { "nativeUnmountStorageOnInit", "()V",
Christopher Ferris76de39e2017-06-20 16:13:40 -07001539 (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit },
1540 { "nativePreApplicationInit", "()V",
Chris Wailes8b35ba22019-01-10 16:55:32 -08001541 (void *) com_android_internal_os_Zygote_nativePreApplicationInit },
1542 { "nativeForkBlastula", "(II[I)I",
1543 (void *) com_android_internal_os_Zygote_nativeForkBlastula },
1544 { "nativeSpecializeBlastula",
1545 "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V",
1546 (void *) com_android_internal_os_Zygote_nativeSpecializeBlastula },
1547 { "nativeGetSocketFDs", "(Z)V",
1548 (void *) com_android_internal_os_Zygote_nativeGetSocketFDs },
1549 { "nativeGetBlastulaPipeFDs", "()[I",
1550 (void *) com_android_internal_os_Zygote_nativeGetBlastulaPipeFDs },
1551 { "nativeRemoveBlastulaTableEntry", "(I)Z",
1552 (void *) com_android_internal_os_Zygote_nativeRemoveBlastulaTableEntry },
1553 { "nativeGetBlastulaPoolEventFD", "()I",
1554 (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolEventFD },
1555 { "nativeGetBlastulaPoolCount", "()I",
1556 (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolCount }
Narayan Kamath973b4662014-03-31 13:41:26 +01001557};
1558
1559int register_com_android_internal_os_Zygote(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001560 gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName));
Orion Hodson46724e72018-10-19 13:05:33 +01001561 gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass,
1562 "callPostForkSystemServerHooks",
1563 "()V");
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001564 gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
Robert Sesekd0a190df2018-02-12 18:46:01 -05001565 "(IZZLjava/lang/String;)V");
Narayan Kamath973b4662014-03-31 13:41:26 +01001566
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001567 return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
Narayan Kamath973b4662014-03-31 13:41:26 +01001568}
1569} // namespace android