blob: 9cab67abdf6156e6bdb2c633fc31e6ff86e712da [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>
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
48static constexpr char kHeapprofdSharedLib[] = "heapprofd_client.so";
49static constexpr char kHeapprofdPrefix[] = "heapprofd";
50static constexpr char kHeapprofdPropertyEnable[] = "heapprofd.enable";
51static 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.
76static _Atomic (void*) gHeapprofdHandle = nullptr;
77
78static _Atomic bool gHeapprofdInitInProgress = false;
79static _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).
86static _Atomic bool gMallocZygoteChildProfileable = false;
87
88extern "C" void* MallocInitHeapprofdHook(size_t);
89
90static 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),
Christopher Ferris6c619a02019-03-01 17:59:51 -0800111 Malloc(malloc_info),
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800112 };
113
114static void MaybeInstallInitHeapprofdHook(int) {
115 // Zygote child processes must be marked profileable.
116 if (gMallocLeakZygoteChild &&
117 !atomic_load_explicit(&gMallocZygoteChildProfileable, memory_order_acquire)) {
118 return;
119 }
120
121 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
122 __libc_globals.mutate([](libc_globals* globals) {
123 atomic_store(&globals->current_dispatch_table, &__heapprofd_init_dispatch);
124 });
125 }
126}
127
128static bool GetHeapprofdProgramProperty(char* data, size_t size) {
129 constexpr char prefix[] = "heapprofd.enable.";
130 // - 1 to skip nullbyte, which we will write later.
131 constexpr size_t prefix_size = sizeof(prefix) - 1;
132 if (size < prefix_size) {
133 error_log("%s: Overflow constructing heapprofd property", getprogname());
134 return false;
135 }
136 memcpy(data, prefix, prefix_size);
137
138 int fd = open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
139 if (fd == -1) {
140 error_log("%s: Failed to open /proc/self/cmdline", getprogname());
141 return false;
142 }
143 char cmdline[128];
144 ssize_t rd = read(fd, cmdline, sizeof(cmdline) - 1);
145 close(fd);
146 if (rd == -1) {
147 error_log("%s: Failed to read /proc/self/cmdline", getprogname());
148 return false;
149 }
150 cmdline[rd] = '\0';
151 char* first_arg = static_cast<char*>(memchr(cmdline, '\0', rd));
152 if (first_arg == nullptr || first_arg == cmdline + size - 1) {
153 error_log("%s: Overflow reading cmdline", getprogname());
154 return false;
155 }
156 // For consistency with what we do with Java app cmdlines, trim everything
157 // after the @ sign of the first arg.
158 char* first_at = static_cast<char*>(memchr(cmdline, '@', rd));
159 if (first_at != nullptr && first_at < first_arg) {
160 *first_at = '\0';
161 first_arg = first_at;
162 }
163
164 char* start = static_cast<char*>(memrchr(cmdline, '/', first_arg - cmdline));
165 if (start == first_arg) {
166 // The first argument ended in a slash.
167 error_log("%s: cmdline ends in /", getprogname());
168 return false;
169 } else if (start == nullptr) {
170 start = cmdline;
171 } else {
172 // Skip the /.
173 start++;
174 }
175
176 size_t name_size = static_cast<size_t>(first_arg - start);
177 if (name_size >= size - prefix_size) {
178 error_log("%s: overflow constructing heapprofd property.", getprogname());
179 return false;
180 }
181 // + 1 to also copy the trailing null byte.
182 memcpy(data + prefix_size, start, name_size + 1);
183 return true;
184}
185
186bool HeapprofdShouldLoad() {
187 // First check for heapprofd.enable. If it is set to "all", enable
188 // heapprofd for all processes. Otherwise, check heapprofd.enable.${prog},
189 // if it is set and not 0, enable heap profiling for this process.
190 char property_value[PROP_VALUE_MAX];
191 if (__system_property_get(kHeapprofdPropertyEnable, property_value) == 0) {
192 return false;
193 }
194 if (strcmp(property_value, "all") == 0) {
195 return true;
196 }
197
198 char program_property[128];
199 if (!GetHeapprofdProgramProperty(program_property,
200 sizeof(program_property))) {
201 return false;
202 }
203 if (__system_property_get(program_property, property_value) == 0) {
204 return false;
205 }
Christopher Ferris503c17b2019-02-22 12:47:23 -0800206 return property_value[0] != '\0';
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800207}
208
209void HeapprofdInstallSignalHandler() {
210 struct sigaction action = {};
211 action.sa_handler = MaybeInstallInitHeapprofdHook;
212 sigaction(kHeapprofdSignal, &action, nullptr);
213}
214
Christopher Ferris28228562019-02-14 10:23:58 -0800215static void DisplayError(int) {
216 error_log("Cannot install heapprofd while malloc debug/malloc hooks are enabled.");
217}
218
219void HeapprofdInstallErrorSignalHandler() {
220 struct sigaction action = {};
221 action.sa_handler = DisplayError;
222 sigaction(kHeapprofdSignal, &action, nullptr);
223}
224
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800225static void CommonInstallHooks(libc_globals* globals) {
226 void* impl_handle = atomic_load(&gHeapprofdHandle);
227 bool reusing_handle = impl_handle != nullptr;
228 if (!reusing_handle) {
229 impl_handle = LoadSharedLibrary(kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table);
230 if (impl_handle == nullptr) {
231 return;
232 }
233 } else if (!InitSharedLibrary(impl_handle, kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table)) {
234 return;
235 }
236
237 if (FinishInstallHooks(globals, nullptr, kHeapprofdPrefix)) {
238 atomic_store(&gHeapprofdHandle, impl_handle);
239 } else if (!reusing_handle) {
240 dlclose(impl_handle);
241 }
242
243 atomic_store(&gHeapprofdInitInProgress, false);
244}
245
246void HeapprofdInstallHooksAtInit(libc_globals* globals) {
247 if (atomic_exchange(&gHeapprofdInitInProgress, true)) {
248 return;
249 }
250 CommonInstallHooks(globals);
251}
252
253static void* InitHeapprofd(void*) {
254 __libc_globals.mutate([](libc_globals* globals) {
255 CommonInstallHooks(globals);
256 });
257
258 // Allow to install hook again to re-initialize heap profiling after the
259 // current session finished.
260 atomic_store(&gHeapprofdInitHookInstalled, false);
261 return nullptr;
262}
263
264extern "C" void* MallocInitHeapprofdHook(size_t bytes) {
265 if (!atomic_exchange(&gHeapprofdInitHookInstalled, true)) {
266 __libc_globals.mutate([](libc_globals* globals) {
267 atomic_store(&globals->current_dispatch_table, nullptr);
268 });
269
270 pthread_t thread_id;
271 if (pthread_create(&thread_id, nullptr, InitHeapprofd, nullptr) != 0) {
272 error_log("%s: heapprofd: failed to pthread_create.", getprogname());
273 } else if (pthread_detach(thread_id) != 0) {
274 error_log("%s: heapprofd: failed to pthread_detach", getprogname());
275 }
276 if (pthread_setname_np(thread_id, "heapprofdinit") != 0) {
277 error_log("%s: heapprod: failed to pthread_setname_np", getprogname());
278 }
279 }
280 return Malloc(malloc)(bytes);
281}
282
283// Marks this process as a profileable zygote child.
284static bool HandleInitZygoteChildProfiling() {
285 atomic_store_explicit(&gMallocZygoteChildProfileable, true, memory_order_release);
286
287 // Conditionally start "from startup" profiling.
288 if (HeapprofdShouldLoad()) {
289 // Directly call the signal handler (will correctly guard against
290 // concurrent signal delivery).
291 MaybeInstallInitHeapprofdHook(kHeapprofdSignal);
292 }
293 return true;
294}
295
296static bool DispatchReset() {
297 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
298 __libc_globals.mutate([](libc_globals* globals) {
299 atomic_store(&globals->current_dispatch_table, nullptr);
300 });
301 atomic_store(&gHeapprofdInitInProgress, false);
302 return true;
303 }
304 errno = EAGAIN;
305 return false;
306}
307
308bool HeapprofdMallopt(int opcode, void* arg, size_t arg_size) {
309 if (opcode == M_INIT_ZYGOTE_CHILD_PROFILING) {
310 if (arg != nullptr || arg_size != 0) {
311 errno = EINVAL;
312 return false;
313 }
314 return HandleInitZygoteChildProfiling();
315 }
316 if (opcode == M_RESET_HOOKS) {
317 if (arg != nullptr || arg_size != 0) {
318 errno = EINVAL;
319 return false;
320 }
321 return DispatchReset();
322 }
323 errno = ENOTSUP;
324 return false;
325}