Christopher Ferris | e4cdbc4 | 2019-02-08 17:30:58 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2019 The Android Open Source Project |
| 3 | * All rights reserved. |
| 4 | * |
| 5 | * Redistribution and use in source and binary forms, with or without |
| 6 | * modification, are permitted provided that the following conditions |
| 7 | * are met: |
| 8 | * * Redistributions of source code must retain the above copyright |
| 9 | * notice, this list of conditions and the following disclaimer. |
| 10 | * * Redistributions in binary form must reproduce the above copyright |
| 11 | * notice, this list of conditions and the following disclaimer in |
| 12 | * the documentation and/or other materials provided with the |
| 13 | * distribution. |
| 14 | * |
| 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 16 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 17 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
| 18 | * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
| 19 | * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 20 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
| 21 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS |
| 22 | * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
| 23 | * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 24 | * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT |
| 25 | * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF |
| 26 | * SUCH DAMAGE. |
| 27 | */ |
| 28 | |
| 29 | #if defined(LIBC_STATIC) |
| 30 | #error This file should not be compiled for static targets. |
| 31 | #endif |
| 32 | |
| 33 | #include <dlfcn.h> |
| 34 | #include <fcntl.h> |
| 35 | #include <stdio.h> |
| 36 | #include <stdlib.h> |
| 37 | #include <unistd.h> |
| 38 | |
| 39 | #include <private/bionic_config.h> |
| 40 | #include <private/bionic_malloc.h> |
| 41 | #include <private/bionic_malloc_dispatch.h> |
| 42 | #include <sys/system_properties.h> |
| 43 | |
| 44 | #include "malloc_common.h" |
| 45 | #include "malloc_common_dynamic.h" |
| 46 | #include "malloc_heapprofd.h" |
| 47 | |
| 48 | static constexpr char kHeapprofdSharedLib[] = "heapprofd_client.so"; |
| 49 | static constexpr char kHeapprofdPrefix[] = "heapprofd"; |
| 50 | static constexpr char kHeapprofdPropertyEnable[] = "heapprofd.enable"; |
| 51 | static constexpr int kHeapprofdSignal = __SIGRTMIN + 4; |
| 52 | |
| 53 | // The logic for triggering heapprofd (at runtime) is as follows: |
| 54 | // 1. HEAPPROFD_SIGNAL is received by the process, entering the |
| 55 | // MaybeInstallInitHeapprofdHook signal handler. |
| 56 | // 2. If the initialization is not already in flight |
| 57 | // (gHeapprofdInitInProgress is false), the malloc hook is set to |
| 58 | // point at InitHeapprofdHook, and gHeapprofdInitInProgress is set to |
| 59 | // true. |
| 60 | // 3. The next malloc call enters InitHeapprofdHook, which removes the malloc |
| 61 | // hook, and spawns a detached pthread to run the InitHeapprofd task. |
| 62 | // (gHeapprofdInitHook_installed atomic is used to perform this once.) |
| 63 | // 4. InitHeapprofd, on a dedicated pthread, loads the heapprofd client library, |
| 64 | // installs the full set of heapprofd hooks, and invokes the client's |
| 65 | // initializer. The dedicated pthread then terminates. |
| 66 | // 5. gHeapprofdInitInProgress and gHeapprofdInitHookInstalled are |
| 67 | // reset to false such that heapprofd can be reinitialized. Reinitialization |
| 68 | // means that a new profiling session is started, and any still active is |
| 69 | // torn down. |
| 70 | // |
| 71 | // The incremental hooking and a dedicated task thread are used since we cannot |
| 72 | // do heavy work within a signal handler, or when blocking a malloc invocation. |
| 73 | |
| 74 | // The handle returned by dlopen when previously loading the heapprofd |
| 75 | // hooks. nullptr if shared library has not been already been loaded. |
| 76 | static _Atomic (void*) gHeapprofdHandle = nullptr; |
| 77 | |
| 78 | static _Atomic bool gHeapprofdInitInProgress = false; |
| 79 | static _Atomic bool gHeapprofdInitHookInstalled = false; |
| 80 | |
| 81 | // In a Zygote child process, this is set to true if profiling of this process |
| 82 | // is allowed. Note that this is set at a later time than the global |
| 83 | // gMallocLeakZygoteChild. The latter is set during the fork (while still in |
| 84 | // zygote's SELinux domain). While this bit is set after the child is |
| 85 | // specialized (and has transferred SELinux domains if applicable). |
| 86 | static _Atomic bool gMallocZygoteChildProfileable = false; |
| 87 | |
| 88 | extern "C" void* MallocInitHeapprofdHook(size_t); |
| 89 | |
| 90 | static constexpr MallocDispatch __heapprofd_init_dispatch |
| 91 | __attribute__((unused)) = { |
| 92 | Malloc(calloc), |
| 93 | Malloc(free), |
| 94 | Malloc(mallinfo), |
| 95 | MallocInitHeapprofdHook, |
| 96 | Malloc(malloc_usable_size), |
| 97 | Malloc(memalign), |
| 98 | Malloc(posix_memalign), |
| 99 | #if defined(HAVE_DEPRECATED_MALLOC_FUNCS) |
| 100 | Malloc(pvalloc), |
| 101 | #endif |
| 102 | Malloc(realloc), |
| 103 | #if defined(HAVE_DEPRECATED_MALLOC_FUNCS) |
| 104 | Malloc(valloc), |
| 105 | #endif |
| 106 | Malloc(iterate), |
| 107 | Malloc(malloc_disable), |
| 108 | Malloc(malloc_enable), |
| 109 | Malloc(mallopt), |
| 110 | Malloc(aligned_alloc), |
| 111 | }; |
| 112 | |
| 113 | static void MaybeInstallInitHeapprofdHook(int) { |
| 114 | // Zygote child processes must be marked profileable. |
| 115 | if (gMallocLeakZygoteChild && |
| 116 | !atomic_load_explicit(&gMallocZygoteChildProfileable, memory_order_acquire)) { |
| 117 | return; |
| 118 | } |
| 119 | |
| 120 | if (!atomic_exchange(&gHeapprofdInitInProgress, true)) { |
| 121 | __libc_globals.mutate([](libc_globals* globals) { |
| 122 | atomic_store(&globals->current_dispatch_table, &__heapprofd_init_dispatch); |
| 123 | }); |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | static bool GetHeapprofdProgramProperty(char* data, size_t size) { |
| 128 | constexpr char prefix[] = "heapprofd.enable."; |
| 129 | // - 1 to skip nullbyte, which we will write later. |
| 130 | constexpr size_t prefix_size = sizeof(prefix) - 1; |
| 131 | if (size < prefix_size) { |
| 132 | error_log("%s: Overflow constructing heapprofd property", getprogname()); |
| 133 | return false; |
| 134 | } |
| 135 | memcpy(data, prefix, prefix_size); |
| 136 | |
| 137 | int fd = open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC); |
| 138 | if (fd == -1) { |
| 139 | error_log("%s: Failed to open /proc/self/cmdline", getprogname()); |
| 140 | return false; |
| 141 | } |
| 142 | char cmdline[128]; |
| 143 | ssize_t rd = read(fd, cmdline, sizeof(cmdline) - 1); |
| 144 | close(fd); |
| 145 | if (rd == -1) { |
| 146 | error_log("%s: Failed to read /proc/self/cmdline", getprogname()); |
| 147 | return false; |
| 148 | } |
| 149 | cmdline[rd] = '\0'; |
| 150 | char* first_arg = static_cast<char*>(memchr(cmdline, '\0', rd)); |
| 151 | if (first_arg == nullptr || first_arg == cmdline + size - 1) { |
| 152 | error_log("%s: Overflow reading cmdline", getprogname()); |
| 153 | return false; |
| 154 | } |
| 155 | // For consistency with what we do with Java app cmdlines, trim everything |
| 156 | // after the @ sign of the first arg. |
| 157 | char* first_at = static_cast<char*>(memchr(cmdline, '@', rd)); |
| 158 | if (first_at != nullptr && first_at < first_arg) { |
| 159 | *first_at = '\0'; |
| 160 | first_arg = first_at; |
| 161 | } |
| 162 | |
| 163 | char* start = static_cast<char*>(memrchr(cmdline, '/', first_arg - cmdline)); |
| 164 | if (start == first_arg) { |
| 165 | // The first argument ended in a slash. |
| 166 | error_log("%s: cmdline ends in /", getprogname()); |
| 167 | return false; |
| 168 | } else if (start == nullptr) { |
| 169 | start = cmdline; |
| 170 | } else { |
| 171 | // Skip the /. |
| 172 | start++; |
| 173 | } |
| 174 | |
| 175 | size_t name_size = static_cast<size_t>(first_arg - start); |
| 176 | if (name_size >= size - prefix_size) { |
| 177 | error_log("%s: overflow constructing heapprofd property.", getprogname()); |
| 178 | return false; |
| 179 | } |
| 180 | // + 1 to also copy the trailing null byte. |
| 181 | memcpy(data + prefix_size, start, name_size + 1); |
| 182 | return true; |
| 183 | } |
| 184 | |
| 185 | bool HeapprofdShouldLoad() { |
| 186 | // First check for heapprofd.enable. If it is set to "all", enable |
| 187 | // heapprofd for all processes. Otherwise, check heapprofd.enable.${prog}, |
| 188 | // if it is set and not 0, enable heap profiling for this process. |
| 189 | char property_value[PROP_VALUE_MAX]; |
| 190 | if (__system_property_get(kHeapprofdPropertyEnable, property_value) == 0) { |
| 191 | return false; |
| 192 | } |
| 193 | if (strcmp(property_value, "all") == 0) { |
| 194 | return true; |
| 195 | } |
| 196 | |
| 197 | char program_property[128]; |
| 198 | if (!GetHeapprofdProgramProperty(program_property, |
| 199 | sizeof(program_property))) { |
| 200 | return false; |
| 201 | } |
| 202 | if (__system_property_get(program_property, property_value) == 0) { |
| 203 | return false; |
| 204 | } |
| 205 | return program_property[0] != '\0'; |
| 206 | } |
| 207 | |
| 208 | void HeapprofdInstallSignalHandler() { |
| 209 | struct sigaction action = {}; |
| 210 | action.sa_handler = MaybeInstallInitHeapprofdHook; |
| 211 | sigaction(kHeapprofdSignal, &action, nullptr); |
| 212 | } |
| 213 | |
| 214 | static void CommonInstallHooks(libc_globals* globals) { |
| 215 | void* impl_handle = atomic_load(&gHeapprofdHandle); |
| 216 | bool reusing_handle = impl_handle != nullptr; |
| 217 | if (!reusing_handle) { |
| 218 | impl_handle = LoadSharedLibrary(kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table); |
| 219 | if (impl_handle == nullptr) { |
| 220 | return; |
| 221 | } |
| 222 | } else if (!InitSharedLibrary(impl_handle, kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table)) { |
| 223 | return; |
| 224 | } |
| 225 | |
| 226 | if (FinishInstallHooks(globals, nullptr, kHeapprofdPrefix)) { |
| 227 | atomic_store(&gHeapprofdHandle, impl_handle); |
| 228 | } else if (!reusing_handle) { |
| 229 | dlclose(impl_handle); |
| 230 | } |
| 231 | |
| 232 | atomic_store(&gHeapprofdInitInProgress, false); |
| 233 | } |
| 234 | |
| 235 | void HeapprofdInstallHooksAtInit(libc_globals* globals) { |
| 236 | if (atomic_exchange(&gHeapprofdInitInProgress, true)) { |
| 237 | return; |
| 238 | } |
| 239 | CommonInstallHooks(globals); |
| 240 | } |
| 241 | |
| 242 | static void* InitHeapprofd(void*) { |
| 243 | __libc_globals.mutate([](libc_globals* globals) { |
| 244 | CommonInstallHooks(globals); |
| 245 | }); |
| 246 | |
| 247 | // Allow to install hook again to re-initialize heap profiling after the |
| 248 | // current session finished. |
| 249 | atomic_store(&gHeapprofdInitHookInstalled, false); |
| 250 | return nullptr; |
| 251 | } |
| 252 | |
| 253 | extern "C" void* MallocInitHeapprofdHook(size_t bytes) { |
| 254 | if (!atomic_exchange(&gHeapprofdInitHookInstalled, true)) { |
| 255 | __libc_globals.mutate([](libc_globals* globals) { |
| 256 | atomic_store(&globals->current_dispatch_table, nullptr); |
| 257 | }); |
| 258 | |
| 259 | pthread_t thread_id; |
| 260 | if (pthread_create(&thread_id, nullptr, InitHeapprofd, nullptr) != 0) { |
| 261 | error_log("%s: heapprofd: failed to pthread_create.", getprogname()); |
| 262 | } else if (pthread_detach(thread_id) != 0) { |
| 263 | error_log("%s: heapprofd: failed to pthread_detach", getprogname()); |
| 264 | } |
| 265 | if (pthread_setname_np(thread_id, "heapprofdinit") != 0) { |
| 266 | error_log("%s: heapprod: failed to pthread_setname_np", getprogname()); |
| 267 | } |
| 268 | } |
| 269 | return Malloc(malloc)(bytes); |
| 270 | } |
| 271 | |
| 272 | // Marks this process as a profileable zygote child. |
| 273 | static bool HandleInitZygoteChildProfiling() { |
| 274 | atomic_store_explicit(&gMallocZygoteChildProfileable, true, memory_order_release); |
| 275 | |
| 276 | // Conditionally start "from startup" profiling. |
| 277 | if (HeapprofdShouldLoad()) { |
| 278 | // Directly call the signal handler (will correctly guard against |
| 279 | // concurrent signal delivery). |
| 280 | MaybeInstallInitHeapprofdHook(kHeapprofdSignal); |
| 281 | } |
| 282 | return true; |
| 283 | } |
| 284 | |
| 285 | static bool DispatchReset() { |
| 286 | if (!atomic_exchange(&gHeapprofdInitInProgress, true)) { |
| 287 | __libc_globals.mutate([](libc_globals* globals) { |
| 288 | atomic_store(&globals->current_dispatch_table, nullptr); |
| 289 | }); |
| 290 | atomic_store(&gHeapprofdInitInProgress, false); |
| 291 | return true; |
| 292 | } |
| 293 | errno = EAGAIN; |
| 294 | return false; |
| 295 | } |
| 296 | |
| 297 | bool HeapprofdMallopt(int opcode, void* arg, size_t arg_size) { |
| 298 | if (opcode == M_INIT_ZYGOTE_CHILD_PROFILING) { |
| 299 | if (arg != nullptr || arg_size != 0) { |
| 300 | errno = EINVAL; |
| 301 | return false; |
| 302 | } |
| 303 | return HandleInitZygoteChildProfiling(); |
| 304 | } |
| 305 | if (opcode == M_RESET_HOOKS) { |
| 306 | if (arg != nullptr || arg_size != 0) { |
| 307 | errno = EINVAL; |
| 308 | return false; |
| 309 | } |
| 310 | return DispatchReset(); |
| 311 | } |
| 312 | errno = ENOTSUP; |
| 313 | return false; |
| 314 | } |