blob: 1448d7b97eb1a0777deb34b835b51a237cb41bc9 [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
28// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
29#include <sys/mount.h>
30#include <linux/fs.h>
31
Chris Wailes8b35ba22019-01-10 16:55:32 -080032#include <array>
33#include <atomic>
Chris Wailesefc65b22018-10-26 12:41:54 -070034#include <functional>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070035#include <list>
Chris Wailesefc65b22018-10-26 12:41:54 -070036#include <optional>
Andreas Gampeb053cce2015-11-17 16:38:59 -080037#include <sstream>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070038#include <string>
Chris Wailes8b35ba22019-01-10 16:55:32 -080039#include <string_view>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070040
Josh Gaod7951102018-06-26 16:05:12 -070041#include <android/fdsan.h>
Chris Wailes8b35ba22019-01-10 16:55:32 -080042#include <arpa/inet.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070043#include <fcntl.h>
Dan Albert46d84442014-11-18 16:07:51 -080044#include <grp.h>
45#include <inttypes.h>
Christopher Ferrisab16dd12017-05-15 16:50:29 -070046#include <malloc.h>
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -070047#include <mntent.h>
Narayan Kamath973b4662014-03-31 13:41:26 +010048#include <paths.h>
49#include <signal.h>
50#include <stdlib.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070051#include <sys/capability.h>
Robert Seseke4f8d692016-09-13 19:13:01 -040052#include <sys/cdefs.h>
Chris Wailes8b35ba22019-01-10 16:55:32 -080053#include <sys/eventfd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070054#include <sys/personality.h>
55#include <sys/prctl.h>
56#include <sys/resource.h>
Chris Wailes8b35ba22019-01-10 16:55:32 -080057#include <sys/socket.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070058#include <sys/stat.h>
Vitalii Tomkiv5cbce852016-05-18 17:43:02 -070059#include <sys/time.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070060#include <sys/types.h>
61#include <sys/utsname.h>
62#include <sys/wait.h>
Dan Albert46d84442014-11-18 16:07:51 -080063#include <unistd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070064
Chris Wailes8b35ba22019-01-10 16:55:32 -080065#include <android-base/logging.h>
Minchan Kim696873e2018-06-27 11:32:40 +090066#include <android-base/properties.h>
Carmen Jacksondd401252017-02-23 15:21:10 -080067#include <android-base/file.h>
68#include <android-base/stringprintf.h>
Chris Wailes8b35ba22019-01-10 16:55:32 -080069#include <android-base/unique_fd.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070070#include <cutils/fs.h>
71#include <cutils/multiuser.h>
Sharvil Nanavati4990e4f2014-06-29 17:06:52 -070072#include <private/android_filesystem_config.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070073#include <utils/String8.h>
74#include <selinux/android.h>
Victor Hsiehc8176ef2018-01-08 12:43:00 -080075#include <seccomp_policy.h>
Howard Ro65e48ec2018-10-02 12:08:28 -070076#include <stats_event_list.h>
Colin Cross0161bbc2014-06-03 13:26:58 -070077#include <processgroup/processgroup.h>
Suren Baghdasaryan5d445ad2019-01-25 05:23:40 +000078#include <processgroup/sched_policy.h>
Colin Cross18cd9f52014-06-13 12:58:55 -070079
Andreas Gampeed6b9df2014-11-20 22:02:20 -080080#include "core_jni_helpers.h"
Steven Moreland2279b252017-07-19 09:50:45 -070081#include <nativehelper/JNIHelp.h>
82#include <nativehelper/ScopedLocalRef.h>
83#include <nativehelper/ScopedPrimitiveArray.h>
84#include <nativehelper/ScopedUtfChars.h>
Robert Sesek8225b7c2016-12-16 14:02:31 -050085#include "fd_utils.h"
Narayan Kamath973b4662014-03-31 13:41:26 +010086
jgu212eacd062014-09-10 06:55:07 -040087#include "nativebridge/native_bridge.h"
88
Narayan Kamath973b4662014-03-31 13:41:26 +010089namespace {
90
Chris Wailes8b35ba22019-01-10 16:55:32 -080091// TODO (chriswailes): Add a function to initialize native Zygote data.
92// TODO (chriswailes): Fix mixed indentation style (2 and 4 spaces).
93
Chris Wailesefc65b22018-10-26 12:41:54 -070094using namespace std::placeholders;
95
Narayan Kamath973b4662014-03-31 13:41:26 +010096using android::String8;
Carmen Jacksondd401252017-02-23 15:21:10 -080097using android::base::StringPrintf;
98using android::base::WriteStringToFile;
Minchan Kim696873e2018-06-27 11:32:40 +090099using android::base::GetBoolProperty;
Narayan Kamath973b4662014-03-31 13:41:26 +0100100
Andreas Gamped5758f62018-03-12 12:08:55 -0700101#define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \
102 append(StringPrintf(__VA_ARGS__))
103
Chris Wailes8b35ba22019-01-10 16:55:32 -0800104// This type is duplicated in fd_utils.h
105typedef const std::function<void(std::string)>& fail_fn_t;
106
Narayan Kamath973b4662014-03-31 13:41:26 +0100107static pid_t gSystemServerPid = 0;
108
109static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
110static jclass gZygoteClass;
Orion Hodson46724e72018-10-19 13:05:33 +0100111static jmethodID gCallPostForkSystemServerHooks;
Narayan Kamath973b4662014-03-31 13:41:26 +0100112static jmethodID gCallPostForkChildHooks;
113
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800114static bool g_is_security_enforced = true;
115
Chris Wailes8b35ba22019-01-10 16:55:32 -0800116/**
117 * The maximum number of characters (not including a null terminator) that a
118 * process name may contain.
119 */
120static constexpr size_t MAX_NAME_LENGTH = 15;
121
122/**
123 * The prefix string for environmental variables storing socket FDs created by
124 * init.
125 */
126
127static constexpr std::string_view ANDROID_SOCKET_PREFIX("ANDROID_SOCKET_");
128
129/**
130 * The file descriptor for the Zygote socket opened by init.
131 */
132
133static int gZygoteSocketFD = -1;
134
135/**
136 * The file descriptor for the Blastula pool socket opened by init.
137 */
138
139static int gBlastulaPoolSocketFD = -1;
140
141/**
142 * The number of Blastulas currently in this Zygote's pool.
143 */
144static std::atomic_uint32_t gBlastulaPoolCount = 0;
145
146/**
147 * Event file descriptor used to communicate reaped blastulas to the
148 * ZygoteServer.
149 */
150static int gBlastulaPoolEventFD = -1;
151
152/**
153 * The maximum value that the gBlastulaPoolMax variable may take. This value
154 * is a mirror of Zygote.BLASTULA_POOL_MAX_LIMIT
155 */
156static constexpr int BLASTULA_POOL_MAX_LIMIT = 10;
157
158/**
159 * A helper class containing accounting information for Blastulas.
160 */
161class BlastulaTableEntry {
162 public:
163 struct EntryStorage {
164 int32_t pid;
165 int32_t read_pipe_fd;
166
167 bool operator!=(const EntryStorage& other) {
168 return pid != other.pid || read_pipe_fd != other.read_pipe_fd;
169 }
170 };
171
172 private:
173 static constexpr EntryStorage INVALID_ENTRY_VALUE = {-1, -1};
174
175 std::atomic<EntryStorage> mStorage;
176 static_assert(decltype(mStorage)::is_always_lock_free);
177
178 public:
179 constexpr BlastulaTableEntry() : mStorage(INVALID_ENTRY_VALUE) {}
180
181 /**
182 * If the provided PID matches the one stored in this entry, the entry will
183 * be invalidated and the associated file descriptor will be closed. If the
184 * PIDs don't match nothing will happen.
185 *
186 * @param pid The ID of the process who's entry we want to clear.
187 * @return True if the entry was cleared; false otherwise
188 */
189 bool ClearForPID(int32_t pid) {
190 EntryStorage storage = mStorage.load();
191
192 if (storage.pid == pid) {
193 /*
194 * There are three possible outcomes from this compare-and-exchange:
195 * 1) It succeeds, in which case we close the FD
196 * 2) It fails and the new value is INVALID_ENTRY_VALUE, in which case
197 * the entry has already been cleared.
198 * 3) It fails and the new value isn't INVALID_ENTRY_VALUE, in which
199 * case the entry has already been cleared and re-used.
200 *
201 * In all three cases the goal of the caller has been met and we can
202 * return true.
203 */
204 if (mStorage.compare_exchange_strong(storage, INVALID_ENTRY_VALUE)) {
205 close(storage.read_pipe_fd);
206 }
207
208 return true;
209 } else {
210 return false;
211 }
212 }
213
214 /**
215 * @return A copy of the data stored in this entry.
216 */
217 std::optional<EntryStorage> GetValues() {
218 EntryStorage storage = mStorage.load();
219
220 if (storage != INVALID_ENTRY_VALUE) {
221 return storage;
222 } else {
223 return std::nullopt;
224 }
225 }
226
227 /**
228 * Sets the entry to the given values if it is currently invalid.
229 *
230 * @param pid The process ID for the new entry.
231 * @param read_pipe_fd The read end of the blastula control pipe for this
232 * process.
233 * @return True if the entry was set; false otherwise.
234 */
235 bool SetIfInvalid(int32_t pid, int32_t read_pipe_fd) {
236 EntryStorage new_value_storage;
237
238 new_value_storage.pid = pid;
239 new_value_storage.read_pipe_fd = read_pipe_fd;
240
241 EntryStorage expected = INVALID_ENTRY_VALUE;
242
243 return mStorage.compare_exchange_strong(expected, new_value_storage);
244 }
245};
246
247/**
248 * A table containing information about the Blastulas currently in the pool.
249 *
250 * Multiple threads may be attempting to modify the table, either from the
251 * signal handler or from the ZygoteServer poll loop. Atomic loads/stores in
252 * the BlastulaTableEntry class prevent data races during these concurrent
253 * operations.
254 */
255static std::array<BlastulaTableEntry, BLASTULA_POOL_MAX_LIMIT> gBlastulaTable;
256
257/**
258 * The list of open zygote file descriptors.
259 */
260static FileDescriptorTable* gOpenFdTable = nullptr;
261
Narayan Kamath973b4662014-03-31 13:41:26 +0100262// Must match values in com.android.internal.os.Zygote.
263enum MountExternalKind {
264 MOUNT_EXTERNAL_NONE = 0,
Jeff Sharkey48877892015-03-18 11:27:19 -0700265 MOUNT_EXTERNAL_DEFAULT = 1,
Jeff Sharkey9527b222015-06-24 15:24:48 -0700266 MOUNT_EXTERNAL_READ = 2,
267 MOUNT_EXTERNAL_WRITE = 3,
Narayan Kamath973b4662014-03-31 13:41:26 +0100268};
269
Orion Hodson8d005a62018-12-05 12:28:53 +0000270// Must match values in com.android.internal.os.Zygote.
271enum RuntimeFlags : uint32_t {
272 DEBUG_ENABLE_JDWP = 1,
273};
274
Chris Wailes8b35ba22019-01-10 16:55:32 -0800275// Forward declaration so we don't have to move the signal handler.
276static bool RemoveBlastulaTableEntry(pid_t blastula_pid);
277
Andreas Gampeb053cce2015-11-17 16:38:59 -0800278static void RuntimeAbort(JNIEnv* env, int line, const char* msg) {
279 std::ostringstream oss;
280 oss << __FILE__ << ":" << line << ": " << msg;
281 env->FatalError(oss.str().c_str());
Narayan Kamath973b4662014-03-31 13:41:26 +0100282}
283
284// This signal handler is for zygote mode, since the zygote must reap its children
285static void SigChldHandler(int /*signal_number*/) {
286 pid_t pid;
287 int status;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800288 int64_t blastulas_removed = 0;
Narayan Kamath973b4662014-03-31 13:41:26 +0100289
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700290 // It's necessary to save and restore the errno during this function.
291 // Since errno is stored per thread, changing it here modifies the errno
292 // on the thread on which this signal handler executes. If a signal occurs
293 // between a call and an errno check, it's possible to get the errno set
294 // here.
295 // See b/23572286 for extra information.
296 int saved_errno = errno;
297
Narayan Kamath973b4662014-03-31 13:41:26 +0100298 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
299 // Log process-death status that we care about. In general it is
300 // not safe to call LOG(...) from a signal handler because of
301 // possible reentrancy. However, we know a priori that the
302 // current implementation of LOG() is safe to call from a SIGCHLD
303 // handler in the zygote process. If the LOG() implementation
304 // changes its locking strategy or its use of syscalls within the
305 // lazy-init critical section, its use here may become unsafe.
306 if (WIFEXITED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700307 ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100308 } else if (WIFSIGNALED(status)) {
Josh Gao6d747ca2017-08-02 12:54:05 -0700309 ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
Narayan Kamath973b4662014-03-31 13:41:26 +0100310 if (WCOREDUMP(status)) {
311 ALOGI("Process %d dumped core.", pid);
312 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100313 }
314
315 // If the just-crashed process is the system_server, bring down zygote
316 // so that it is restarted by init and system server will be restarted
317 // from there.
318 if (pid == gSystemServerPid) {
Dan Albert46d84442014-11-18 16:07:51 -0800319 ALOGE("Exit zygote because system server (%d) has terminated", pid);
Narayan Kamath973b4662014-03-31 13:41:26 +0100320 kill(getpid(), SIGKILL);
321 }
Chris Wailes8b35ba22019-01-10 16:55:32 -0800322
323 // Check to see if the PID is in the blastula pool and remove it if it is.
324 if (RemoveBlastulaTableEntry(pid)) {
325 ++blastulas_removed;
326 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100327 }
328
Narayan Kamath160992d2014-04-14 14:46:07 +0100329 // Note that we shouldn't consider ECHILD an error because
330 // the secondary zygote might have no children left to wait for.
331 if (pid < 0 && errno != ECHILD) {
332 ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100333 }
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700334
Chris Wailes8b35ba22019-01-10 16:55:32 -0800335 if (blastulas_removed > 0) {
336 if (write(gBlastulaPoolEventFD, &blastulas_removed, sizeof(blastulas_removed)) == -1) {
337 // If this write fails something went terribly wrong. We will now kill
338 // the zygote and let the system bring it back up.
339 ALOGE("Zygote failed to write to blastula pool event FD: %s", strerror(errno));
340 kill(getpid(), SIGKILL);
341 }
342 }
343
Christopher Ferrisa8a79542015-08-31 15:40:01 -0700344 errno = saved_errno;
Narayan Kamath973b4662014-03-31 13:41:26 +0100345}
346
yuanhao435e84b2018-01-15 15:37:02 +0800347// Configures the SIGCHLD/SIGHUP handlers for the zygote process. This is
348// configured very late, because earlier in the runtime we may fork() and
349// exec() other processes, and we want to waitpid() for those rather than
Narayan Kamath973b4662014-03-31 13:41:26 +0100350// have them be harvested immediately.
351//
yuanhao435e84b2018-01-15 15:37:02 +0800352// Ignore SIGHUP because all processes forked by the zygote are in the same
353// process group as the zygote and we don't want to be notified if we become
354// an orphaned group and have one or more stopped processes. This is not a
355// theoretical concern :
356// - we can become an orphaned group if one of our direct descendants forks
357// and is subsequently killed before its children.
358// - crash_dump routinely STOPs the process it's tracing.
359//
360// See issues b/71965619 and b/25567761 for further details.
361//
Narayan Kamath973b4662014-03-31 13:41:26 +0100362// This ends up being called repeatedly before each fork(), but there's
363// no real harm in that.
yuanhao435e84b2018-01-15 15:37:02 +0800364static void SetSignalHandlers() {
365 struct sigaction sig_chld = {};
366 sig_chld.sa_handler = SigChldHandler;
Narayan Kamath973b4662014-03-31 13:41:26 +0100367
Chris Wailes8b35ba22019-01-10 16:55:32 -0800368 if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700369 ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100370 }
yuanhao435e84b2018-01-15 15:37:02 +0800371
372 struct sigaction sig_hup = {};
373 sig_hup.sa_handler = SIG_IGN;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800374 if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
yuanhao435e84b2018-01-15 15:37:02 +0800375 ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
376 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100377}
378
379// Sets the SIGCHLD handler back to default behavior in zygote children.
yuanhao435e84b2018-01-15 15:37:02 +0800380static void UnsetChldSignalHandler() {
Narayan Kamath973b4662014-03-31 13:41:26 +0100381 struct sigaction sa;
382 memset(&sa, 0, sizeof(sa));
383 sa.sa_handler = SIG_DFL;
384
Chris Wailes8b35ba22019-01-10 16:55:32 -0800385 if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700386 ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100387 }
388}
389
390// Calls POSIX setgroups() using the int[] object as an argument.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800391// A nullptr argument is tolerated.
392static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) {
393 if (managed_gids == nullptr) {
394 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100395 }
396
Chris Wailes8b35ba22019-01-10 16:55:32 -0800397 ScopedIntArrayRO gids(env, managed_gids);
398 if (gids.get() == nullptr) {
399 fail_fn(CREATE_ERROR("Getting gids int array failed"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100400 }
Andreas Gamped5758f62018-03-12 12:08:55 -0700401
Chris Wailes8b35ba22019-01-10 16:55:32 -0800402 if (setgroups(gids.size(), reinterpret_cast<const gid_t*>(&gids[0])) == -1) {
403 fail_fn(CREATE_ERROR("setgroups failed: %s, gids.size=%zu", strerror(errno), gids.size()));
404 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100405}
406
407// Sets the resource limits via setrlimit(2) for the values in the
408// two-dimensional array of integers that's passed in. The second dimension
Chris Wailes8b35ba22019-01-10 16:55:32 -0800409// contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
Narayan Kamath973b4662014-03-31 13:41:26 +0100410// treated as an empty array.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800411static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) {
412 if (managed_rlimits == nullptr) {
413 return;
Narayan Kamath973b4662014-03-31 13:41:26 +0100414 }
415
416 rlimit rlim;
417 memset(&rlim, 0, sizeof(rlim));
418
Chris Wailes8b35ba22019-01-10 16:55:32 -0800419 for (int i = 0; i < env->GetArrayLength(managed_rlimits); ++i) {
420 ScopedLocalRef<jobject>
421 managed_rlimit_object(env, env->GetObjectArrayElement(managed_rlimits, i));
422 ScopedIntArrayRO rlimit_handle(env, reinterpret_cast<jintArray>(managed_rlimit_object.get()));
423
424 if (rlimit_handle.size() != 3) {
425 fail_fn(CREATE_ERROR("rlimits array must have a second dimension of size 3"));
Narayan Kamath973b4662014-03-31 13:41:26 +0100426 }
427
Chris Wailes8b35ba22019-01-10 16:55:32 -0800428 rlim.rlim_cur = rlimit_handle[1];
429 rlim.rlim_max = rlimit_handle[2];
Narayan Kamath973b4662014-03-31 13:41:26 +0100430
Chris Wailes8b35ba22019-01-10 16:55:32 -0800431 if (setrlimit(rlimit_handle[0], &rlim) == -1) {
432 fail_fn(CREATE_ERROR("setrlimit(%d, {%ld, %ld}) failed",
433 rlimit_handle[0], rlim.rlim_cur, rlim.rlim_max));
Narayan Kamath973b4662014-03-31 13:41:26 +0100434 }
435 }
436}
437
Orion Hodson8d005a62018-12-05 12:28:53 +0000438static void EnableDebugger() {
439 // To let a non-privileged gdbserver attach to this
440 // process, we must set our dumpable flag.
441 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
442 ALOGE("prctl(PR_SET_DUMPABLE) failed");
443 }
444
445 // A non-privileged native debugger should be able to attach to the debuggable app, even if Yama
446 // is enabled (see kernel/Documentation/security/Yama.txt).
447 if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0) == -1) {
448 // if Yama is off prctl(PR_SET_PTRACER) returns EINVAL - don't log in this
449 // case since it's expected behaviour.
450 if (errno != EINVAL) {
451 ALOGE("prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) failed");
452 }
453 }
454
Orion Hodson2b71ad02018-12-07 16:44:33 +0000455 // Set the core dump size to zero unless wanted (see also coredump_setup in build/envsetup.sh).
456 if (!GetBoolProperty("persist.zygote.core_dump", false)) {
457 // Set the soft limit on core dump size to 0 without changing the hard limit.
458 rlimit rl;
459 if (getrlimit(RLIMIT_CORE, &rl) == -1) {
460 ALOGE("getrlimit(RLIMIT_CORE) failed");
461 } else {
462 rl.rlim_cur = 0;
463 if (setrlimit(RLIMIT_CORE, &rl) == -1) {
464 ALOGE("setrlimit(RLIMIT_CORE) failed");
465 }
Orion Hodson8d005a62018-12-05 12:28:53 +0000466 }
467 }
468}
469
Narayan Kamath973b4662014-03-31 13:41:26 +0100470// The debug malloc library needs to know whether it's the zygote or a child.
471extern "C" int gMallocLeakZygoteChild;
472
Christopher Ferris76de39e2017-06-20 16:13:40 -0700473static void PreApplicationInit() {
474 // The child process sets this to indicate it's not the zygote.
475 gMallocLeakZygoteChild = 1;
476
477 // Set the jemalloc decay time to 1.
478 mallopt(M_DECAY_TIME, 1);
479}
480
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800481static void SetUpSeccompFilter(uid_t uid) {
482 if (!g_is_security_enforced) {
483 ALOGI("seccomp disabled by setenforce 0");
484 return;
485 }
486
487 // Apply system or app filter based on uid.
Victor Hsiehfa046a12018-03-28 16:26:28 -0700488 if (uid >= AID_APP_START) {
Victor Hsiehc8176ef2018-01-08 12:43:00 -0800489 set_app_seccomp_filter();
490 } else {
491 set_system_seccomp_filter();
492 }
493}
494
Chris Wailes8b35ba22019-01-10 16:55:32 -0800495static void EnableKeepCapabilities(fail_fn_t fail_fn) {
496 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
497 fail_fn(CREATE_ERROR("prctl(PR_SET_KEEPCAPS) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100498 }
499}
500
Chris Wailes8b35ba22019-01-10 16:55:32 -0800501static void DropCapabilitiesBoundingSet(fail_fn_t fail_fn) {
502 for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {;
503 if (prctl(PR_CAPBSET_DROP, i, 0, 0, 0) == -1) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100504 if (errno == EINVAL) {
505 ALOGE("prctl(PR_CAPBSET_DROP) failed with EINVAL. Please verify "
506 "your kernel is compiled with file capabilities support");
507 } else {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800508 fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100509 }
510 }
511 }
512}
513
Chris Wailes8b35ba22019-01-10 16:55:32 -0800514static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) {
Josh Gao45dab782017-02-01 14:56:09 -0800515 __user_cap_header_struct capheader;
516 memset(&capheader, 0, sizeof(capheader));
517 capheader.version = _LINUX_CAPABILITY_VERSION_3;
518 capheader.pid = 0;
519
520 __user_cap_data_struct capdata[2];
521 if (capget(&capheader, &capdata[0]) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800522 fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800523 }
524
525 capdata[0].inheritable = inheritable;
526 capdata[1].inheritable = inheritable >> 32;
527
528 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800529 fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno)));
Josh Gao45dab782017-02-01 14:56:09 -0800530 }
531}
532
Chris Wailes8b35ba22019-01-10 16:55:32 -0800533static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable,
534 fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100535 __user_cap_header_struct capheader;
536 memset(&capheader, 0, sizeof(capheader));
537 capheader.version = _LINUX_CAPABILITY_VERSION_3;
538 capheader.pid = 0;
539
540 __user_cap_data_struct capdata[2];
541 memset(&capdata, 0, sizeof(capdata));
542 capdata[0].effective = effective;
543 capdata[1].effective = effective >> 32;
544 capdata[0].permitted = permitted;
545 capdata[1].permitted = permitted >> 32;
Josh Gao45dab782017-02-01 14:56:09 -0800546 capdata[0].inheritable = inheritable;
547 capdata[1].inheritable = inheritable >> 32;
Narayan Kamath973b4662014-03-31 13:41:26 +0100548
549 if (capset(&capheader, &capdata[0]) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800550 fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") "
551 "failed: %s", permitted, effective, inheritable, strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100552 }
553}
554
Chris Wailes8b35ba22019-01-10 16:55:32 -0800555static void SetSchedulerPolicy(fail_fn_t fail_fn) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100556 errno = -set_sched_policy(0, SP_DEFAULT);
557 if (errno != 0) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800558 fail_fn(CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100559 }
560}
561
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700562static int UnmountTree(const char* path) {
563 size_t path_len = strlen(path);
564
565 FILE* fp = setmntent("/proc/mounts", "r");
Chris Wailes8b35ba22019-01-10 16:55:32 -0800566 if (fp == nullptr) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700567 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
568 return -errno;
569 }
570
571 // Some volumes can be stacked on each other, so force unmount in
572 // reverse order to give us the best chance of success.
573 std::list<std::string> toUnmount;
574 mntent* mentry;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800575 while ((mentry = getmntent(fp)) != nullptr) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700576 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
577 toUnmount.push_front(std::string(mentry->mnt_dir));
578 }
579 }
580 endmntent(fp);
581
Chih-Hung Hsieha1b644e2018-12-11 11:09:20 -0800582 for (const auto& path : toUnmount) {
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700583 if (umount2(path.c_str(), MNT_DETACH)) {
584 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
585 }
586 }
587 return 0;
588}
589
Narayan Kamath973b4662014-03-31 13:41:26 +0100590// Create a private mount namespace and bind mount appropriate emulated
591// storage for the given user.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800592static void MountEmulatedStorage(uid_t uid, jint mount_mode,
593 bool force_mount_namespace, fail_fn_t fail_fn) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700594 // See storage config details at http://source.android.com/tech/storage/
595
Jeff Sharkey9527b222015-06-24 15:24:48 -0700596 String8 storageSource;
597 if (mount_mode == MOUNT_EXTERNAL_DEFAULT) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700598 storageSource = "/mnt/runtime/default";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700599 } else if (mount_mode == MOUNT_EXTERNAL_READ) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700600 storageSource = "/mnt/runtime/read";
Jeff Sharkey9527b222015-06-24 15:24:48 -0700601 } else if (mount_mode == MOUNT_EXTERNAL_WRITE) {
Jeff Sharkey928e1ec2015-08-06 11:40:21 -0700602 storageSource = "/mnt/runtime/write";
Robert Sesek06af1c02016-11-10 21:50:04 -0500603 } else if (!force_mount_namespace) {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700604 // Sane default of no storage visible
Chris Wailes8b35ba22019-01-10 16:55:32 -0800605 return;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700606 }
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400607
608 // Create a second private mount namespace for our process
609 if (unshare(CLONE_NEWNS) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800610 fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
Robert Sesek8a3a6ff2016-10-31 11:25:10 -0400611 }
612
Robert Sesek06f39302017-03-20 17:30:05 -0400613 // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
614 if (mount_mode == MOUNT_EXTERNAL_NONE) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800615 return;
Robert Sesek06f39302017-03-20 17:30:05 -0400616 }
617
Jeff Sharkey9527b222015-06-24 15:24:48 -0700618 if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage",
Chris Wailes8b35ba22019-01-10 16:55:32 -0800619 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
620 fail_fn(CREATE_ERROR("Failed to mount %s to /storage: %s",
621 storageSource.string(),
622 strerror(errno)));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700623 }
624
Jeff Sharkeyfaf3f692015-06-30 15:56:33 -0700625 // Mount user-specific symlink helper into place
Jeff Sharkey9527b222015-06-24 15:24:48 -0700626 userid_t user_id = multiuser_get_user_id(uid);
627 const String8 userSource(String8::format("/mnt/user/%d", user_id));
628 if (fs_prepare_dir(userSource.string(), 0751, 0, 0) == -1) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800629 fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s (%s)",
630 userSource.string(), strerror(errno)));
Jeff Sharkey9527b222015-06-24 15:24:48 -0700631 }
632
Chris Wailes8b35ba22019-01-10 16:55:32 -0800633 if (TEMP_FAILURE_RETRY(mount(userSource.string(), "/storage/self",
634 nullptr, MS_BIND, nullptr)) == -1) {
635 fail_fn(CREATE_ERROR("Failed to mount %s to /storage/self: %s",
636 userSource.string(), strerror(errno)));
637 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100638}
639
Narayan Kamath973b4662014-03-31 13:41:26 +0100640static bool NeedsNoRandomizeWorkaround() {
641#if !defined(__arm__)
642 return false;
643#else
644 int major;
645 int minor;
646 struct utsname uts;
647 if (uname(&uts) == -1) {
648 return false;
649 }
650
651 if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
652 return false;
653 }
654
655 // Kernels before 3.4.* need the workaround.
656 return (major < 3) || ((major == 3) && (minor < 4));
657#endif
658}
Narayan Kamath973b4662014-03-31 13:41:26 +0100659
660// Utility to close down the Zygote socket file descriptors while
661// the child is still running as root with Zygote's privileges. Each
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800662// descriptor (if any) is closed via dup3(), replacing it with a valid
Narayan Kamath973b4662014-03-31 13:41:26 +0100663// (open) descriptor to /dev/null.
664
Chris Wailes8b35ba22019-01-10 16:55:32 -0800665static void DetachDescriptors(JNIEnv* env,
666 const std::vector<int>& fds_to_close,
667 fail_fn_t fail_fn) {
668
669 if (fds_to_close.size() > 0) {
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800670 android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC));
Chris Wailes8b35ba22019-01-10 16:55:32 -0800671 if (devnull_fd == -1) {
672 fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno)));
Narayan Kamath973b4662014-03-31 13:41:26 +0100673 }
Chris Wailes8b35ba22019-01-10 16:55:32 -0800674
675 for (int fd : fds_to_close) {
676 ALOGV("Switching descriptor %d to /dev/null", fd);
Nick Kralevich5d5bf1f2019-01-25 10:24:42 -0800677 if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) {
678 fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno)));
Chris Wailes8b35ba22019-01-10 16:55:32 -0800679 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100680 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100681 }
682}
683
Chris Wailes8b35ba22019-01-10 16:55:32 -0800684void SetThreadName(const std::string& thread_name) {
Narayan Kamath973b4662014-03-31 13:41:26 +0100685 bool hasAt = false;
686 bool hasDot = false;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800687
688 for (const char str_el : thread_name) {
689 if (str_el == '.') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100690 hasDot = true;
Chris Wailes8b35ba22019-01-10 16:55:32 -0800691 } else if (str_el == '@') {
Narayan Kamath973b4662014-03-31 13:41:26 +0100692 hasAt = true;
693 }
Narayan Kamath973b4662014-03-31 13:41:26 +0100694 }
Chris Wailes8b35ba22019-01-10 16:55:32 -0800695
696 const char* name_start_ptr = thread_name.c_str();
697 if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
698 name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
Narayan Kamath973b4662014-03-31 13:41:26 +0100699 }
Chris Wailes8b35ba22019-01-10 16:55:32 -0800700
Narayan Kamath973b4662014-03-31 13:41:26 +0100701 // pthread_setname_np fails rather than truncating long strings.
702 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
Chris Wailes8b35ba22019-01-10 16:55:32 -0800703 strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
Narayan Kamath973b4662014-03-31 13:41:26 +0100704 errno = pthread_setname_np(pthread_self(), buf);
705 if (errno != 0) {
Elliott Hughes960e8312014-09-30 08:49:01 -0700706 ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
Narayan Kamath973b4662014-03-31 13:41:26 +0100707 }
Andreas Gampe041483a2018-03-05 13:00:42 -0800708 // Update base::logging default tag.
709 android::base::SetDefaultTag(buf);
Narayan Kamath973b4662014-03-31 13:41:26 +0100710}
711
Chris Wailes8b35ba22019-01-10 16:55:32 -0800712/**
713 * A failure function used to report fatal errors to the managed runtime. This
714 * function is often curried with the process name information and then passed
715 * to called functions.
716 *
717 * @param env Managed runtime environment
718 * @param process_name A native representation of the process name
719 * @param managed_process_name A managed representation of the process name
720 * @param msg The error message to be reported
721 */
Chris Wailesefc65b22018-10-26 12:41:54 -0700722[[noreturn]]
723static void ZygoteFailure(JNIEnv* env,
724 const char* process_name,
725 jstring managed_process_name,
726 const std::string& msg) {
727 std::unique_ptr<ScopedUtfChars> scoped_managed_process_name_ptr = nullptr;
728 if (managed_process_name != nullptr) {
729 scoped_managed_process_name_ptr.reset(new ScopedUtfChars(env, managed_process_name));
730 if (scoped_managed_process_name_ptr->c_str() != nullptr) {
731 process_name = scoped_managed_process_name_ptr->c_str();
732 }
733 }
David Sehrde8d0bd2018-06-22 10:45:36 -0700734
Chris Wailesefc65b22018-10-26 12:41:54 -0700735 const std::string& error_msg =
736 (process_name == nullptr) ? msg : StringPrintf("(%s) %s", process_name, msg.c_str());
737
738 env->FatalError(error_msg.c_str());
739 __builtin_unreachable();
740}
741
Chris Wailes8b35ba22019-01-10 16:55:32 -0800742/**
743 * A helper method for converting managed strings to native strings. A fatal
744 * error is generated if a problem is encountered in extracting a non-null
745 * string.
746 *
747 * @param env Managed runtime environment
748 * @param process_name A native representation of the process name
749 * @param managed_process_name A managed representation of the process name
750 * @param managed_string The managed string to extract
751 *
752 * @return An empty option if the managed string is null. A optional-wrapped
753 * string otherwise.
754 */
Chris Wailesefc65b22018-10-26 12:41:54 -0700755static std::optional<std::string> ExtractJString(JNIEnv* env,
756 const char* process_name,
757 jstring managed_process_name,
758 jstring managed_string) {
759 if (managed_string == nullptr) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800760 return std::nullopt;
Chris Wailesefc65b22018-10-26 12:41:54 -0700761 } else {
762 ScopedUtfChars scoped_string_chars(env, managed_string);
763
764 if (scoped_string_chars.c_str() != nullptr) {
765 return std::optional<std::string>(scoped_string_chars.c_str());
766 } else {
767 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JString.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700768 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700769 }
770}
771
Chris Wailes8b35ba22019-01-10 16:55:32 -0800772/**
773 * A helper method for converting managed integer arrays to native vectors. A
774 * fatal error is generated if a problem is encountered in extracting a non-null array.
775 *
776 * @param env Managed runtime environment
777 * @param process_name A native representation of the process name
778 * @param managed_process_name A managed representation of the process name
779 * @param managed_array The managed integer array to extract
780 *
781 * @return An empty option if the managed array is null. A optional-wrapped
782 * vector otherwise.
783 */
784static std::optional<std::vector<int>> ExtractJIntArray(JNIEnv* env,
785 const char* process_name,
786 jstring managed_process_name,
787 jintArray managed_array) {
788 if (managed_array == nullptr) {
789 return std::nullopt;
790 } else {
791 ScopedIntArrayRO managed_array_handle(env, managed_array);
Chris Wailesefc65b22018-10-26 12:41:54 -0700792
Chris Wailes8b35ba22019-01-10 16:55:32 -0800793 if (managed_array_handle.get() != nullptr) {
794 std::vector<int> native_array;
795 native_array.reserve(managed_array_handle.size());
796
797 for (size_t array_index = 0; array_index < managed_array_handle.size(); ++array_index) {
798 native_array.push_back(managed_array_handle[array_index]);
799 }
800
801 return std::move(native_array);
802
803 } else {
804 ZygoteFailure(env, process_name, managed_process_name, "Failed to extract JIntArray.");
805 }
806 }
807}
808
809/**
810 * A utility function for blocking signals.
811 *
812 * @param signum Signal number to block
813 * @param fail_fn Fatal error reporting function
814 *
815 * @see ZygoteFailure
816 */
817static void BlockSignal(int signum, fail_fn_t fail_fn) {
818 sigset_t sigs;
819 sigemptyset(&sigs);
820 sigaddset(&sigs, signum);
821
822 if (sigprocmask(SIG_BLOCK, &sigs, nullptr) == -1) {
823 fail_fn(CREATE_ERROR("Failed to block signal %s: %s", strsignal(signum), strerror(errno)));
824 }
825}
826
827
828/**
829 * A utility function for unblocking signals.
830 *
831 * @param signum Signal number to unblock
832 * @param fail_fn Fatal error reporting function
833 *
834 * @see ZygoteFailure
835 */
836static void UnblockSignal(int signum, fail_fn_t fail_fn) {
837 sigset_t sigs;
838 sigemptyset(&sigs);
839 sigaddset(&sigs, signum);
840
841 if (sigprocmask(SIG_UNBLOCK, &sigs, nullptr) == -1) {
842 fail_fn(CREATE_ERROR("Failed to un-block signal %s: %s", strsignal(signum), strerror(errno)));
843 }
844}
845
846// Utility routine to fork a process from the zygote.
847static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
848 const std::vector<int>& fds_to_close,
849 const std::vector<int>& fds_to_ignore) {
850 SetSignalHandlers();
Chris Wailesefc65b22018-10-26 12:41:54 -0700851
852 // Curry a failure function.
853 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
854 nullptr, _1);
855
856 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
857 // log, which would result in the logging FDs we close being reopened.
858 // This would cause failures because the FDs are not whitelisted.
859 //
860 // Note that the zygote process is single threaded at this point.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800861 BlockSignal(SIGCHLD, fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700862
863 // Close any logging related FDs before we start evaluating the list of
864 // file descriptors.
865 __android_log_close();
866 stats_log_close();
867
868 // If this is the first fork for this zygote, create the open FD table. If
869 // it isn't, we just need to check whether the list of open files has changed
870 // (and it shouldn't in the normal case).
Chris Wailesefc65b22018-10-26 12:41:54 -0700871 if (gOpenFdTable == nullptr) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800872 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
873 } else {
874 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700875 }
876
877 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
878
879 pid_t pid = fork();
880
881 if (pid == 0) {
882 // The child process.
883 PreApplicationInit();
884
885 // Clean up any descriptors which must be closed immediately
Chris Wailes8b35ba22019-01-10 16:55:32 -0800886 DetachDescriptors(env, fds_to_close, fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700887
888 // Re-open all remaining open file descriptors so that they aren't shared
889 // with the zygote across a fork.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800890 gOpenFdTable->ReopenOrDetach(fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700891
892 // Turn fdsan back on.
893 android_fdsan_set_error_level(fdsan_error_level);
894 }
895
896 // We blocked SIGCHLD prior to a fork, we unblock it here.
Chris Wailes8b35ba22019-01-10 16:55:32 -0800897 UnblockSignal(SIGCHLD, fail_fn);
898
Chris Wailesefc65b22018-10-26 12:41:54 -0700899 return pid;
900}
901
902// Utility routine to specialize a zygote child process.
903static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
904 jint runtime_flags, jobjectArray rlimits,
905 jlong permitted_capabilities, jlong effective_capabilities,
906 jint mount_external, jstring managed_se_info,
907 jstring managed_nice_name, bool is_system_server,
908 bool is_child_zygote, jstring managed_instruction_set,
909 jstring managed_app_data_dir) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800910 const char* process_name = is_system_server ? "system_server" : "zygote";
911 auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
912 auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
Chris Wailesefc65b22018-10-26 12:41:54 -0700913
914 auto se_info = extract_fn(managed_se_info);
915 auto nice_name = extract_fn(managed_nice_name);
916 auto instruction_set = extract_fn(managed_instruction_set);
917 auto app_data_dir = extract_fn(managed_app_data_dir);
918
David Sehrde8d0bd2018-06-22 10:45:36 -0700919 // Keep capabilities across UID change, unless we're staying root.
920 if (uid != 0) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800921 EnableKeepCapabilities(fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700922 }
923
Chris Wailes8b35ba22019-01-10 16:55:32 -0800924 SetInheritable(permitted_capabilities, fail_fn);
Chris Wailesefc65b22018-10-26 12:41:54 -0700925
Chris Wailes8b35ba22019-01-10 16:55:32 -0800926 DropCapabilitiesBoundingSet(fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700927
Chris Wailesefc65b22018-10-26 12:41:54 -0700928 bool use_native_bridge = !is_system_server &&
929 instruction_set.has_value() &&
930 android::NativeBridgeAvailable() &&
931 android::NeedsNativeBridge(instruction_set.value().c_str());
932
933 if (use_native_bridge && !app_data_dir.has_value()) {
934 // The app_data_dir variable should never be empty if we need to use a
935 // native bridge. In general, app_data_dir will never be empty for normal
936 // applications. It can only happen in special cases (for isolated
937 // processes which are not associated with any app). These are launched by
938 // the framework and should not be emulated anyway.
David Sehrde8d0bd2018-06-22 10:45:36 -0700939 use_native_bridge = false;
Chris Wailesefc65b22018-10-26 12:41:54 -0700940 ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr.");
David Sehrde8d0bd2018-06-22 10:45:36 -0700941 }
942
Chris Wailes8b35ba22019-01-10 16:55:32 -0800943 MountEmulatedStorage(uid, mount_external, use_native_bridge, fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700944
945 // If this zygote isn't root, it won't be able to create a process group,
946 // since the directory is owned by root.
947 if (!is_system_server && getuid() == 0) {
Chris Wailes8b35ba22019-01-10 16:55:32 -0800948 const int rc = createProcessGroup(uid, getpid());
David Sehrde8d0bd2018-06-22 10:45:36 -0700949 if (rc != 0) {
950 if (rc == -EROFS) {
951 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
952 } else {
953 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, 0/*pid*/, strerror(-rc));
954 }
955 }
956 }
957
Chris Wailes8b35ba22019-01-10 16:55:32 -0800958 SetGids(env, gids, fail_fn);
959 SetRLimits(env, rlimits, fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -0700960
961 if (use_native_bridge) {
Chris Wailesefc65b22018-10-26 12:41:54 -0700962 // Due to the logic behind use_native_bridge we know that both app_data_dir
963 // and instruction_set contain values.
964 android::PreInitializeNativeBridge(app_data_dir.value().c_str(),
965 instruction_set.value().c_str());
David Sehrde8d0bd2018-06-22 10:45:36 -0700966 }
967
Chris Wailesefc65b22018-10-26 12:41:54 -0700968 if (setresgid(gid, gid, gid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700969 fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno)));
970 }
971
Chris Wailesefc65b22018-10-26 12:41:54 -0700972 // Must be called when the new process still has CAP_SYS_ADMIN, in this case,
973 // before changing uid from 0, which clears capabilities. The other
974 // alternative is to call prctl(PR_SET_NO_NEW_PRIVS, 1) afterward, but that
975 // breaks SELinux domain transition (see b/71859146). As the result,
976 // privileged syscalls used below still need to be accessible in app process.
David Sehrde8d0bd2018-06-22 10:45:36 -0700977 SetUpSeccompFilter(uid);
978
Chris Wailesefc65b22018-10-26 12:41:54 -0700979 if (setresuid(uid, uid, uid) == -1) {
David Sehrde8d0bd2018-06-22 10:45:36 -0700980 fail_fn(CREATE_ERROR("setresuid(%d) failed: %s", uid, strerror(errno)));
981 }
982
983 // The "dumpable" flag of a process, which controls core dump generation, is
984 // overwritten by the value in /proc/sys/fs/suid_dumpable when the effective
985 // user or group ID changes. See proc(5) for possible values. In most cases,
986 // the value is 0, so core dumps are disabled for zygote children. However,
987 // when running in a Chrome OS container, the value is already set to 2,
988 // which allows the external crash reporter to collect all core dumps. Since
989 // only system crashes are interested, core dump is disabled for app
990 // processes. This also ensures compliance with CTS.
991 int dumpable = prctl(PR_GET_DUMPABLE);
992 if (dumpable == -1) {
993 ALOGE("prctl(PR_GET_DUMPABLE) failed: %s", strerror(errno));
994 RuntimeAbort(env, __LINE__, "prctl(PR_GET_DUMPABLE) failed");
995 }
Chris Wailesefc65b22018-10-26 12:41:54 -0700996
David Sehrde8d0bd2018-06-22 10:45:36 -0700997 if (dumpable == 2 && uid >= AID_APP) {
998 if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == -1) {
999 ALOGE("prctl(PR_SET_DUMPABLE, 0) failed: %s", strerror(errno));
1000 RuntimeAbort(env, __LINE__, "prctl(PR_SET_DUMPABLE, 0) failed");
1001 }
1002 }
1003
Orion Hodson8d005a62018-12-05 12:28:53 +00001004 // Set process properties to enable debugging if required.
1005 if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
1006 EnableDebugger();
1007 }
1008
David Sehrde8d0bd2018-06-22 10:45:36 -07001009 if (NeedsNoRandomizeWorkaround()) {
1010 // Work around ARM kernel ASLR lossage (http://b/5817320).
1011 int old_personality = personality(0xffffffff);
1012 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1013 if (new_personality == -1) {
1014 ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
1015 }
1016 }
1017
Chris Wailes8b35ba22019-01-10 16:55:32 -08001018 SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -07001019
Chris Wailes8b35ba22019-01-10 16:55:32 -08001020 SetSchedulerPolicy(fail_fn);
David Sehrde8d0bd2018-06-22 10:45:36 -07001021
Chris Wailesefc65b22018-10-26 12:41:54 -07001022 const char* se_info_ptr = se_info.has_value() ? se_info.value().c_str() : nullptr;
1023 const char* nice_name_ptr = nice_name.has_value() ? nice_name.value().c_str() : nullptr;
1024
1025 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1026 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1027 uid, is_system_server, se_info_ptr, nice_name_ptr));
David Sehrde8d0bd2018-06-22 10:45:36 -07001028 }
1029
1030 // Make it easier to debug audit logs by setting the main thread's name to the
1031 // nice name rather than "app_process".
Chris Wailesefc65b22018-10-26 12:41:54 -07001032 if (nice_name.has_value()) {
Chris Wailes8b35ba22019-01-10 16:55:32 -08001033 SetThreadName(nice_name.value());
Chris Wailesefc65b22018-10-26 12:41:54 -07001034 } else if (is_system_server) {
1035 SetThreadName("system_server");
David Sehrde8d0bd2018-06-22 10:45:36 -07001036 }
David Sehrde8d0bd2018-06-22 10:45:36 -07001037
1038 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1039 UnsetChldSignalHandler();
1040
Orion Hodson46724e72018-10-19 13:05:33 +01001041 if (is_system_server) {
1042 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1043 if (env->ExceptionCheck()) {
1044 fail_fn("Error calling post fork system server hooks.");
1045 }
Chris Wailes8b35ba22019-01-10 16:55:32 -08001046
Orion Hodson46724e72018-10-19 13:05:33 +01001047 // TODO(oth): Remove hardcoded label here (b/117874058).
1048 static const char* kSystemServerLabel = "u:r:system_server:s0";
1049 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1050 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1051 }
1052 }
1053
David Sehrde8d0bd2018-06-22 10:45:36 -07001054 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
Chris Wailesefc65b22018-10-26 12:41:54 -07001055 is_system_server, is_child_zygote, managed_instruction_set);
1056
David Sehrde8d0bd2018-06-22 10:45:36 -07001057 if (env->ExceptionCheck()) {
1058 fail_fn("Error calling post fork hooks.");
1059 }
1060}
1061
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001062static uint64_t GetEffectiveCapabilityMask(JNIEnv* env) {
1063 __user_cap_header_struct capheader;
1064 memset(&capheader, 0, sizeof(capheader));
1065 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1066 capheader.pid = 0;
1067
1068 __user_cap_data_struct capdata[2];
1069 if (capget(&capheader, &capdata[0]) == -1) {
1070 ALOGE("capget failed: %s", strerror(errno));
1071 RuntimeAbort(env, __LINE__, "capget failed");
1072 }
1073
Chris Wailesefc65b22018-10-26 12:41:54 -07001074 return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32);
1075}
1076
1077static jlong CalculateCapabilities(JNIEnv* env, jint uid, jint gid, jintArray gids,
1078 bool is_child_zygote) {
1079 jlong capabilities = 0;
1080
1081 /*
1082 * Grant the following capabilities to the Bluetooth user:
1083 * - CAP_WAKE_ALARM
1084 * - CAP_NET_RAW
1085 * - CAP_NET_BIND_SERVICE (for DHCP client functionality)
1086 * - CAP_SYS_NICE (for setting RT priority for audio-related threads)
1087 */
1088
1089 if (multiuser_get_app_id(uid) == AID_BLUETOOTH) {
1090 capabilities |= (1LL << CAP_WAKE_ALARM);
1091 capabilities |= (1LL << CAP_NET_RAW);
1092 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1093 capabilities |= (1LL << CAP_SYS_NICE);
1094 }
1095
Remi NGUYEN VANc094a542018-12-07 16:52:24 +09001096 if (multiuser_get_app_id(uid) == AID_NETWORK_STACK) {
1097 capabilities |= (1LL << CAP_NET_ADMIN);
1098 capabilities |= (1LL << CAP_NET_BROADCAST);
1099 capabilities |= (1LL << CAP_NET_BIND_SERVICE);
1100 capabilities |= (1LL << CAP_NET_RAW);
1101 }
1102
Chris Wailesefc65b22018-10-26 12:41:54 -07001103 /*
1104 * Grant CAP_BLOCK_SUSPEND to processes that belong to GID "wakelock"
1105 */
1106
1107 bool gid_wakelock_found = false;
1108 if (gid == AID_WAKELOCK) {
1109 gid_wakelock_found = true;
1110 } else if (gids != nullptr) {
1111 jsize gids_num = env->GetArrayLength(gids);
1112 ScopedIntArrayRO native_gid_proxy(env, gids);
1113
1114 if (native_gid_proxy.get() == nullptr) {
1115 RuntimeAbort(env, __LINE__, "Bad gids array");
1116 }
1117
1118 for (int gid_index = gids_num; --gids_num >= 0;) {
1119 if (native_gid_proxy[gid_index] == AID_WAKELOCK) {
1120 gid_wakelock_found = true;
1121 break;
1122 }
1123 }
1124 }
1125
1126 if (gid_wakelock_found) {
1127 capabilities |= (1LL << CAP_BLOCK_SUSPEND);
1128 }
1129
1130 /*
1131 * Grant child Zygote processes the following capabilities:
1132 * - CAP_SETUID (change UID of child processes)
1133 * - CAP_SETGID (change GID of child processes)
1134 * - CAP_SETPCAP (change capabilities of child processes)
1135 */
1136
1137 if (is_child_zygote) {
1138 capabilities |= (1LL << CAP_SETUID);
1139 capabilities |= (1LL << CAP_SETGID);
1140 capabilities |= (1LL << CAP_SETPCAP);
1141 }
1142
1143 /*
1144 * Containers run without some capabilities, so drop any caps that are not
1145 * available.
1146 */
1147
1148 return capabilities & GetEffectiveCapabilityMask(env);
Luis Hector Chavez72042c92017-07-12 10:03:30 -07001149}
Chris Wailes8b35ba22019-01-10 16:55:32 -08001150
1151/**
1152 * Adds the given information about a newly created blastula to the Zygote's
1153 * blastula table.
1154 *
1155 * @param blastula_pid Process ID of the newly created blastula
1156 * @param read_pipe_fd File descriptor for the read end of the blastula
1157 * reporting pipe. Used in the ZygoteServer poll loop to track blastula
1158 * specialization.
1159 */
1160static void AddBlastulaTableEntry(pid_t blastula_pid, int read_pipe_fd) {
1161 static int sBlastulaTableInsertIndex = 0;
1162
1163 int search_index = sBlastulaTableInsertIndex;
1164
1165 do {
1166 if (gBlastulaTable[search_index].SetIfInvalid(blastula_pid, read_pipe_fd)) {
1167 // Start our next search right after where we finished this one.
1168 sBlastulaTableInsertIndex = (search_index + 1) % gBlastulaTable.size();
1169
1170 return;
1171 }
1172
1173 search_index = (search_index + 1) % gBlastulaTable.size();
1174 } while (search_index != sBlastulaTableInsertIndex);
1175
1176 // Much like money in the banana stand, there should always be an entry
1177 // in the blastula table.
1178 __builtin_unreachable();
1179}
1180
1181/**
1182 * Invalidates the entry in the BlastulaTable corresponding to the provided
1183 * process ID if it is present. If an entry was removed the blastula pool
1184 * count is decremented.
1185 *
1186 * @param blastula_pid Process ID of the blastula entry to invalidate
1187 * @return True if an entry was invalidated; false otherwise
1188 */
1189static bool RemoveBlastulaTableEntry(pid_t blastula_pid) {
1190 for (BlastulaTableEntry& entry : gBlastulaTable) {
1191 if (entry.ClearForPID(blastula_pid)) {
1192 --gBlastulaPoolCount;
1193 return true;
1194 }
1195 }
1196
1197 return false;
1198}
1199
1200/**
1201 * @return A vector of the read pipe FDs for each of the active blastulas.
1202 */
1203std::vector<int> MakeBlastulaPipeReadFDVector() {
1204 std::vector<int> fd_vec;
1205 fd_vec.reserve(gBlastulaTable.size());
1206
1207 for (BlastulaTableEntry& entry : gBlastulaTable) {
1208 auto entry_values = entry.GetValues();
1209
1210 if (entry_values.has_value()) {
1211 fd_vec.push_back(entry_values.value().read_pipe_fd);
1212 }
1213 }
1214
1215 return fd_vec;
1216}
1217
Narayan Kamath973b4662014-03-31 13:41:26 +01001218} // anonymous namespace
1219
1220namespace android {
1221
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001222static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) {
Chris Wailesefc65b22018-10-26 12:41:54 -07001223 // security_getenforce is not allowed on app process. Initialize and cache
1224 // the value before zygote forks.
Victor Hsiehc8176ef2018-01-08 12:43:00 -08001225 g_is_security_enforced = security_getenforce();
1226}
1227
Christopher Ferris76de39e2017-06-20 16:13:40 -07001228static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) {
1229 PreApplicationInit();
1230}
1231
Narayan Kamath973b4662014-03-31 13:41:26 +01001232static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
1233 JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +01001234 jint runtime_flags, jobjectArray rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -07001235 jint mount_external, jstring se_info, jstring nice_name,
Chris Wailes8b35ba22019-01-10 16:55:32 -08001236 jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
Chris Wailesefc65b22018-10-26 12:41:54 -07001237 jstring instruction_set, jstring app_data_dir) {
1238 jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
Pavlin Radoslavovfbd59042015-11-23 17:13:25 -08001239
Chris Wailes8b35ba22019-01-10 16:55:32 -08001240 if (UNLIKELY(managed_fds_to_close == nullptr)) {
1241 ZygoteFailure(env, "zygote", nice_name, "Zygote received a null fds_to_close vector.");
1242 }
1243
1244 std::vector<int> fds_to_close =
1245 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_close).value();
1246 std::vector<int> fds_to_ignore =
1247 ExtractJIntArray(env, "zygote", nice_name, managed_fds_to_ignore)
1248 .value_or(std::vector<int>());
1249
1250 std::vector<int> blastula_pipes = MakeBlastulaPipeReadFDVector();
1251
1252 fds_to_close.insert(fds_to_close.end(), blastula_pipes.begin(), blastula_pipes.end());
1253 fds_to_ignore.insert(fds_to_ignore.end(), blastula_pipes.begin(), blastula_pipes.end());
1254
Chris Wailescffbf1c2019-01-11 17:13:00 -08001255 fds_to_close.push_back(gBlastulaPoolSocketFD);
Chris Wailes8b35ba22019-01-10 16:55:32 -08001256
1257 if (gBlastulaPoolEventFD != -1) {
1258 fds_to_close.push_back(gBlastulaPoolEventFD);
1259 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1260 }
1261
Chris Wailesefc65b22018-10-26 12:41:54 -07001262 pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
Chris Wailes8b35ba22019-01-10 16:55:32 -08001263
David Sehrde8d0bd2018-06-22 10:45:36 -07001264 if (pid == 0) {
1265 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1266 capabilities, capabilities,
Chris Wailesefc65b22018-10-26 12:41:54 -07001267 mount_external, se_info, nice_name, false,
1268 is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
David Sehrde8d0bd2018-06-22 10:45:36 -07001269 }
1270 return pid;
Narayan Kamath973b4662014-03-31 13:41:26 +01001271}
1272
1273static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1274 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
Chris Wailesefc65b22018-10-26 12:41:54 -07001275 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1276 jlong effective_capabilities) {
Chris Wailes8b35ba22019-01-10 16:55:32 -08001277 std::vector<int> fds_to_close(MakeBlastulaPipeReadFDVector()),
1278 fds_to_ignore(fds_to_close);
1279
Chris Wailescffbf1c2019-01-11 17:13:00 -08001280 fds_to_close.push_back(gBlastulaPoolSocketFD);
Chris Wailes8b35ba22019-01-10 16:55:32 -08001281
1282 if (gBlastulaPoolEventFD != -1) {
1283 fds_to_close.push_back(gBlastulaPoolEventFD);
1284 fds_to_ignore.push_back(gBlastulaPoolEventFD);
1285 }
1286
Chris Wailesefc65b22018-10-26 12:41:54 -07001287 pid_t pid = ForkCommon(env, true,
Chris Wailes8b35ba22019-01-10 16:55:32 -08001288 fds_to_close,
1289 fds_to_ignore);
David Sehrde8d0bd2018-06-22 10:45:36 -07001290 if (pid == 0) {
1291 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
Chris Wailesefc65b22018-10-26 12:41:54 -07001292 permitted_capabilities, effective_capabilities,
1293 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1294 false, nullptr, nullptr);
David Sehrde8d0bd2018-06-22 10:45:36 -07001295 } else if (pid > 0) {
Narayan Kamath973b4662014-03-31 13:41:26 +01001296 // The zygote process checks whether the child process has died or not.
1297 ALOGI("System server process %d has been created", pid);
1298 gSystemServerPid = pid;
1299 // There is a slight window that the system server process has crashed
1300 // but it went unnoticed because we haven't published its pid yet. So
1301 // we recheck here just to make sure that all is well.
1302 int status;
1303 if (waitpid(pid, &status, WNOHANG) == pid) {
1304 ALOGE("System server process %d has died. Restarting Zygote!", pid);
Andreas Gampeb053cce2015-11-17 16:38:59 -08001305 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
Narayan Kamath973b4662014-03-31 13:41:26 +01001306 }
Carmen Jacksondd401252017-02-23 15:21:10 -08001307
Minchan Kim696873e2018-06-27 11:32:40 +09001308 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
1309 bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
1310 if (per_app_memcg) {
1311 // Assign system_server to the correct memory cgroup.
1312 // Not all devices mount /dev/memcg so check for the file first
1313 // to avoid unnecessarily printing errors and denials in the logs.
1314 if (!access("/dev/memcg/system/tasks", F_OK) &&
Jeff Vander Stoep6bdc3a22017-11-22 23:09:23 -08001315 !WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
Minchan Kim696873e2018-06-27 11:32:40 +09001316 ALOGE("couldn't write %d to /dev/memcg/system/tasks", pid);
1317 }
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