blob: 62249fb1d87bb6533aac93c4e714e5bf46350305 [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";
52static constexpr int kHeapprofdSignal = __SIGRTMIN + 4;
53
54// The logic for triggering heapprofd (at runtime) is as follows:
55// 1. HEAPPROFD_SIGNAL is received by the process, entering the
56// MaybeInstallInitHeapprofdHook signal handler.
57// 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.
63// (gHeapprofdInitHook_installed atomic is used to perform this once.)
64// 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
82// In a Zygote child process, this is set to true if profiling of this process
83// is allowed. Note that this is set at a later time than the global
Christopher Ferris8189e772019-04-09 16:37:23 -070084// gZygoteChild. The latter is set during the fork (while still in
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080085// zygote's SELinux domain). While this bit is set after the child is
86// specialized (and has transferred SELinux domains if applicable).
Christopher Ferris8189e772019-04-09 16:37:23 -070087static _Atomic bool gZygoteChildProfileable = false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080088
89extern "C" void* MallocInitHeapprofdHook(size_t);
90
91static constexpr MallocDispatch __heapprofd_init_dispatch
92 __attribute__((unused)) = {
93 Malloc(calloc),
94 Malloc(free),
95 Malloc(mallinfo),
96 MallocInitHeapprofdHook,
97 Malloc(malloc_usable_size),
98 Malloc(memalign),
99 Malloc(posix_memalign),
100#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
101 Malloc(pvalloc),
102#endif
103 Malloc(realloc),
104#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
105 Malloc(valloc),
106#endif
107 Malloc(iterate),
108 Malloc(malloc_disable),
109 Malloc(malloc_enable),
110 Malloc(mallopt),
111 Malloc(aligned_alloc),
Christopher Ferris6c619a02019-03-01 17:59:51 -0800112 Malloc(malloc_info),
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800113 };
114
115static void MaybeInstallInitHeapprofdHook(int) {
116 // Zygote child processes must be marked profileable.
Christopher Ferris8189e772019-04-09 16:37:23 -0700117 if (gZygoteChild &&
118 !atomic_load_explicit(&gZygoteChildProfileable, memory_order_acquire)) {
Florian Mayer9fc95092019-05-29 10:31:17 +0100119 error_log("%s: not enabling heapprofd, not marked profileable.", getprogname());
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800120 return;
121 }
122
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800123 // Checking this variable is only necessary when this could conflict with
124 // the change to enable the allocation limit. All other places will
125 // not ever have a conflict modifying the globals.
126 if (!atomic_exchange(&gGlobalsMutating, true)) {
127 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
128 __libc_globals.mutate([](libc_globals* globals) {
129 atomic_store(&globals->default_dispatch_table, &__heapprofd_init_dispatch);
130 auto dispatch_table = GetDispatchTable();
131 if (dispatch_table == nullptr || dispatch_table == &globals->malloc_dispatch_table) {
132 atomic_store(&globals->current_dispatch_table, &__heapprofd_init_dispatch);
133 }
134 });
135 }
136 atomic_store(&gGlobalsMutating, false);
137 } else {
138 // The only way you can get to this point is if the signal has been
139 // blocked by a call to HeapprofdMaskSignal. The raise below will
140 // do nothing until a call to HeapprofdUnmaskSignal, which will cause
141 // the signal to be resent. Using this avoids the need for a busy loop
142 // waiting for gGlobalsMutating to change back to false.
143 raise(kHeapprofdSignal);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800144 }
145}
146
Florian Mayerf6d221e2019-05-03 16:24:52 +0100147constexpr char kHeapprofdProgramPropertyPrefix[] = "heapprofd.enable.";
148constexpr size_t kHeapprofdProgramPropertyPrefixSize = sizeof(kHeapprofdProgramPropertyPrefix) - 1;
149constexpr size_t kMaxCmdlineSize = 512;
150
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800151static bool GetHeapprofdProgramProperty(char* data, size_t size) {
Florian Mayerf6d221e2019-05-03 16:24:52 +0100152 if (size < kHeapprofdProgramPropertyPrefixSize) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800153 error_log("%s: Overflow constructing heapprofd property", getprogname());
154 return false;
155 }
Florian Mayerf6d221e2019-05-03 16:24:52 +0100156 memcpy(data, kHeapprofdProgramPropertyPrefix, kHeapprofdProgramPropertyPrefixSize);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800157
158 int fd = open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
159 if (fd == -1) {
160 error_log("%s: Failed to open /proc/self/cmdline", getprogname());
161 return false;
162 }
Florian Mayerf6d221e2019-05-03 16:24:52 +0100163 char cmdline[kMaxCmdlineSize];
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800164 ssize_t rd = read(fd, cmdline, sizeof(cmdline) - 1);
165 close(fd);
166 if (rd == -1) {
167 error_log("%s: Failed to read /proc/self/cmdline", getprogname());
168 return false;
169 }
170 cmdline[rd] = '\0';
171 char* first_arg = static_cast<char*>(memchr(cmdline, '\0', rd));
Florian Mayerf6d221e2019-05-03 16:24:52 +0100172 if (first_arg == nullptr) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800173 error_log("%s: Overflow reading cmdline", getprogname());
174 return false;
175 }
176 // For consistency with what we do with Java app cmdlines, trim everything
177 // after the @ sign of the first arg.
178 char* first_at = static_cast<char*>(memchr(cmdline, '@', rd));
179 if (first_at != nullptr && first_at < first_arg) {
180 *first_at = '\0';
181 first_arg = first_at;
182 }
183
184 char* start = static_cast<char*>(memrchr(cmdline, '/', first_arg - cmdline));
185 if (start == first_arg) {
186 // The first argument ended in a slash.
187 error_log("%s: cmdline ends in /", getprogname());
188 return false;
189 } else if (start == nullptr) {
190 start = cmdline;
191 } else {
192 // Skip the /.
193 start++;
194 }
195
196 size_t name_size = static_cast<size_t>(first_arg - start);
Florian Mayerf6d221e2019-05-03 16:24:52 +0100197 if (name_size >= size - kHeapprofdProgramPropertyPrefixSize) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800198 error_log("%s: overflow constructing heapprofd property.", getprogname());
199 return false;
200 }
201 // + 1 to also copy the trailing null byte.
Florian Mayerf6d221e2019-05-03 16:24:52 +0100202 memcpy(data + kHeapprofdProgramPropertyPrefixSize, start, name_size + 1);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800203 return true;
204}
205
206bool HeapprofdShouldLoad() {
207 // First check for heapprofd.enable. If it is set to "all", enable
208 // heapprofd for all processes. Otherwise, check heapprofd.enable.${prog},
209 // if it is set and not 0, enable heap profiling for this process.
210 char property_value[PROP_VALUE_MAX];
211 if (__system_property_get(kHeapprofdPropertyEnable, property_value) == 0) {
212 return false;
213 }
214 if (strcmp(property_value, "all") == 0) {
215 return true;
216 }
217
Florian Mayerf6d221e2019-05-03 16:24:52 +0100218 char program_property[kHeapprofdProgramPropertyPrefixSize + kMaxCmdlineSize];
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800219 if (!GetHeapprofdProgramProperty(program_property,
220 sizeof(program_property))) {
221 return false;
222 }
223 if (__system_property_get(program_property, property_value) == 0) {
224 return false;
225 }
Christopher Ferris503c17b2019-02-22 12:47:23 -0800226 return property_value[0] != '\0';
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800227}
228
229void HeapprofdInstallSignalHandler() {
230 struct sigaction action = {};
231 action.sa_handler = MaybeInstallInitHeapprofdHook;
232 sigaction(kHeapprofdSignal, &action, nullptr);
233}
234
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800235extern "C" int __rt_sigprocmask(int, const sigset64_t*, sigset64_t*, size_t);
236
237void HeapprofdMaskSignal() {
238 sigset64_t mask_set;
239 // Need to use this function instead because sigprocmask64 filters
240 // out this signal.
241 __rt_sigprocmask(SIG_SETMASK, nullptr, &mask_set, sizeof(mask_set));
242 sigaddset64(&mask_set, kHeapprofdSignal);
243 __rt_sigprocmask(SIG_SETMASK, &mask_set, nullptr, sizeof(mask_set));
244}
245
246void HeapprofdUnmaskSignal() {
247 sigset64_t mask_set;
248 __rt_sigprocmask(SIG_SETMASK, nullptr, &mask_set, sizeof(mask_set));
249 sigdelset64(&mask_set, kHeapprofdSignal);
250 __rt_sigprocmask(SIG_SETMASK, &mask_set, nullptr, sizeof(mask_set));
251}
252
Christopher Ferris28228562019-02-14 10:23:58 -0800253static void DisplayError(int) {
254 error_log("Cannot install heapprofd while malloc debug/malloc hooks are enabled.");
255}
256
257void HeapprofdInstallErrorSignalHandler() {
258 struct sigaction action = {};
259 action.sa_handler = DisplayError;
260 sigaction(kHeapprofdSignal, &action, nullptr);
261}
262
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800263static void CommonInstallHooks(libc_globals* globals) {
264 void* impl_handle = atomic_load(&gHeapprofdHandle);
265 bool reusing_handle = impl_handle != nullptr;
266 if (!reusing_handle) {
267 impl_handle = LoadSharedLibrary(kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table);
268 if (impl_handle == nullptr) {
269 return;
270 }
271 } else if (!InitSharedLibrary(impl_handle, kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table)) {
272 return;
273 }
274
275 if (FinishInstallHooks(globals, nullptr, kHeapprofdPrefix)) {
276 atomic_store(&gHeapprofdHandle, impl_handle);
277 } else if (!reusing_handle) {
278 dlclose(impl_handle);
279 }
280
281 atomic_store(&gHeapprofdInitInProgress, false);
282}
283
284void HeapprofdInstallHooksAtInit(libc_globals* globals) {
285 if (atomic_exchange(&gHeapprofdInitInProgress, true)) {
286 return;
287 }
288 CommonInstallHooks(globals);
289}
290
291static void* InitHeapprofd(void*) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800292 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800293 __libc_globals.mutate([](libc_globals* globals) {
294 CommonInstallHooks(globals);
295 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800296 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800297
298 // Allow to install hook again to re-initialize heap profiling after the
299 // current session finished.
300 atomic_store(&gHeapprofdInitHookInstalled, false);
301 return nullptr;
302}
303
304extern "C" void* MallocInitHeapprofdHook(size_t bytes) {
305 if (!atomic_exchange(&gHeapprofdInitHookInstalled, true)) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800306 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800307 __libc_globals.mutate([](libc_globals* globals) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800308 auto old_dispatch = GetDefaultDispatchTable();
309 atomic_store(&globals->default_dispatch_table, nullptr);
310 if (GetDispatchTable() == old_dispatch) {
311 atomic_store(&globals->current_dispatch_table, nullptr);
312 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800313 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800314 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800315
316 pthread_t thread_id;
317 if (pthread_create(&thread_id, nullptr, InitHeapprofd, nullptr) != 0) {
318 error_log("%s: heapprofd: failed to pthread_create.", getprogname());
319 } else if (pthread_detach(thread_id) != 0) {
320 error_log("%s: heapprofd: failed to pthread_detach", getprogname());
321 }
322 if (pthread_setname_np(thread_id, "heapprofdinit") != 0) {
323 error_log("%s: heapprod: failed to pthread_setname_np", getprogname());
324 }
325 }
326 return Malloc(malloc)(bytes);
327}
328
329// Marks this process as a profileable zygote child.
330static bool HandleInitZygoteChildProfiling() {
Christopher Ferris8189e772019-04-09 16:37:23 -0700331 atomic_store_explicit(&gZygoteChildProfileable, true, memory_order_release);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800332
333 // Conditionally start "from startup" profiling.
334 if (HeapprofdShouldLoad()) {
335 // Directly call the signal handler (will correctly guard against
336 // concurrent signal delivery).
337 MaybeInstallInitHeapprofdHook(kHeapprofdSignal);
338 }
339 return true;
340}
341
342static bool DispatchReset() {
343 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800344 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800345 __libc_globals.mutate([](libc_globals* globals) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800346 auto old_dispatch = GetDefaultDispatchTable();
347 atomic_store(&globals->default_dispatch_table, nullptr);
348 if (GetDispatchTable() == old_dispatch) {
349 atomic_store(&globals->current_dispatch_table, nullptr);
350 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800351 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800352 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800353 atomic_store(&gHeapprofdInitInProgress, false);
354 return true;
355 }
356 errno = EAGAIN;
357 return false;
358}
359
360bool HeapprofdMallopt(int opcode, void* arg, size_t arg_size) {
361 if (opcode == M_INIT_ZYGOTE_CHILD_PROFILING) {
362 if (arg != nullptr || arg_size != 0) {
363 errno = EINVAL;
364 return false;
365 }
366 return HandleInitZygoteChildProfiling();
367 }
368 if (opcode == M_RESET_HOOKS) {
369 if (arg != nullptr || arg_size != 0) {
370 errno = EINVAL;
371 return false;
372 }
373 return DispatchReset();
374 }
375 errno = ENOTSUP;
376 return false;
377}