blob: 3d2dc2b9c8ff053264c9c275c6904a98a378bc54 [file] [log] [blame]
Christopher Ferrise4cdbc42019-02-08 17:30:58 -08001/*
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>
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080035#include <signal.h>
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080036#include <stdio.h>
37#include <stdlib.h>
38#include <unistd.h>
39
Christopher Ferris2b0638e2019-09-11 19:05:29 -070040#include <platform/bionic/malloc.h>
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080041#include <private/bionic_config.h>
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080042#include <private/bionic_malloc_dispatch.h>
43#include <sys/system_properties.h>
44
45#include "malloc_common.h"
46#include "malloc_common_dynamic.h"
47#include "malloc_heapprofd.h"
48
49static constexpr char kHeapprofdSharedLib[] = "heapprofd_client.so";
50static constexpr char kHeapprofdPrefix[] = "heapprofd";
51static constexpr char kHeapprofdPropertyEnable[] = "heapprofd.enable";
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080052
53// The logic for triggering heapprofd (at runtime) is as follows:
Ryan Savitski175c8862020-01-02 19:54:57 +000054// 1. A reserved profiling signal is received by the process, its si_value
55// discriminating between different handlers. For the case of heapprofd,
56// HandleHeapprofdSignal is called.
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080057// 2. If the initialization is not already in flight
58// (gHeapprofdInitInProgress is false), the malloc hook is set to
59// point at InitHeapprofdHook, and gHeapprofdInitInProgress is set to
60// true.
61// 3. The next malloc call enters InitHeapprofdHook, which removes the malloc
62// hook, and spawns a detached pthread to run the InitHeapprofd task.
Ryan Savitski175c8862020-01-02 19:54:57 +000063// (gHeapprofdInitHookInstalled atomic is used to perform this once.)
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080064// 4. InitHeapprofd, on a dedicated pthread, loads the heapprofd client library,
65// installs the full set of heapprofd hooks, and invokes the client's
66// initializer. The dedicated pthread then terminates.
67// 5. gHeapprofdInitInProgress and gHeapprofdInitHookInstalled are
68// reset to false such that heapprofd can be reinitialized. Reinitialization
69// means that a new profiling session is started, and any still active is
70// torn down.
71//
72// The incremental hooking and a dedicated task thread are used since we cannot
73// do heavy work within a signal handler, or when blocking a malloc invocation.
74
75// The handle returned by dlopen when previously loading the heapprofd
76// hooks. nullptr if shared library has not been already been loaded.
77static _Atomic (void*) gHeapprofdHandle = nullptr;
78
79static _Atomic bool gHeapprofdInitInProgress = false;
80static _Atomic bool gHeapprofdInitHookInstalled = false;
81
Ryan Savitski175c8862020-01-02 19:54:57 +000082// Set to true if the process has enabled malloc_debug or malloc_hooks, which
83// are incompatible (and take precedence over) heapprofd.
84static _Atomic bool gHeapprofdIncompatibleHooks = false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080085
86extern "C" void* MallocInitHeapprofdHook(size_t);
87
88static constexpr MallocDispatch __heapprofd_init_dispatch
89 __attribute__((unused)) = {
90 Malloc(calloc),
91 Malloc(free),
92 Malloc(mallinfo),
Ryan Savitski175c8862020-01-02 19:54:57 +000093 MallocInitHeapprofdHook, // malloc replacement
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080094 Malloc(malloc_usable_size),
95 Malloc(memalign),
96 Malloc(posix_memalign),
97#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
98 Malloc(pvalloc),
99#endif
100 Malloc(realloc),
101#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
102 Malloc(valloc),
103#endif
Christopher Ferris6f517cd2019-11-08 11:28:38 -0800104 Malloc(malloc_iterate),
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800105 Malloc(malloc_disable),
106 Malloc(malloc_enable),
107 Malloc(mallopt),
108 Malloc(aligned_alloc),
Christopher Ferris6c619a02019-03-01 17:59:51 -0800109 Malloc(malloc_info),
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800110 };
111
Florian Mayerf6d221e2019-05-03 16:24:52 +0100112constexpr char kHeapprofdProgramPropertyPrefix[] = "heapprofd.enable.";
113constexpr size_t kHeapprofdProgramPropertyPrefixSize = sizeof(kHeapprofdProgramPropertyPrefix) - 1;
114constexpr size_t kMaxCmdlineSize = 512;
115
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800116static bool GetHeapprofdProgramProperty(char* data, size_t size) {
Florian Mayerf6d221e2019-05-03 16:24:52 +0100117 if (size < kHeapprofdProgramPropertyPrefixSize) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800118 error_log("%s: Overflow constructing heapprofd property", getprogname());
119 return false;
120 }
Florian Mayerf6d221e2019-05-03 16:24:52 +0100121 memcpy(data, kHeapprofdProgramPropertyPrefix, kHeapprofdProgramPropertyPrefixSize);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800122
123 int fd = open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
124 if (fd == -1) {
125 error_log("%s: Failed to open /proc/self/cmdline", getprogname());
126 return false;
127 }
Florian Mayerf6d221e2019-05-03 16:24:52 +0100128 char cmdline[kMaxCmdlineSize];
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800129 ssize_t rd = read(fd, cmdline, sizeof(cmdline) - 1);
130 close(fd);
131 if (rd == -1) {
132 error_log("%s: Failed to read /proc/self/cmdline", getprogname());
133 return false;
134 }
135 cmdline[rd] = '\0';
136 char* first_arg = static_cast<char*>(memchr(cmdline, '\0', rd));
Florian Mayerf6d221e2019-05-03 16:24:52 +0100137 if (first_arg == nullptr) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800138 error_log("%s: Overflow reading cmdline", getprogname());
139 return false;
140 }
141 // For consistency with what we do with Java app cmdlines, trim everything
142 // after the @ sign of the first arg.
143 char* first_at = static_cast<char*>(memchr(cmdline, '@', rd));
144 if (first_at != nullptr && first_at < first_arg) {
145 *first_at = '\0';
146 first_arg = first_at;
147 }
148
149 char* start = static_cast<char*>(memrchr(cmdline, '/', first_arg - cmdline));
150 if (start == first_arg) {
151 // The first argument ended in a slash.
152 error_log("%s: cmdline ends in /", getprogname());
153 return false;
154 } else if (start == nullptr) {
155 start = cmdline;
156 } else {
157 // Skip the /.
158 start++;
159 }
160
161 size_t name_size = static_cast<size_t>(first_arg - start);
Florian Mayerf6d221e2019-05-03 16:24:52 +0100162 if (name_size >= size - kHeapprofdProgramPropertyPrefixSize) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800163 error_log("%s: overflow constructing heapprofd property.", getprogname());
164 return false;
165 }
166 // + 1 to also copy the trailing null byte.
Florian Mayerf6d221e2019-05-03 16:24:52 +0100167 memcpy(data + kHeapprofdProgramPropertyPrefixSize, start, name_size + 1);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800168 return true;
169}
170
Ryan Savitski175c8862020-01-02 19:54:57 +0000171// Runtime triggering entry-point. Two possible call sites:
172// * when receiving a profiling signal with a si_value indicating heapprofd.
173// * when a Zygote child is marking itself as profileable, and there's a
174// matching profiling request for this process (in which case heapprofd client
175// is loaded synchronously).
176// In both cases, the caller is responsible for verifying that the process is
177// considered profileable.
178void HandleHeapprofdSignal() {
179 if (atomic_load_explicit(&gHeapprofdIncompatibleHooks, memory_order_acquire)) {
180 error_log("%s: not enabling heapprofd, malloc_debug/malloc_hooks are enabled.", getprogname());
181 return;
182 }
183
184 // Checking this variable is only necessary when this could conflict with
185 // the change to enable the allocation limit. All other places will
186 // not ever have a conflict modifying the globals.
187 if (!atomic_exchange(&gGlobalsMutating, true)) {
188 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
189 __libc_globals.mutate([](libc_globals* globals) {
190 atomic_store(&globals->default_dispatch_table, &__heapprofd_init_dispatch);
191 auto dispatch_table = GetDispatchTable();
192 if (dispatch_table == nullptr || dispatch_table == &globals->malloc_dispatch_table) {
193 atomic_store(&globals->current_dispatch_table, &__heapprofd_init_dispatch);
194 }
195 });
196 }
197 atomic_store(&gGlobalsMutating, false);
198 }
199 // Otherwise, we're racing against malloc_limit's enable logic (at most once
200 // per process, and a niche feature). This is highly unlikely, so simply give
201 // up if it does happen.
202}
203
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800204bool HeapprofdShouldLoad() {
205 // First check for heapprofd.enable. If it is set to "all", enable
206 // heapprofd for all processes. Otherwise, check heapprofd.enable.${prog},
207 // if it is set and not 0, enable heap profiling for this process.
208 char property_value[PROP_VALUE_MAX];
209 if (__system_property_get(kHeapprofdPropertyEnable, property_value) == 0) {
210 return false;
211 }
212 if (strcmp(property_value, "all") == 0) {
213 return true;
214 }
215
Florian Mayerf6d221e2019-05-03 16:24:52 +0100216 char program_property[kHeapprofdProgramPropertyPrefixSize + kMaxCmdlineSize];
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800217 if (!GetHeapprofdProgramProperty(program_property,
218 sizeof(program_property))) {
219 return false;
220 }
221 if (__system_property_get(program_property, property_value) == 0) {
222 return false;
223 }
Christopher Ferris503c17b2019-02-22 12:47:23 -0800224 return property_value[0] != '\0';
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800225}
226
Ryan Savitski175c8862020-01-02 19:54:57 +0000227void HeapprofdRememberHookConflict() {
228 atomic_store_explicit(&gHeapprofdIncompatibleHooks, true, memory_order_release);
Christopher Ferris28228562019-02-14 10:23:58 -0800229}
230
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800231static void CommonInstallHooks(libc_globals* globals) {
232 void* impl_handle = atomic_load(&gHeapprofdHandle);
233 bool reusing_handle = impl_handle != nullptr;
234 if (!reusing_handle) {
235 impl_handle = LoadSharedLibrary(kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table);
236 if (impl_handle == nullptr) {
237 return;
238 }
239 } else if (!InitSharedLibrary(impl_handle, kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table)) {
240 return;
241 }
242
243 if (FinishInstallHooks(globals, nullptr, kHeapprofdPrefix)) {
244 atomic_store(&gHeapprofdHandle, impl_handle);
245 } else if (!reusing_handle) {
246 dlclose(impl_handle);
247 }
248
249 atomic_store(&gHeapprofdInitInProgress, false);
250}
251
252void HeapprofdInstallHooksAtInit(libc_globals* globals) {
253 if (atomic_exchange(&gHeapprofdInitInProgress, true)) {
254 return;
255 }
256 CommonInstallHooks(globals);
257}
258
259static void* InitHeapprofd(void*) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800260 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800261 __libc_globals.mutate([](libc_globals* globals) {
262 CommonInstallHooks(globals);
263 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800264 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800265
266 // Allow to install hook again to re-initialize heap profiling after the
267 // current session finished.
268 atomic_store(&gHeapprofdInitHookInstalled, false);
269 return nullptr;
270}
271
272extern "C" void* MallocInitHeapprofdHook(size_t bytes) {
273 if (!atomic_exchange(&gHeapprofdInitHookInstalled, true)) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800274 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800275 __libc_globals.mutate([](libc_globals* globals) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800276 auto old_dispatch = GetDefaultDispatchTable();
277 atomic_store(&globals->default_dispatch_table, nullptr);
278 if (GetDispatchTable() == old_dispatch) {
279 atomic_store(&globals->current_dispatch_table, nullptr);
280 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800281 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800282 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800283
284 pthread_t thread_id;
285 if (pthread_create(&thread_id, nullptr, InitHeapprofd, nullptr) != 0) {
286 error_log("%s: heapprofd: failed to pthread_create.", getprogname());
287 } else if (pthread_detach(thread_id) != 0) {
288 error_log("%s: heapprofd: failed to pthread_detach", getprogname());
289 }
290 if (pthread_setname_np(thread_id, "heapprofdinit") != 0) {
291 error_log("%s: heapprod: failed to pthread_setname_np", getprogname());
292 }
293 }
294 return Malloc(malloc)(bytes);
295}
296
Ryan Savitski175c8862020-01-02 19:54:57 +0000297bool HeapprofdInitZygoteChildProfiling() {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800298 // Conditionally start "from startup" profiling.
299 if (HeapprofdShouldLoad()) {
Ryan Savitski175c8862020-01-02 19:54:57 +0000300 // Directly call the signal handler codepath (properly protects against
301 // concurrent invocations).
302 HandleHeapprofdSignal();
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800303 }
304 return true;
305}
306
307static bool DispatchReset() {
308 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800309 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800310 __libc_globals.mutate([](libc_globals* globals) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800311 auto old_dispatch = GetDefaultDispatchTable();
312 atomic_store(&globals->default_dispatch_table, nullptr);
313 if (GetDispatchTable() == old_dispatch) {
314 atomic_store(&globals->current_dispatch_table, nullptr);
315 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800316 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800317 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800318 atomic_store(&gHeapprofdInitInProgress, false);
319 return true;
320 }
321 errno = EAGAIN;
322 return false;
323}
324
325bool HeapprofdMallopt(int opcode, void* arg, size_t arg_size) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800326 if (opcode == M_RESET_HOOKS) {
327 if (arg != nullptr || arg_size != 0) {
328 errno = EINVAL;
329 return false;
330 }
331 return DispatchReset();
332 }
333 errno = ENOTSUP;
334 return false;
335}