Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2008 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
Chris Wailes | 30f16ca | 2019-01-17 14:57:10 -0800 | [diff] [blame] | 17 | /* |
| 18 | * Disable optimization of this file if we are compiling with the address |
| 19 | * sanitizer. This is a mitigation for b/122921367 and can be removed once the |
| 20 | * bug is fixed. |
| 21 | */ |
| 22 | #if __has_feature(address_sanitizer) |
| 23 | #pragma clang optimize off |
| 24 | #endif |
| 25 | |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 26 | #define LOG_TAG "Zygote" |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 27 | |
| 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 32 | #include <array> |
| 33 | #include <atomic> |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 34 | #include <functional> |
Jeff Sharkey | faf3f69 | 2015-06-30 15:56:33 -0700 | [diff] [blame] | 35 | #include <list> |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 36 | #include <optional> |
Andreas Gampe | b053cce | 2015-11-17 16:38:59 -0800 | [diff] [blame] | 37 | #include <sstream> |
Jeff Sharkey | faf3f69 | 2015-06-30 15:56:33 -0700 | [diff] [blame] | 38 | #include <string> |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 39 | #include <string_view> |
Jeff Sharkey | faf3f69 | 2015-06-30 15:56:33 -0700 | [diff] [blame] | 40 | |
Josh Gao | d795110 | 2018-06-26 16:05:12 -0700 | [diff] [blame] | 41 | #include <android/fdsan.h> |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 42 | #include <arpa/inet.h> |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 43 | #include <fcntl.h> |
Dan Albert | 46d8444 | 2014-11-18 16:07:51 -0800 | [diff] [blame] | 44 | #include <grp.h> |
| 45 | #include <inttypes.h> |
Christopher Ferris | ab16dd1 | 2017-05-15 16:50:29 -0700 | [diff] [blame] | 46 | #include <malloc.h> |
Jeff Sharkey | faf3f69 | 2015-06-30 15:56:33 -0700 | [diff] [blame] | 47 | #include <mntent.h> |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 48 | #include <paths.h> |
| 49 | #include <signal.h> |
| 50 | #include <stdlib.h> |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 51 | #include <sys/capability.h> |
Robert Sesek | e4f8d69 | 2016-09-13 19:13:01 -0400 | [diff] [blame] | 52 | #include <sys/cdefs.h> |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 53 | #include <sys/eventfd.h> |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 54 | #include <sys/personality.h> |
| 55 | #include <sys/prctl.h> |
| 56 | #include <sys/resource.h> |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 57 | #include <sys/socket.h> |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 58 | #include <sys/stat.h> |
Vitalii Tomkiv | 5cbce85 | 2016-05-18 17:43:02 -0700 | [diff] [blame] | 59 | #include <sys/time.h> |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 60 | #include <sys/types.h> |
| 61 | #include <sys/utsname.h> |
| 62 | #include <sys/wait.h> |
Dan Albert | 46d8444 | 2014-11-18 16:07:51 -0800 | [diff] [blame] | 63 | #include <unistd.h> |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 64 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 65 | #include <android-base/logging.h> |
Minchan Kim | 696873e | 2018-06-27 11:32:40 +0900 | [diff] [blame] | 66 | #include <android-base/properties.h> |
Carmen Jackson | dd40125 | 2017-02-23 15:21:10 -0800 | [diff] [blame] | 67 | #include <android-base/file.h> |
| 68 | #include <android-base/stringprintf.h> |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 69 | #include <android-base/unique_fd.h> |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 70 | #include <cutils/fs.h> |
| 71 | #include <cutils/multiuser.h> |
Sharvil Nanavati | 4990e4f | 2014-06-29 17:06:52 -0700 | [diff] [blame] | 72 | #include <private/android_filesystem_config.h> |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 73 | #include <utils/String8.h> |
| 74 | #include <selinux/android.h> |
Victor Hsieh | c8176ef | 2018-01-08 12:43:00 -0800 | [diff] [blame] | 75 | #include <seccomp_policy.h> |
Howard Ro | 65e48ec | 2018-10-02 12:08:28 -0700 | [diff] [blame] | 76 | #include <stats_event_list.h> |
Colin Cross | 0161bbc | 2014-06-03 13:26:58 -0700 | [diff] [blame] | 77 | #include <processgroup/processgroup.h> |
Suren Baghdasaryan | 5d445ad | 2019-01-25 05:23:40 +0000 | [diff] [blame] | 78 | #include <processgroup/sched_policy.h> |
Colin Cross | 18cd9f5 | 2014-06-13 12:58:55 -0700 | [diff] [blame] | 79 | |
Andreas Gampe | ed6b9df | 2014-11-20 22:02:20 -0800 | [diff] [blame] | 80 | #include "core_jni_helpers.h" |
Steven Moreland | 2279b25 | 2017-07-19 09:50:45 -0700 | [diff] [blame] | 81 | #include <nativehelper/JNIHelp.h> |
| 82 | #include <nativehelper/ScopedLocalRef.h> |
| 83 | #include <nativehelper/ScopedPrimitiveArray.h> |
| 84 | #include <nativehelper/ScopedUtfChars.h> |
Robert Sesek | 8225b7c | 2016-12-16 14:02:31 -0500 | [diff] [blame] | 85 | #include "fd_utils.h" |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 86 | |
jgu21 | 2eacd06 | 2014-09-10 06:55:07 -0400 | [diff] [blame] | 87 | #include "nativebridge/native_bridge.h" |
| 88 | |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 89 | namespace { |
| 90 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 91 | // TODO (chriswailes): Add a function to initialize native Zygote data. |
| 92 | // TODO (chriswailes): Fix mixed indentation style (2 and 4 spaces). |
| 93 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 94 | using namespace std::placeholders; |
| 95 | |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 96 | using android::String8; |
Carmen Jackson | dd40125 | 2017-02-23 15:21:10 -0800 | [diff] [blame] | 97 | using android::base::StringPrintf; |
| 98 | using android::base::WriteStringToFile; |
Minchan Kim | 696873e | 2018-06-27 11:32:40 +0900 | [diff] [blame] | 99 | using android::base::GetBoolProperty; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 100 | |
Andreas Gampe | d5758f6 | 2018-03-12 12:08:55 -0700 | [diff] [blame] | 101 | #define CREATE_ERROR(...) StringPrintf("%s:%d: ", __FILE__, __LINE__). \ |
| 102 | append(StringPrintf(__VA_ARGS__)) |
| 103 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 104 | // This type is duplicated in fd_utils.h |
| 105 | typedef const std::function<void(std::string)>& fail_fn_t; |
| 106 | |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 107 | static pid_t gSystemServerPid = 0; |
| 108 | |
| 109 | static const char kZygoteClassName[] = "com/android/internal/os/Zygote"; |
| 110 | static jclass gZygoteClass; |
Orion Hodson | 46724e7 | 2018-10-19 13:05:33 +0100 | [diff] [blame] | 111 | static jmethodID gCallPostForkSystemServerHooks; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 112 | static jmethodID gCallPostForkChildHooks; |
| 113 | |
Victor Hsieh | c8176ef | 2018-01-08 12:43:00 -0800 | [diff] [blame] | 114 | static bool g_is_security_enforced = true; |
| 115 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 116 | /** |
| 117 | * The maximum number of characters (not including a null terminator) that a |
| 118 | * process name may contain. |
| 119 | */ |
| 120 | static 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 | |
| 127 | static constexpr std::string_view ANDROID_SOCKET_PREFIX("ANDROID_SOCKET_"); |
| 128 | |
| 129 | /** |
| 130 | * The file descriptor for the Zygote socket opened by init. |
| 131 | */ |
| 132 | |
| 133 | static int gZygoteSocketFD = -1; |
| 134 | |
| 135 | /** |
| 136 | * The file descriptor for the Blastula pool socket opened by init. |
| 137 | */ |
| 138 | |
| 139 | static int gBlastulaPoolSocketFD = -1; |
| 140 | |
| 141 | /** |
| 142 | * The number of Blastulas currently in this Zygote's pool. |
| 143 | */ |
| 144 | static std::atomic_uint32_t gBlastulaPoolCount = 0; |
| 145 | |
| 146 | /** |
| 147 | * Event file descriptor used to communicate reaped blastulas to the |
| 148 | * ZygoteServer. |
| 149 | */ |
| 150 | static 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 | */ |
| 156 | static constexpr int BLASTULA_POOL_MAX_LIMIT = 10; |
| 157 | |
| 158 | /** |
| 159 | * A helper class containing accounting information for Blastulas. |
| 160 | */ |
| 161 | class 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 | */ |
| 255 | static std::array<BlastulaTableEntry, BLASTULA_POOL_MAX_LIMIT> gBlastulaTable; |
| 256 | |
| 257 | /** |
| 258 | * The list of open zygote file descriptors. |
| 259 | */ |
| 260 | static FileDescriptorTable* gOpenFdTable = nullptr; |
| 261 | |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 262 | // Must match values in com.android.internal.os.Zygote. |
| 263 | enum MountExternalKind { |
| 264 | MOUNT_EXTERNAL_NONE = 0, |
Jeff Sharkey | 4887789 | 2015-03-18 11:27:19 -0700 | [diff] [blame] | 265 | MOUNT_EXTERNAL_DEFAULT = 1, |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 266 | MOUNT_EXTERNAL_READ = 2, |
| 267 | MOUNT_EXTERNAL_WRITE = 3, |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 268 | }; |
| 269 | |
Orion Hodson | 8d005a6 | 2018-12-05 12:28:53 +0000 | [diff] [blame] | 270 | // Must match values in com.android.internal.os.Zygote. |
| 271 | enum RuntimeFlags : uint32_t { |
| 272 | DEBUG_ENABLE_JDWP = 1, |
| 273 | }; |
| 274 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 275 | // Forward declaration so we don't have to move the signal handler. |
| 276 | static bool RemoveBlastulaTableEntry(pid_t blastula_pid); |
| 277 | |
Andreas Gampe | b053cce | 2015-11-17 16:38:59 -0800 | [diff] [blame] | 278 | static 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 282 | } |
| 283 | |
| 284 | // This signal handler is for zygote mode, since the zygote must reap its children |
| 285 | static void SigChldHandler(int /*signal_number*/) { |
| 286 | pid_t pid; |
| 287 | int status; |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 288 | int64_t blastulas_removed = 0; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 289 | |
Christopher Ferris | a8a7954 | 2015-08-31 15:40:01 -0700 | [diff] [blame] | 290 | // 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 298 | 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 Gao | 6d747ca | 2017-08-02 12:54:05 -0700 | [diff] [blame] | 307 | ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status)); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 308 | } else if (WIFSIGNALED(status)) { |
Josh Gao | 6d747ca | 2017-08-02 12:54:05 -0700 | [diff] [blame] | 309 | ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status)); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 310 | if (WCOREDUMP(status)) { |
| 311 | ALOGI("Process %d dumped core.", pid); |
| 312 | } |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 313 | } |
| 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 Albert | 46d8444 | 2014-11-18 16:07:51 -0800 | [diff] [blame] | 319 | ALOGE("Exit zygote because system server (%d) has terminated", pid); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 320 | kill(getpid(), SIGKILL); |
| 321 | } |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 322 | |
| 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 327 | } |
| 328 | |
Narayan Kamath | 160992d | 2014-04-14 14:46:07 +0100 | [diff] [blame] | 329 | // 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 333 | } |
Christopher Ferris | a8a7954 | 2015-08-31 15:40:01 -0700 | [diff] [blame] | 334 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 335 | 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 Ferris | a8a7954 | 2015-08-31 15:40:01 -0700 | [diff] [blame] | 344 | errno = saved_errno; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 345 | } |
| 346 | |
yuanhao | 435e84b | 2018-01-15 15:37:02 +0800 | [diff] [blame] | 347 | // 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 350 | // have them be harvested immediately. |
| 351 | // |
yuanhao | 435e84b | 2018-01-15 15:37:02 +0800 | [diff] [blame] | 352 | // 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 362 | // This ends up being called repeatedly before each fork(), but there's |
| 363 | // no real harm in that. |
yuanhao | 435e84b | 2018-01-15 15:37:02 +0800 | [diff] [blame] | 364 | static void SetSignalHandlers() { |
| 365 | struct sigaction sig_chld = {}; |
| 366 | sig_chld.sa_handler = SigChldHandler; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 367 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 368 | if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) { |
Elliott Hughes | 960e831 | 2014-09-30 08:49:01 -0700 | [diff] [blame] | 369 | ALOGW("Error setting SIGCHLD handler: %s", strerror(errno)); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 370 | } |
yuanhao | 435e84b | 2018-01-15 15:37:02 +0800 | [diff] [blame] | 371 | |
| 372 | struct sigaction sig_hup = {}; |
| 373 | sig_hup.sa_handler = SIG_IGN; |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 374 | if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) { |
yuanhao | 435e84b | 2018-01-15 15:37:02 +0800 | [diff] [blame] | 375 | ALOGW("Error setting SIGHUP handler: %s", strerror(errno)); |
| 376 | } |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 377 | } |
| 378 | |
| 379 | // Sets the SIGCHLD handler back to default behavior in zygote children. |
yuanhao | 435e84b | 2018-01-15 15:37:02 +0800 | [diff] [blame] | 380 | static void UnsetChldSignalHandler() { |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 381 | struct sigaction sa; |
| 382 | memset(&sa, 0, sizeof(sa)); |
| 383 | sa.sa_handler = SIG_DFL; |
| 384 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 385 | if (sigaction(SIGCHLD, &sa, nullptr) < 0) { |
Elliott Hughes | 960e831 | 2014-09-30 08:49:01 -0700 | [diff] [blame] | 386 | ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno)); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 387 | } |
| 388 | } |
| 389 | |
| 390 | // Calls POSIX setgroups() using the int[] object as an argument. |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 391 | // A nullptr argument is tolerated. |
| 392 | static void SetGids(JNIEnv* env, jintArray managed_gids, fail_fn_t fail_fn) { |
| 393 | if (managed_gids == nullptr) { |
| 394 | return; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 395 | } |
| 396 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 397 | ScopedIntArrayRO gids(env, managed_gids); |
| 398 | if (gids.get() == nullptr) { |
| 399 | fail_fn(CREATE_ERROR("Getting gids int array failed")); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 400 | } |
Andreas Gampe | d5758f6 | 2018-03-12 12:08:55 -0700 | [diff] [blame] | 401 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 402 | 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 405 | } |
| 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 409 | // contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 410 | // treated as an empty array. |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 411 | static void SetRLimits(JNIEnv* env, jobjectArray managed_rlimits, fail_fn_t fail_fn) { |
| 412 | if (managed_rlimits == nullptr) { |
| 413 | return; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 414 | } |
| 415 | |
| 416 | rlimit rlim; |
| 417 | memset(&rlim, 0, sizeof(rlim)); |
| 418 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 419 | 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 426 | } |
| 427 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 428 | rlim.rlim_cur = rlimit_handle[1]; |
| 429 | rlim.rlim_max = rlimit_handle[2]; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 430 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 431 | 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
Orion Hodson | 8d005a6 | 2018-12-05 12:28:53 +0000 | [diff] [blame] | 438 | static 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 Hodson | 2b71ad0 | 2018-12-07 16:44:33 +0000 | [diff] [blame] | 455 | // 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 Hodson | 8d005a6 | 2018-12-05 12:28:53 +0000 | [diff] [blame] | 466 | } |
| 467 | } |
| 468 | } |
| 469 | |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 470 | // The debug malloc library needs to know whether it's the zygote or a child. |
| 471 | extern "C" int gMallocLeakZygoteChild; |
| 472 | |
Christopher Ferris | 76de39e | 2017-06-20 16:13:40 -0700 | [diff] [blame] | 473 | static 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 Hsieh | c8176ef | 2018-01-08 12:43:00 -0800 | [diff] [blame] | 481 | static 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 Hsieh | fa046a1 | 2018-03-28 16:26:28 -0700 | [diff] [blame] | 488 | if (uid >= AID_APP_START) { |
Victor Hsieh | c8176ef | 2018-01-08 12:43:00 -0800 | [diff] [blame] | 489 | set_app_seccomp_filter(); |
| 490 | } else { |
| 491 | set_system_seccomp_filter(); |
| 492 | } |
| 493 | } |
| 494 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 495 | static 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 498 | } |
| 499 | } |
| 500 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 501 | static 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 504 | 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 508 | fail_fn(CREATE_ERROR("prctl(PR_CAPBSET_DROP, %d) failed: %s", i, strerror(errno))); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 509 | } |
| 510 | } |
| 511 | } |
| 512 | } |
| 513 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 514 | static void SetInheritable(uint64_t inheritable, fail_fn_t fail_fn) { |
Josh Gao | 45dab78 | 2017-02-01 14:56:09 -0800 | [diff] [blame] | 515 | __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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 522 | fail_fn(CREATE_ERROR("capget failed: %s", strerror(errno))); |
Josh Gao | 45dab78 | 2017-02-01 14:56:09 -0800 | [diff] [blame] | 523 | } |
| 524 | |
| 525 | capdata[0].inheritable = inheritable; |
| 526 | capdata[1].inheritable = inheritable >> 32; |
| 527 | |
| 528 | if (capset(&capheader, &capdata[0]) == -1) { |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 529 | fail_fn(CREATE_ERROR("capset(inh=%" PRIx64 ") failed: %s", inheritable, strerror(errno))); |
Josh Gao | 45dab78 | 2017-02-01 14:56:09 -0800 | [diff] [blame] | 530 | } |
| 531 | } |
| 532 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 533 | static void SetCapabilities(uint64_t permitted, uint64_t effective, uint64_t inheritable, |
| 534 | fail_fn_t fail_fn) { |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 535 | __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 Gao | 45dab78 | 2017-02-01 14:56:09 -0800 | [diff] [blame] | 546 | capdata[0].inheritable = inheritable; |
| 547 | capdata[1].inheritable = inheritable >> 32; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 548 | |
| 549 | if (capset(&capheader, &capdata[0]) == -1) { |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 550 | fail_fn(CREATE_ERROR("capset(perm=%" PRIx64 ", eff=%" PRIx64 ", inh=%" PRIx64 ") " |
| 551 | "failed: %s", permitted, effective, inheritable, strerror(errno))); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 552 | } |
| 553 | } |
| 554 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 555 | static void SetSchedulerPolicy(fail_fn_t fail_fn) { |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 556 | errno = -set_sched_policy(0, SP_DEFAULT); |
| 557 | if (errno != 0) { |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 558 | fail_fn(CREATE_ERROR("set_sched_policy(0, SP_DEFAULT) failed: %s", strerror(errno))); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 559 | } |
| 560 | } |
| 561 | |
Jeff Sharkey | faf3f69 | 2015-06-30 15:56:33 -0700 | [diff] [blame] | 562 | static int UnmountTree(const char* path) { |
| 563 | size_t path_len = strlen(path); |
| 564 | |
| 565 | FILE* fp = setmntent("/proc/mounts", "r"); |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 566 | if (fp == nullptr) { |
Jeff Sharkey | faf3f69 | 2015-06-30 15:56:33 -0700 | [diff] [blame] | 567 | 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 575 | while ((mentry = getmntent(fp)) != nullptr) { |
Jeff Sharkey | faf3f69 | 2015-06-30 15:56:33 -0700 | [diff] [blame] | 576 | 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 Hsieh | a1b644e | 2018-12-11 11:09:20 -0800 | [diff] [blame] | 582 | for (const auto& path : toUnmount) { |
Jeff Sharkey | faf3f69 | 2015-06-30 15:56:33 -0700 | [diff] [blame] | 583 | 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 590 | // Create a private mount namespace and bind mount appropriate emulated |
| 591 | // storage for the given user. |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 592 | static void MountEmulatedStorage(uid_t uid, jint mount_mode, |
| 593 | bool force_mount_namespace, fail_fn_t fail_fn) { |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 594 | // See storage config details at http://source.android.com/tech/storage/ |
| 595 | |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 596 | String8 storageSource; |
| 597 | if (mount_mode == MOUNT_EXTERNAL_DEFAULT) { |
Jeff Sharkey | 928e1ec | 2015-08-06 11:40:21 -0700 | [diff] [blame] | 598 | storageSource = "/mnt/runtime/default"; |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 599 | } else if (mount_mode == MOUNT_EXTERNAL_READ) { |
Jeff Sharkey | 928e1ec | 2015-08-06 11:40:21 -0700 | [diff] [blame] | 600 | storageSource = "/mnt/runtime/read"; |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 601 | } else if (mount_mode == MOUNT_EXTERNAL_WRITE) { |
Jeff Sharkey | 928e1ec | 2015-08-06 11:40:21 -0700 | [diff] [blame] | 602 | storageSource = "/mnt/runtime/write"; |
Robert Sesek | 06af1c0 | 2016-11-10 21:50:04 -0500 | [diff] [blame] | 603 | } else if (!force_mount_namespace) { |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 604 | // Sane default of no storage visible |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 605 | return; |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 606 | } |
Robert Sesek | 8a3a6ff | 2016-10-31 11:25:10 -0400 | [diff] [blame] | 607 | |
| 608 | // Create a second private mount namespace for our process |
| 609 | if (unshare(CLONE_NEWNS) == -1) { |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 610 | fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno))); |
Robert Sesek | 8a3a6ff | 2016-10-31 11:25:10 -0400 | [diff] [blame] | 611 | } |
| 612 | |
Robert Sesek | 06f3930 | 2017-03-20 17:30:05 -0400 | [diff] [blame] | 613 | // Handle force_mount_namespace with MOUNT_EXTERNAL_NONE. |
| 614 | if (mount_mode == MOUNT_EXTERNAL_NONE) { |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 615 | return; |
Robert Sesek | 06f3930 | 2017-03-20 17:30:05 -0400 | [diff] [blame] | 616 | } |
| 617 | |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 618 | if (TEMP_FAILURE_RETRY(mount(storageSource.string(), "/storage", |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 619 | 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 Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 623 | } |
| 624 | |
Jeff Sharkey | faf3f69 | 2015-06-30 15:56:33 -0700 | [diff] [blame] | 625 | // Mount user-specific symlink helper into place |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 626 | 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 629 | fail_fn(CREATE_ERROR("fs_prepare_dir failed on %s (%s)", |
| 630 | userSource.string(), strerror(errno))); |
Jeff Sharkey | 9527b22 | 2015-06-24 15:24:48 -0700 | [diff] [blame] | 631 | } |
| 632 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 633 | 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 638 | } |
| 639 | |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 640 | static 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 659 | |
| 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 Kralevich | 5d5bf1f | 2019-01-25 10:24:42 -0800 | [diff] [blame] | 662 | // descriptor (if any) is closed via dup3(), replacing it with a valid |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 663 | // (open) descriptor to /dev/null. |
| 664 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 665 | static 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 Kralevich | 5d5bf1f | 2019-01-25 10:24:42 -0800 | [diff] [blame] | 670 | android::base::unique_fd devnull_fd(open("/dev/null", O_RDWR | O_CLOEXEC)); |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 671 | if (devnull_fd == -1) { |
| 672 | fail_fn(std::string("Failed to open /dev/null: ").append(strerror(errno))); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 673 | } |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 674 | |
| 675 | for (int fd : fds_to_close) { |
| 676 | ALOGV("Switching descriptor %d to /dev/null", fd); |
Nick Kralevich | 5d5bf1f | 2019-01-25 10:24:42 -0800 | [diff] [blame] | 677 | if (dup3(devnull_fd, fd, O_CLOEXEC) == -1) { |
| 678 | fail_fn(StringPrintf("Failed dup3() on descriptor %d: %s", fd, strerror(errno))); |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 679 | } |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 680 | } |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 681 | } |
| 682 | } |
| 683 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 684 | void SetThreadName(const std::string& thread_name) { |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 685 | bool hasAt = false; |
| 686 | bool hasDot = false; |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 687 | |
| 688 | for (const char str_el : thread_name) { |
| 689 | if (str_el == '.') { |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 690 | hasDot = true; |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 691 | } else if (str_el == '@') { |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 692 | hasAt = true; |
| 693 | } |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 694 | } |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 695 | |
| 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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 699 | } |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 700 | |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 701 | // pthread_setname_np fails rather than truncating long strings. |
| 702 | char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 703 | strlcpy(buf, name_start_ptr, sizeof(buf) - 1); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 704 | errno = pthread_setname_np(pthread_self(), buf); |
| 705 | if (errno != 0) { |
Elliott Hughes | 960e831 | 2014-09-30 08:49:01 -0700 | [diff] [blame] | 706 | ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno)); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 707 | } |
Andreas Gampe | 041483a | 2018-03-05 13:00:42 -0800 | [diff] [blame] | 708 | // Update base::logging default tag. |
| 709 | android::base::SetDefaultTag(buf); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 710 | } |
| 711 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 712 | /** |
| 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 722 | [[noreturn]] |
| 723 | static 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 Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 734 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 735 | 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 742 | /** |
| 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 755 | static 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 760 | return std::nullopt; |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 761 | } 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 Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 768 | } |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 769 | } |
| 770 | } |
| 771 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 772 | /** |
| 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 | */ |
| 784 | static 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 792 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 793 | 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 | */ |
| 817 | static 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 | */ |
| 836 | static 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. |
| 847 | static 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 851 | |
| 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 861 | BlockSignal(SIGCHLD, fail_fn); |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 862 | |
| 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 871 | if (gOpenFdTable == nullptr) { |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 872 | gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn); |
| 873 | } else { |
| 874 | gOpenFdTable->Restat(fds_to_ignore, fail_fn); |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 875 | } |
| 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 886 | DetachDescriptors(env, fds_to_close, fail_fn); |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 887 | |
| 888 | // Re-open all remaining open file descriptors so that they aren't shared |
| 889 | // with the zygote across a fork. |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 890 | gOpenFdTable->ReopenOrDetach(fail_fn); |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 891 | |
| 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 897 | UnblockSignal(SIGCHLD, fail_fn); |
| 898 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 899 | return pid; |
| 900 | } |
| 901 | |
| 902 | // Utility routine to specialize a zygote child process. |
| 903 | static 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 910 | 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 913 | |
| 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 Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 919 | // Keep capabilities across UID change, unless we're staying root. |
| 920 | if (uid != 0) { |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 921 | EnableKeepCapabilities(fail_fn); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 922 | } |
| 923 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 924 | SetInheritable(permitted_capabilities, fail_fn); |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 925 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 926 | DropCapabilitiesBoundingSet(fail_fn); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 927 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 928 | 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 Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 939 | use_native_bridge = false; |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 940 | ALOGW("Native bridge will not be used because managed_app_data_dir == nullptr."); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 941 | } |
| 942 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 943 | MountEmulatedStorage(uid, mount_external, use_native_bridge, fail_fn); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 944 | |
| 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 948 | const int rc = createProcessGroup(uid, getpid()); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 949 | 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 958 | SetGids(env, gids, fail_fn); |
| 959 | SetRLimits(env, rlimits, fail_fn); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 960 | |
| 961 | if (use_native_bridge) { |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 962 | // 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 Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 966 | } |
| 967 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 968 | if (setresgid(gid, gid, gid) == -1) { |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 969 | fail_fn(CREATE_ERROR("setresgid(%d) failed: %s", gid, strerror(errno))); |
| 970 | } |
| 971 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 972 | // 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 Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 977 | SetUpSeccompFilter(uid); |
| 978 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 979 | if (setresuid(uid, uid, uid) == -1) { |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 980 | 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 996 | |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 997 | 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 Hodson | 8d005a6 | 2018-12-05 12:28:53 +0000 | [diff] [blame] | 1004 | // Set process properties to enable debugging if required. |
| 1005 | if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) { |
| 1006 | EnableDebugger(); |
| 1007 | } |
| 1008 | |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1009 | 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1018 | SetCapabilities(permitted_capabilities, effective_capabilities, permitted_capabilities, fail_fn); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1019 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1020 | SetSchedulerPolicy(fail_fn); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1021 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1022 | 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 Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1028 | } |
| 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1032 | if (nice_name.has_value()) { |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1033 | SetThreadName(nice_name.value()); |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1034 | } else if (is_system_server) { |
| 1035 | SetThreadName("system_server"); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1036 | } |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1037 | |
| 1038 | // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers). |
| 1039 | UnsetChldSignalHandler(); |
| 1040 | |
Orion Hodson | 46724e7 | 2018-10-19 13:05:33 +0100 | [diff] [blame] | 1041 | 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 Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1046 | |
Orion Hodson | 46724e7 | 2018-10-19 13:05:33 +0100 | [diff] [blame] | 1047 | // 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 Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1054 | env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags, |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1055 | is_system_server, is_child_zygote, managed_instruction_set); |
| 1056 | |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1057 | if (env->ExceptionCheck()) { |
| 1058 | fail_fn("Error calling post fork hooks."); |
| 1059 | } |
| 1060 | } |
| 1061 | |
Luis Hector Chavez | 72042c9 | 2017-07-12 10:03:30 -0700 | [diff] [blame] | 1062 | static 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1074 | return capdata[0].effective | (static_cast<uint64_t>(capdata[1].effective) << 32); |
| 1075 | } |
| 1076 | |
| 1077 | static 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 VAN | c094a54 | 2018-12-07 16:52:24 +0900 | [diff] [blame] | 1096 | 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 Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1103 | /* |
| 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 Chavez | 72042c9 | 2017-07-12 10:03:30 -0700 | [diff] [blame] | 1149 | } |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1150 | |
| 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 | */ |
| 1160 | static 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 | */ |
| 1189 | static 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 | */ |
| 1203 | std::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 Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1218 | } // anonymous namespace |
| 1219 | |
| 1220 | namespace android { |
| 1221 | |
Victor Hsieh | c8176ef | 2018-01-08 12:43:00 -0800 | [diff] [blame] | 1222 | static void com_android_internal_os_Zygote_nativeSecurityInit(JNIEnv*, jclass) { |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1223 | // security_getenforce is not allowed on app process. Initialize and cache |
| 1224 | // the value before zygote forks. |
Victor Hsieh | c8176ef | 2018-01-08 12:43:00 -0800 | [diff] [blame] | 1225 | g_is_security_enforced = security_getenforce(); |
| 1226 | } |
| 1227 | |
Christopher Ferris | 76de39e | 2017-06-20 16:13:40 -0700 | [diff] [blame] | 1228 | static void com_android_internal_os_Zygote_nativePreApplicationInit(JNIEnv*, jclass) { |
| 1229 | PreApplicationInit(); |
| 1230 | } |
| 1231 | |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1232 | static jint com_android_internal_os_Zygote_nativeForkAndSpecialize( |
| 1233 | JNIEnv* env, jclass, jint uid, jint gid, jintArray gids, |
Nicolas Geoffray | 81edac4 | 2017-09-07 14:13:29 +0100 | [diff] [blame] | 1234 | jint runtime_flags, jobjectArray rlimits, |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1235 | jint mount_external, jstring se_info, jstring nice_name, |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1236 | jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote, |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1237 | jstring instruction_set, jstring app_data_dir) { |
| 1238 | jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote); |
Pavlin Radoslavov | fbd5904 | 2015-11-23 17:13:25 -0800 | [diff] [blame] | 1239 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1240 | 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 Wailes | cffbf1c | 2019-01-11 17:13:00 -0800 | [diff] [blame] | 1255 | fds_to_close.push_back(gBlastulaPoolSocketFD); |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1256 | |
| 1257 | if (gBlastulaPoolEventFD != -1) { |
| 1258 | fds_to_close.push_back(gBlastulaPoolEventFD); |
| 1259 | fds_to_ignore.push_back(gBlastulaPoolEventFD); |
| 1260 | } |
| 1261 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1262 | pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore); |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1263 | |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1264 | if (pid == 0) { |
| 1265 | SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, |
| 1266 | capabilities, capabilities, |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1267 | mount_external, se_info, nice_name, false, |
| 1268 | is_child_zygote == JNI_TRUE, instruction_set, app_data_dir); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1269 | } |
| 1270 | return pid; |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1271 | } |
| 1272 | |
| 1273 | static jint com_android_internal_os_Zygote_nativeForkSystemServer( |
| 1274 | JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids, |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1275 | jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities, |
| 1276 | jlong effective_capabilities) { |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1277 | std::vector<int> fds_to_close(MakeBlastulaPipeReadFDVector()), |
| 1278 | fds_to_ignore(fds_to_close); |
| 1279 | |
Chris Wailes | cffbf1c | 2019-01-11 17:13:00 -0800 | [diff] [blame] | 1280 | fds_to_close.push_back(gBlastulaPoolSocketFD); |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1281 | |
| 1282 | if (gBlastulaPoolEventFD != -1) { |
| 1283 | fds_to_close.push_back(gBlastulaPoolEventFD); |
| 1284 | fds_to_ignore.push_back(gBlastulaPoolEventFD); |
| 1285 | } |
| 1286 | |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1287 | pid_t pid = ForkCommon(env, true, |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1288 | fds_to_close, |
| 1289 | fds_to_ignore); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1290 | if (pid == 0) { |
| 1291 | SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1292 | permitted_capabilities, effective_capabilities, |
| 1293 | MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true, |
| 1294 | false, nullptr, nullptr); |
David Sehr | de8d0bd | 2018-06-22 10:45:36 -0700 | [diff] [blame] | 1295 | } else if (pid > 0) { |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1296 | // 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 Gampe | b053cce | 2015-11-17 16:38:59 -0800 | [diff] [blame] | 1305 | RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!"); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1306 | } |
Carmen Jackson | dd40125 | 2017-02-23 15:21:10 -0800 | [diff] [blame] | 1307 | |
Suren Baghdasaryan | 9c9b025 | 2018-12-14 10:32:22 -0800 | [diff] [blame^] | 1308 | if (UsePerAppMemcg()) { |
Minchan Kim | 696873e | 2018-06-27 11:32:40 +0900 | [diff] [blame] | 1309 | // Assign system_server to the correct memory cgroup. |
Suren Baghdasaryan | 9c9b025 | 2018-12-14 10:32:22 -0800 | [diff] [blame^] | 1310 | // Not all devices mount memcg so check if it is mounted first |
Minchan Kim | 696873e | 2018-06-27 11:32:40 +0900 | [diff] [blame] | 1311 | // to avoid unnecessarily printing errors and denials in the logs. |
Suren Baghdasaryan | 9c9b025 | 2018-12-14 10:32:22 -0800 | [diff] [blame^] | 1312 | if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) { |
| 1313 | ALOGE("couldn't add process %d into system memcg group", pid); |
Minchan Kim | 696873e | 2018-06-27 11:32:40 +0900 | [diff] [blame] | 1314 | } |
Carmen Jackson | dd40125 | 2017-02-23 15:21:10 -0800 | [diff] [blame] | 1315 | } |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1316 | } |
| 1317 | return pid; |
| 1318 | } |
| 1319 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1320 | /** |
| 1321 | * A JNI function that forks a blastula from the Zygote while ensuring proper |
| 1322 | * file descriptor hygiene. |
| 1323 | * |
| 1324 | * @param env Managed runtime environment |
| 1325 | * @param read_pipe_fd The read FD for the blastula reporting pipe. Manually closed by blastlas |
| 1326 | * in managed code. |
| 1327 | * @param write_pipe_fd The write FD for the blastula reporting pipe. Manually closed by the |
| 1328 | * zygote in managed code. |
| 1329 | * @param managed_session_socket_fds A list of anonymous session sockets that must be ignored by |
| 1330 | * the FD hygiene code and automatically "closed" in the new blastula. |
| 1331 | * @return |
| 1332 | */ |
| 1333 | static jint com_android_internal_os_Zygote_nativeForkBlastula(JNIEnv* env, jclass, |
| 1334 | jint read_pipe_fd, jint write_pipe_fd, jintArray managed_session_socket_fds) { |
| 1335 | std::vector<int> fds_to_close(MakeBlastulaPipeReadFDVector()), |
| 1336 | fds_to_ignore(fds_to_close); |
| 1337 | |
| 1338 | std::vector<int> session_socket_fds = |
| 1339 | ExtractJIntArray(env, "blastula", nullptr, managed_session_socket_fds) |
| 1340 | .value_or(std::vector<int>()); |
| 1341 | |
| 1342 | // The Blastula Pool Event FD is created during the initialization of the |
| 1343 | // blastula pool and should always be valid here. |
| 1344 | |
| 1345 | fds_to_close.push_back(gZygoteSocketFD); |
| 1346 | fds_to_close.push_back(gBlastulaPoolEventFD); |
| 1347 | fds_to_close.insert(fds_to_close.end(), session_socket_fds.begin(), session_socket_fds.end()); |
| 1348 | |
| 1349 | fds_to_ignore.push_back(gZygoteSocketFD); |
| 1350 | fds_to_ignore.push_back(gBlastulaPoolSocketFD); |
| 1351 | fds_to_ignore.push_back(gBlastulaPoolEventFD); |
| 1352 | fds_to_ignore.push_back(read_pipe_fd); |
| 1353 | fds_to_ignore.push_back(write_pipe_fd); |
| 1354 | fds_to_ignore.insert(fds_to_ignore.end(), session_socket_fds.begin(), session_socket_fds.end()); |
| 1355 | |
| 1356 | pid_t blastula_pid = ForkCommon(env, /* is_system_server= */ false, fds_to_close, fds_to_ignore); |
| 1357 | |
| 1358 | if (blastula_pid != 0) { |
| 1359 | ++gBlastulaPoolCount; |
| 1360 | AddBlastulaTableEntry(blastula_pid, read_pipe_fd); |
| 1361 | } |
| 1362 | |
| 1363 | return blastula_pid; |
| 1364 | } |
| 1365 | |
Robert Sesek | 54e387d | 2016-12-02 17:27:50 -0500 | [diff] [blame] | 1366 | static void com_android_internal_os_Zygote_nativeAllowFileAcrossFork( |
| 1367 | JNIEnv* env, jclass, jstring path) { |
| 1368 | ScopedUtfChars path_native(env, path); |
| 1369 | const char* path_cstr = path_native.c_str(); |
| 1370 | if (!path_cstr) { |
Chris Wailes | efc65b2 | 2018-10-26 12:41:54 -0700 | [diff] [blame] | 1371 | RuntimeAbort(env, __LINE__, "path_cstr == nullptr"); |
Robert Sesek | 54e387d | 2016-12-02 17:27:50 -0500 | [diff] [blame] | 1372 | } |
| 1373 | FileDescriptorWhitelist::Get()->Allow(path_cstr); |
| 1374 | } |
| 1375 | |
doheon1.lee | 885b742 | 2016-01-20 13:07:27 +0900 | [diff] [blame] | 1376 | static void com_android_internal_os_Zygote_nativeUnmountStorageOnInit(JNIEnv* env, jclass) { |
| 1377 | // Zygote process unmount root storage space initially before every child processes are forked. |
| 1378 | // Every forked child processes (include SystemServer) only mount their own root storage space |
Robert Sesek | e4f8d69 | 2016-09-13 19:13:01 -0400 | [diff] [blame] | 1379 | // and no need unmount storage operation in MountEmulatedStorage method. |
| 1380 | // Zygote process does not utilize root storage spaces and unshares its mount namespace below. |
| 1381 | |
| 1382 | // See storage config details at http://source.android.com/tech/storage/ |
| 1383 | // Create private mount namespace shared by all children |
| 1384 | if (unshare(CLONE_NEWNS) == -1) { |
| 1385 | RuntimeAbort(env, __LINE__, "Failed to unshare()"); |
| 1386 | return; |
| 1387 | } |
| 1388 | |
| 1389 | // Mark rootfs as being a slave so that changes from default |
| 1390 | // namespace only flow into our children. |
| 1391 | if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) { |
| 1392 | RuntimeAbort(env, __LINE__, "Failed to mount() rootfs as MS_SLAVE"); |
| 1393 | return; |
| 1394 | } |
| 1395 | |
| 1396 | // Create a staging tmpfs that is shared by our children; they will |
| 1397 | // bind mount storage into their respective private namespaces, which |
| 1398 | // are isolated from each other. |
| 1399 | const char* target_base = getenv("EMULATED_STORAGE_TARGET"); |
| 1400 | if (target_base != nullptr) { |
| 1401 | #define STRINGIFY_UID(x) __STRING(x) |
| 1402 | if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV, |
| 1403 | "uid=0,gid=" STRINGIFY_UID(AID_SDCARD_R) ",mode=0751") == -1) { |
| 1404 | ALOGE("Failed to mount tmpfs to %s", target_base); |
| 1405 | RuntimeAbort(env, __LINE__, "Failed to mount tmpfs"); |
| 1406 | return; |
| 1407 | } |
| 1408 | #undef STRINGIFY_UID |
| 1409 | } |
doheon1.lee | 885b742 | 2016-01-20 13:07:27 +0900 | [diff] [blame] | 1410 | |
| 1411 | UnmountTree("/storage"); |
doheon1.lee | 885b742 | 2016-01-20 13:07:27 +0900 | [diff] [blame] | 1412 | } |
| 1413 | |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1414 | /** |
| 1415 | * Called from a blastula to specialize the process for a specific application. |
| 1416 | * |
| 1417 | * @param env Managed runtime environment |
| 1418 | * @param uid User ID of the new application |
| 1419 | * @param gid Group ID of the new application |
| 1420 | * @param gids Extra groups that the process belongs to |
| 1421 | * @param runtime_flags Flags for changing the behavior of the managed runtime |
| 1422 | * @param rlimits Resource limits |
| 1423 | * @param mount_external The mode (read/write/normal) that external storage will be mounted with |
| 1424 | * @param se_info SELinux policy information |
| 1425 | * @param nice_name New name for this process |
| 1426 | * @param is_child_zygote If the process is to become a WebViewZygote |
| 1427 | * @param instruction_set The instruction set expected/requested by the new application |
| 1428 | * @param app_data_dir Path to the application's data directory |
| 1429 | */ |
| 1430 | static void com_android_internal_os_Zygote_nativeSpecializeBlastula( |
| 1431 | JNIEnv* env, jclass, jint uid, jint gid, jintArray gids, |
| 1432 | jint runtime_flags, jobjectArray rlimits, |
| 1433 | jint mount_external, jstring se_info, jstring nice_name, |
| 1434 | jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) { |
| 1435 | jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote); |
| 1436 | |
| 1437 | SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, |
| 1438 | capabilities, capabilities, |
| 1439 | mount_external, se_info, nice_name, false, |
| 1440 | is_child_zygote == JNI_TRUE, instruction_set, app_data_dir); |
| 1441 | } |
| 1442 | |
| 1443 | /** |
| 1444 | * A helper method for fetching socket file descriptors that were opened by init from the |
| 1445 | * environment. |
| 1446 | * |
| 1447 | * @param env Managed runtime environment |
| 1448 | * @param is_primary If this process is the primary or secondary Zygote; used to compute the name |
| 1449 | * of the environment variable storing the file descriptors. |
| 1450 | */ |
| 1451 | static void com_android_internal_os_Zygote_nativeGetSocketFDs(JNIEnv* env, jclass, |
| 1452 | jboolean is_primary) { |
| 1453 | std::string android_socket_prefix(ANDROID_SOCKET_PREFIX); |
| 1454 | std::string env_var_name = android_socket_prefix + (is_primary ? "zygote" : "zygote_secondary"); |
| 1455 | char* env_var_val = getenv(env_var_name.c_str()); |
| 1456 | |
| 1457 | if (env_var_val != nullptr) { |
| 1458 | gZygoteSocketFD = atoi(env_var_val); |
| 1459 | ALOGV("Zygote:zygoteSocketFD = %d", gZygoteSocketFD); |
| 1460 | } else { |
| 1461 | ALOGE("Unable to fetch Zygote socket file descriptor"); |
| 1462 | } |
| 1463 | |
| 1464 | env_var_name = android_socket_prefix + (is_primary ? "blastula_pool" : "blastula_pool_secondary"); |
| 1465 | env_var_val = getenv(env_var_name.c_str()); |
| 1466 | |
| 1467 | if (env_var_val != nullptr) { |
| 1468 | gBlastulaPoolSocketFD = atoi(env_var_val); |
| 1469 | ALOGV("Zygote:blastulaPoolSocketFD = %d", gBlastulaPoolSocketFD); |
| 1470 | } else { |
| 1471 | ALOGE("Unable to fetch Blastula pool socket file descriptor"); |
| 1472 | } |
| 1473 | } |
| 1474 | |
| 1475 | /** |
| 1476 | * @param env Managed runtime environment |
| 1477 | * @return A managed array of raw file descriptors for the read ends of the blastula reporting |
| 1478 | * pipes. |
| 1479 | */ |
| 1480 | static jintArray com_android_internal_os_Zygote_nativeGetBlastulaPipeFDs(JNIEnv* env, jclass) { |
| 1481 | std::vector<int> blastula_fds = MakeBlastulaPipeReadFDVector(); |
| 1482 | |
| 1483 | jintArray managed_blastula_fds = env->NewIntArray(blastula_fds.size()); |
| 1484 | env->SetIntArrayRegion(managed_blastula_fds, 0, blastula_fds.size(), blastula_fds.data()); |
| 1485 | |
| 1486 | return managed_blastula_fds; |
| 1487 | } |
| 1488 | |
| 1489 | /** |
| 1490 | * A JNI wrapper around RemoveBlastulaTableEntry. |
| 1491 | * |
| 1492 | * @param env Managed runtime environment |
| 1493 | * @param blastula_pid Process ID of the blastula entry to invalidate |
| 1494 | * @return True if an entry was invalidated; false otherwise. |
| 1495 | */ |
| 1496 | static jboolean com_android_internal_os_Zygote_nativeRemoveBlastulaTableEntry(JNIEnv* env, jclass, |
| 1497 | jint blastula_pid) { |
| 1498 | return RemoveBlastulaTableEntry(blastula_pid); |
| 1499 | } |
| 1500 | |
| 1501 | /** |
| 1502 | * Creates the blastula pool event FD if it doesn't exist and returns it. This is used by the |
| 1503 | * ZygoteServer poll loop to know when to re-fill the blastula pool. |
| 1504 | * |
| 1505 | * @param env Managed runtime environment |
| 1506 | * @return A raw event file descriptor used to communicate (from the signal handler) when the |
| 1507 | * Zygote receives a SIGCHLD for a blastula |
| 1508 | */ |
| 1509 | static jint com_android_internal_os_Zygote_nativeGetBlastulaPoolEventFD(JNIEnv* env, jclass) { |
| 1510 | if (gBlastulaPoolEventFD == -1) { |
| 1511 | if ((gBlastulaPoolEventFD = eventfd(0, 0)) == -1) { |
| 1512 | ZygoteFailure(env, "zygote", nullptr, StringPrintf("Unable to create eventfd: %s", strerror(errno))); |
| 1513 | } |
| 1514 | } |
| 1515 | |
| 1516 | return gBlastulaPoolEventFD; |
| 1517 | } |
| 1518 | |
| 1519 | /** |
| 1520 | * @param env Managed runtime environment |
| 1521 | * @return The number of blastulas currently in the blastula pool |
| 1522 | */ |
| 1523 | static jint com_android_internal_os_Zygote_nativeGetBlastulaPoolCount(JNIEnv* env, jclass) { |
| 1524 | return gBlastulaPoolCount; |
| 1525 | } |
| 1526 | |
Daniel Micay | 76f6a86 | 2015-09-19 17:31:01 -0400 | [diff] [blame] | 1527 | static const JNINativeMethod gMethods[] = { |
Victor Hsieh | c8176ef | 2018-01-08 12:43:00 -0800 | [diff] [blame] | 1528 | { "nativeSecurityInit", "()V", |
| 1529 | (void *) com_android_internal_os_Zygote_nativeSecurityInit }, |
Andreas Gampe | aec67dc | 2014-09-02 21:23:06 -0700 | [diff] [blame] | 1530 | { "nativeForkAndSpecialize", |
Robert Sesek | d0a190df | 2018-02-12 18:46:01 -0500 | [diff] [blame] | 1531 | "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I", |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1532 | (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize }, |
| 1533 | { "nativeForkSystemServer", "(II[II[[IJJ)I", |
doheon1.lee | 885b742 | 2016-01-20 13:07:27 +0900 | [diff] [blame] | 1534 | (void *) com_android_internal_os_Zygote_nativeForkSystemServer }, |
Robert Sesek | 54e387d | 2016-12-02 17:27:50 -0500 | [diff] [blame] | 1535 | { "nativeAllowFileAcrossFork", "(Ljava/lang/String;)V", |
| 1536 | (void *) com_android_internal_os_Zygote_nativeAllowFileAcrossFork }, |
doheon1.lee | 885b742 | 2016-01-20 13:07:27 +0900 | [diff] [blame] | 1537 | { "nativeUnmountStorageOnInit", "()V", |
Christopher Ferris | 76de39e | 2017-06-20 16:13:40 -0700 | [diff] [blame] | 1538 | (void *) com_android_internal_os_Zygote_nativeUnmountStorageOnInit }, |
| 1539 | { "nativePreApplicationInit", "()V", |
Chris Wailes | 8b35ba2 | 2019-01-10 16:55:32 -0800 | [diff] [blame] | 1540 | (void *) com_android_internal_os_Zygote_nativePreApplicationInit }, |
| 1541 | { "nativeForkBlastula", "(II[I)I", |
| 1542 | (void *) com_android_internal_os_Zygote_nativeForkBlastula }, |
| 1543 | { "nativeSpecializeBlastula", |
| 1544 | "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V", |
| 1545 | (void *) com_android_internal_os_Zygote_nativeSpecializeBlastula }, |
| 1546 | { "nativeGetSocketFDs", "(Z)V", |
| 1547 | (void *) com_android_internal_os_Zygote_nativeGetSocketFDs }, |
| 1548 | { "nativeGetBlastulaPipeFDs", "()[I", |
| 1549 | (void *) com_android_internal_os_Zygote_nativeGetBlastulaPipeFDs }, |
| 1550 | { "nativeRemoveBlastulaTableEntry", "(I)Z", |
| 1551 | (void *) com_android_internal_os_Zygote_nativeRemoveBlastulaTableEntry }, |
| 1552 | { "nativeGetBlastulaPoolEventFD", "()I", |
| 1553 | (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolEventFD }, |
| 1554 | { "nativeGetBlastulaPoolCount", "()I", |
| 1555 | (void *) com_android_internal_os_Zygote_nativeGetBlastulaPoolCount } |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1556 | }; |
| 1557 | |
| 1558 | int register_com_android_internal_os_Zygote(JNIEnv* env) { |
Andreas Gampe | ed6b9df | 2014-11-20 22:02:20 -0800 | [diff] [blame] | 1559 | gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName)); |
Orion Hodson | 46724e7 | 2018-10-19 13:05:33 +0100 | [diff] [blame] | 1560 | gCallPostForkSystemServerHooks = GetStaticMethodIDOrDie(env, gZygoteClass, |
| 1561 | "callPostForkSystemServerHooks", |
| 1562 | "()V"); |
Andreas Gampe | ed6b9df | 2014-11-20 22:02:20 -0800 | [diff] [blame] | 1563 | gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks", |
Robert Sesek | d0a190df | 2018-02-12 18:46:01 -0500 | [diff] [blame] | 1564 | "(IZZLjava/lang/String;)V"); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1565 | |
Andreas Gampe | ed6b9df | 2014-11-20 22:02:20 -0800 | [diff] [blame] | 1566 | return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods)); |
Narayan Kamath | 973b466 | 2014-03-31 13:41:26 +0100 | [diff] [blame] | 1567 | } |
| 1568 | } // namespace android |