blob: 2aeb9bfee81c2ec296ed419e9f396ec0fb057803 [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
40#include <private/bionic_config.h>
41#include <private/bionic_malloc.h>
42#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)) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800119 return;
120 }
121
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800122 // Checking this variable is only necessary when this could conflict with
123 // the change to enable the allocation limit. All other places will
124 // not ever have a conflict modifying the globals.
125 if (!atomic_exchange(&gGlobalsMutating, true)) {
126 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
127 __libc_globals.mutate([](libc_globals* globals) {
128 atomic_store(&globals->default_dispatch_table, &__heapprofd_init_dispatch);
129 auto dispatch_table = GetDispatchTable();
130 if (dispatch_table == nullptr || dispatch_table == &globals->malloc_dispatch_table) {
131 atomic_store(&globals->current_dispatch_table, &__heapprofd_init_dispatch);
132 }
133 });
134 }
135 atomic_store(&gGlobalsMutating, false);
136 } else {
137 // The only way you can get to this point is if the signal has been
138 // blocked by a call to HeapprofdMaskSignal. The raise below will
139 // do nothing until a call to HeapprofdUnmaskSignal, which will cause
140 // the signal to be resent. Using this avoids the need for a busy loop
141 // waiting for gGlobalsMutating to change back to false.
142 raise(kHeapprofdSignal);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800143 }
144}
145
146static bool GetHeapprofdProgramProperty(char* data, size_t size) {
147 constexpr char prefix[] = "heapprofd.enable.";
148 // - 1 to skip nullbyte, which we will write later.
149 constexpr size_t prefix_size = sizeof(prefix) - 1;
150 if (size < prefix_size) {
151 error_log("%s: Overflow constructing heapprofd property", getprogname());
152 return false;
153 }
154 memcpy(data, prefix, prefix_size);
155
156 int fd = open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
157 if (fd == -1) {
158 error_log("%s: Failed to open /proc/self/cmdline", getprogname());
159 return false;
160 }
161 char cmdline[128];
162 ssize_t rd = read(fd, cmdline, sizeof(cmdline) - 1);
163 close(fd);
164 if (rd == -1) {
165 error_log("%s: Failed to read /proc/self/cmdline", getprogname());
166 return false;
167 }
168 cmdline[rd] = '\0';
169 char* first_arg = static_cast<char*>(memchr(cmdline, '\0', rd));
170 if (first_arg == nullptr || first_arg == cmdline + size - 1) {
171 error_log("%s: Overflow reading cmdline", getprogname());
172 return false;
173 }
174 // For consistency with what we do with Java app cmdlines, trim everything
175 // after the @ sign of the first arg.
176 char* first_at = static_cast<char*>(memchr(cmdline, '@', rd));
177 if (first_at != nullptr && first_at < first_arg) {
178 *first_at = '\0';
179 first_arg = first_at;
180 }
181
182 char* start = static_cast<char*>(memrchr(cmdline, '/', first_arg - cmdline));
183 if (start == first_arg) {
184 // The first argument ended in a slash.
185 error_log("%s: cmdline ends in /", getprogname());
186 return false;
187 } else if (start == nullptr) {
188 start = cmdline;
189 } else {
190 // Skip the /.
191 start++;
192 }
193
194 size_t name_size = static_cast<size_t>(first_arg - start);
195 if (name_size >= size - prefix_size) {
196 error_log("%s: overflow constructing heapprofd property.", getprogname());
197 return false;
198 }
199 // + 1 to also copy the trailing null byte.
200 memcpy(data + prefix_size, start, name_size + 1);
201 return true;
202}
203
204bool 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
216 char program_property[128];
217 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
227void HeapprofdInstallSignalHandler() {
228 struct sigaction action = {};
229 action.sa_handler = MaybeInstallInitHeapprofdHook;
230 sigaction(kHeapprofdSignal, &action, nullptr);
231}
232
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800233extern "C" int __rt_sigprocmask(int, const sigset64_t*, sigset64_t*, size_t);
234
235void HeapprofdMaskSignal() {
236 sigset64_t mask_set;
237 // Need to use this function instead because sigprocmask64 filters
238 // out this signal.
239 __rt_sigprocmask(SIG_SETMASK, nullptr, &mask_set, sizeof(mask_set));
240 sigaddset64(&mask_set, kHeapprofdSignal);
241 __rt_sigprocmask(SIG_SETMASK, &mask_set, nullptr, sizeof(mask_set));
242}
243
244void HeapprofdUnmaskSignal() {
245 sigset64_t mask_set;
246 __rt_sigprocmask(SIG_SETMASK, nullptr, &mask_set, sizeof(mask_set));
247 sigdelset64(&mask_set, kHeapprofdSignal);
248 __rt_sigprocmask(SIG_SETMASK, &mask_set, nullptr, sizeof(mask_set));
249}
250
Christopher Ferris28228562019-02-14 10:23:58 -0800251static void DisplayError(int) {
252 error_log("Cannot install heapprofd while malloc debug/malloc hooks are enabled.");
253}
254
255void HeapprofdInstallErrorSignalHandler() {
256 struct sigaction action = {};
257 action.sa_handler = DisplayError;
258 sigaction(kHeapprofdSignal, &action, nullptr);
259}
260
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800261static void CommonInstallHooks(libc_globals* globals) {
262 void* impl_handle = atomic_load(&gHeapprofdHandle);
263 bool reusing_handle = impl_handle != nullptr;
264 if (!reusing_handle) {
265 impl_handle = LoadSharedLibrary(kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table);
266 if (impl_handle == nullptr) {
267 return;
268 }
269 } else if (!InitSharedLibrary(impl_handle, kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table)) {
270 return;
271 }
272
273 if (FinishInstallHooks(globals, nullptr, kHeapprofdPrefix)) {
274 atomic_store(&gHeapprofdHandle, impl_handle);
275 } else if (!reusing_handle) {
276 dlclose(impl_handle);
277 }
278
279 atomic_store(&gHeapprofdInitInProgress, false);
280}
281
282void HeapprofdInstallHooksAtInit(libc_globals* globals) {
283 if (atomic_exchange(&gHeapprofdInitInProgress, true)) {
284 return;
285 }
286 CommonInstallHooks(globals);
287}
288
289static void* InitHeapprofd(void*) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800290 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800291 __libc_globals.mutate([](libc_globals* globals) {
292 CommonInstallHooks(globals);
293 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800294 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800295
296 // Allow to install hook again to re-initialize heap profiling after the
297 // current session finished.
298 atomic_store(&gHeapprofdInitHookInstalled, false);
299 return nullptr;
300}
301
302extern "C" void* MallocInitHeapprofdHook(size_t bytes) {
303 if (!atomic_exchange(&gHeapprofdInitHookInstalled, true)) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800304 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800305 __libc_globals.mutate([](libc_globals* globals) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800306 auto old_dispatch = GetDefaultDispatchTable();
307 atomic_store(&globals->default_dispatch_table, nullptr);
308 if (GetDispatchTable() == old_dispatch) {
309 atomic_store(&globals->current_dispatch_table, nullptr);
310 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800311 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800312 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800313
314 pthread_t thread_id;
315 if (pthread_create(&thread_id, nullptr, InitHeapprofd, nullptr) != 0) {
316 error_log("%s: heapprofd: failed to pthread_create.", getprogname());
317 } else if (pthread_detach(thread_id) != 0) {
318 error_log("%s: heapprofd: failed to pthread_detach", getprogname());
319 }
320 if (pthread_setname_np(thread_id, "heapprofdinit") != 0) {
321 error_log("%s: heapprod: failed to pthread_setname_np", getprogname());
322 }
323 }
324 return Malloc(malloc)(bytes);
325}
326
327// Marks this process as a profileable zygote child.
328static bool HandleInitZygoteChildProfiling() {
Christopher Ferris8189e772019-04-09 16:37:23 -0700329 atomic_store_explicit(&gZygoteChildProfileable, true, memory_order_release);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800330
331 // Conditionally start "from startup" profiling.
332 if (HeapprofdShouldLoad()) {
333 // Directly call the signal handler (will correctly guard against
334 // concurrent signal delivery).
335 MaybeInstallInitHeapprofdHook(kHeapprofdSignal);
336 }
337 return true;
338}
339
340static bool DispatchReset() {
341 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800342 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800343 __libc_globals.mutate([](libc_globals* globals) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800344 auto old_dispatch = GetDefaultDispatchTable();
345 atomic_store(&globals->default_dispatch_table, nullptr);
346 if (GetDispatchTable() == old_dispatch) {
347 atomic_store(&globals->current_dispatch_table, nullptr);
348 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800349 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800350 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800351 atomic_store(&gHeapprofdInitInProgress, false);
352 return true;
353 }
354 errno = EAGAIN;
355 return false;
356}
357
358bool HeapprofdMallopt(int opcode, void* arg, size_t arg_size) {
359 if (opcode == M_INIT_ZYGOTE_CHILD_PROFILING) {
360 if (arg != nullptr || arg_size != 0) {
361 errno = EINVAL;
362 return false;
363 }
364 return HandleInitZygoteChildProfiling();
365 }
366 if (opcode == M_RESET_HOOKS) {
367 if (arg != nullptr || arg_size != 0) {
368 errno = EINVAL;
369 return false;
370 }
371 return DispatchReset();
372 }
373 errno = ENOTSUP;
374 return false;
375}