| 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 |  | 
| Christopher Ferris | 2822856 | 2019-02-14 10:23:58 -0800 | [diff] [blame] | 214 | static void DisplayError(int) { | 
 | 215 |   error_log("Cannot install heapprofd while malloc debug/malloc hooks are enabled."); | 
 | 216 | } | 
 | 217 |  | 
 | 218 | void HeapprofdInstallErrorSignalHandler() { | 
 | 219 |   struct sigaction action = {}; | 
 | 220 |   action.sa_handler = DisplayError; | 
 | 221 |   sigaction(kHeapprofdSignal, &action, nullptr); | 
 | 222 | } | 
 | 223 |  | 
| Christopher Ferris | e4cdbc4 | 2019-02-08 17:30:58 -0800 | [diff] [blame] | 224 | static void CommonInstallHooks(libc_globals* globals) { | 
 | 225 |   void* impl_handle = atomic_load(&gHeapprofdHandle); | 
 | 226 |   bool reusing_handle = impl_handle != nullptr; | 
 | 227 |   if (!reusing_handle) { | 
 | 228 |     impl_handle = LoadSharedLibrary(kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table); | 
 | 229 |     if (impl_handle == nullptr) { | 
 | 230 |       return; | 
 | 231 |     } | 
 | 232 |   } else if (!InitSharedLibrary(impl_handle, kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table)) { | 
 | 233 |     return; | 
 | 234 |   } | 
 | 235 |  | 
 | 236 |   if (FinishInstallHooks(globals, nullptr, kHeapprofdPrefix)) { | 
 | 237 |     atomic_store(&gHeapprofdHandle, impl_handle); | 
 | 238 |   } else if (!reusing_handle) { | 
 | 239 |     dlclose(impl_handle); | 
 | 240 |   } | 
 | 241 |  | 
 | 242 |   atomic_store(&gHeapprofdInitInProgress, false); | 
 | 243 | } | 
 | 244 |  | 
 | 245 | void HeapprofdInstallHooksAtInit(libc_globals* globals) { | 
 | 246 |   if (atomic_exchange(&gHeapprofdInitInProgress, true)) { | 
 | 247 |     return; | 
 | 248 |   } | 
 | 249 |   CommonInstallHooks(globals); | 
 | 250 | } | 
 | 251 |  | 
 | 252 | static void* InitHeapprofd(void*) { | 
 | 253 |   __libc_globals.mutate([](libc_globals* globals) { | 
 | 254 |     CommonInstallHooks(globals); | 
 | 255 |   }); | 
 | 256 |  | 
 | 257 |   // Allow to install hook again to re-initialize heap profiling after the | 
 | 258 |   // current session finished. | 
 | 259 |   atomic_store(&gHeapprofdInitHookInstalled, false); | 
 | 260 |   return nullptr; | 
 | 261 | } | 
 | 262 |  | 
 | 263 | extern "C" void* MallocInitHeapprofdHook(size_t bytes) { | 
 | 264 |   if (!atomic_exchange(&gHeapprofdInitHookInstalled, true)) { | 
 | 265 |     __libc_globals.mutate([](libc_globals* globals) { | 
 | 266 |       atomic_store(&globals->current_dispatch_table, nullptr); | 
 | 267 |     }); | 
 | 268 |  | 
 | 269 |     pthread_t thread_id; | 
 | 270 |     if (pthread_create(&thread_id, nullptr, InitHeapprofd, nullptr) != 0) { | 
 | 271 |       error_log("%s: heapprofd: failed to pthread_create.", getprogname()); | 
 | 272 |     } else if (pthread_detach(thread_id) != 0) { | 
 | 273 |       error_log("%s: heapprofd: failed to pthread_detach", getprogname()); | 
 | 274 |     } | 
 | 275 |     if (pthread_setname_np(thread_id, "heapprofdinit") != 0) { | 
 | 276 |       error_log("%s: heapprod: failed to pthread_setname_np", getprogname()); | 
 | 277 |     } | 
 | 278 |   } | 
 | 279 |   return Malloc(malloc)(bytes); | 
 | 280 | } | 
 | 281 |  | 
 | 282 | // Marks this process as a profileable zygote child. | 
 | 283 | static bool HandleInitZygoteChildProfiling() { | 
 | 284 |   atomic_store_explicit(&gMallocZygoteChildProfileable, true, memory_order_release); | 
 | 285 |  | 
 | 286 |   // Conditionally start "from startup" profiling. | 
 | 287 |   if (HeapprofdShouldLoad()) { | 
 | 288 |     // Directly call the signal handler (will correctly guard against | 
 | 289 |     // concurrent signal delivery). | 
 | 290 |     MaybeInstallInitHeapprofdHook(kHeapprofdSignal); | 
 | 291 |   } | 
 | 292 |   return true; | 
 | 293 | } | 
 | 294 |  | 
 | 295 | static bool DispatchReset() { | 
 | 296 |   if (!atomic_exchange(&gHeapprofdInitInProgress, true)) { | 
 | 297 |     __libc_globals.mutate([](libc_globals* globals) { | 
 | 298 |       atomic_store(&globals->current_dispatch_table, nullptr); | 
 | 299 |     }); | 
 | 300 |     atomic_store(&gHeapprofdInitInProgress, false); | 
 | 301 |     return true; | 
 | 302 |   } | 
 | 303 |   errno = EAGAIN; | 
 | 304 |   return false; | 
 | 305 | } | 
 | 306 |  | 
 | 307 | bool HeapprofdMallopt(int opcode, void* arg, size_t arg_size) { | 
 | 308 |   if (opcode == M_INIT_ZYGOTE_CHILD_PROFILING) { | 
 | 309 |     if (arg != nullptr || arg_size != 0) { | 
 | 310 |       errno = EINVAL; | 
 | 311 |       return false; | 
 | 312 |     } | 
 | 313 |     return HandleInitZygoteChildProfiling(); | 
 | 314 |   } | 
 | 315 |   if (opcode == M_RESET_HOOKS) { | 
 | 316 |     if (arg != nullptr || arg_size != 0) { | 
 | 317 |       errno = EINVAL; | 
 | 318 |       return false; | 
 | 319 |     } | 
 | 320 |     return DispatchReset(); | 
 | 321 |   } | 
 | 322 |   errno = ENOTSUP; | 
 | 323 |   return false; | 
 | 324 | } |