blob: 198d2f06e2cf2a071f7c10b85c59e26abc1542ae [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
Mitch Phillipsc03856c2020-02-13 16:41:14 -080045#include "gwp_asan_wrappers.h"
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080046#include "malloc_common.h"
47#include "malloc_common_dynamic.h"
48#include "malloc_heapprofd.h"
Mitch Phillips3083cc92020-02-11 15:23:47 -080049#include "malloc_limit.h"
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080050
51static constexpr char kHeapprofdSharedLib[] = "heapprofd_client.so";
52static constexpr char kHeapprofdPrefix[] = "heapprofd";
53static constexpr char kHeapprofdPropertyEnable[] = "heapprofd.enable";
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080054
55// The logic for triggering heapprofd (at runtime) is as follows:
Ryan Savitski175c8862020-01-02 19:54:57 +000056// 1. A reserved profiling signal is received by the process, its si_value
57// discriminating between different handlers. For the case of heapprofd,
58// HandleHeapprofdSignal is called.
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080059// 2. If the initialization is not already in flight
60// (gHeapprofdInitInProgress is false), the malloc hook is set to
61// point at InitHeapprofdHook, and gHeapprofdInitInProgress is set to
62// true.
63// 3. The next malloc call enters InitHeapprofdHook, which removes the malloc
64// hook, and spawns a detached pthread to run the InitHeapprofd task.
Ryan Savitski175c8862020-01-02 19:54:57 +000065// (gHeapprofdInitHookInstalled atomic is used to perform this once.)
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080066// 4. InitHeapprofd, on a dedicated pthread, loads the heapprofd client library,
67// installs the full set of heapprofd hooks, and invokes the client's
68// initializer. The dedicated pthread then terminates.
69// 5. gHeapprofdInitInProgress and gHeapprofdInitHookInstalled are
70// reset to false such that heapprofd can be reinitialized. Reinitialization
71// means that a new profiling session is started, and any still active is
72// torn down.
73//
74// The incremental hooking and a dedicated task thread are used since we cannot
75// do heavy work within a signal handler, or when blocking a malloc invocation.
76
77// The handle returned by dlopen when previously loading the heapprofd
78// hooks. nullptr if shared library has not been already been loaded.
79static _Atomic (void*) gHeapprofdHandle = nullptr;
80
81static _Atomic bool gHeapprofdInitInProgress = false;
82static _Atomic bool gHeapprofdInitHookInstalled = false;
83
Ryan Savitski175c8862020-01-02 19:54:57 +000084// Set to true if the process has enabled malloc_debug or malloc_hooks, which
85// are incompatible (and take precedence over) heapprofd.
86static _Atomic bool gHeapprofdIncompatibleHooks = false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080087
88extern "C" void* MallocInitHeapprofdHook(size_t);
89
Florian Mayerf6d221e2019-05-03 16:24:52 +010090constexpr char kHeapprofdProgramPropertyPrefix[] = "heapprofd.enable.";
91constexpr size_t kHeapprofdProgramPropertyPrefixSize = sizeof(kHeapprofdProgramPropertyPrefix) - 1;
92constexpr size_t kMaxCmdlineSize = 512;
93
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080094static bool GetHeapprofdProgramProperty(char* data, size_t size) {
Florian Mayerf6d221e2019-05-03 16:24:52 +010095 if (size < kHeapprofdProgramPropertyPrefixSize) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080096 error_log("%s: Overflow constructing heapprofd property", getprogname());
97 return false;
98 }
Florian Mayerf6d221e2019-05-03 16:24:52 +010099 memcpy(data, kHeapprofdProgramPropertyPrefix, kHeapprofdProgramPropertyPrefixSize);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800100
101 int fd = open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
102 if (fd == -1) {
103 error_log("%s: Failed to open /proc/self/cmdline", getprogname());
104 return false;
105 }
Florian Mayerf6d221e2019-05-03 16:24:52 +0100106 char cmdline[kMaxCmdlineSize];
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800107 ssize_t rd = read(fd, cmdline, sizeof(cmdline) - 1);
108 close(fd);
109 if (rd == -1) {
110 error_log("%s: Failed to read /proc/self/cmdline", getprogname());
111 return false;
112 }
113 cmdline[rd] = '\0';
114 char* first_arg = static_cast<char*>(memchr(cmdline, '\0', rd));
Florian Mayerf6d221e2019-05-03 16:24:52 +0100115 if (first_arg == nullptr) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800116 error_log("%s: Overflow reading cmdline", getprogname());
117 return false;
118 }
119 // For consistency with what we do with Java app cmdlines, trim everything
120 // after the @ sign of the first arg.
121 char* first_at = static_cast<char*>(memchr(cmdline, '@', rd));
122 if (first_at != nullptr && first_at < first_arg) {
123 *first_at = '\0';
124 first_arg = first_at;
125 }
126
127 char* start = static_cast<char*>(memrchr(cmdline, '/', first_arg - cmdline));
128 if (start == first_arg) {
129 // The first argument ended in a slash.
130 error_log("%s: cmdline ends in /", getprogname());
131 return false;
132 } else if (start == nullptr) {
133 start = cmdline;
134 } else {
135 // Skip the /.
136 start++;
137 }
138
139 size_t name_size = static_cast<size_t>(first_arg - start);
Florian Mayerf6d221e2019-05-03 16:24:52 +0100140 if (name_size >= size - kHeapprofdProgramPropertyPrefixSize) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800141 error_log("%s: overflow constructing heapprofd property.", getprogname());
142 return false;
143 }
144 // + 1 to also copy the trailing null byte.
Florian Mayerf6d221e2019-05-03 16:24:52 +0100145 memcpy(data + kHeapprofdProgramPropertyPrefixSize, start, name_size + 1);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800146 return true;
147}
148
Ryan Savitski175c8862020-01-02 19:54:57 +0000149// Runtime triggering entry-point. Two possible call sites:
150// * when receiving a profiling signal with a si_value indicating heapprofd.
151// * when a Zygote child is marking itself as profileable, and there's a
152// matching profiling request for this process (in which case heapprofd client
153// is loaded synchronously).
154// In both cases, the caller is responsible for verifying that the process is
155// considered profileable.
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800156
157// Previously installed default dispatch table, if it exists. This is used to
158// load heapprofd properly when GWP-ASan was already installed. If GWP-ASan was
159// already installed, heapprofd will take over the dispatch table, but will use
160// GWP-ASan as the backing dispatch. This variable is atomically protected by
161// gHeapprofdInitInProgress.
162static const MallocDispatch* gPreviousDefaultDispatchTable = nullptr;
163static MallocDispatch gEphemeralDispatch;
164
Ryan Savitski175c8862020-01-02 19:54:57 +0000165void HandleHeapprofdSignal() {
166 if (atomic_load_explicit(&gHeapprofdIncompatibleHooks, memory_order_acquire)) {
167 error_log("%s: not enabling heapprofd, malloc_debug/malloc_hooks are enabled.", getprogname());
168 return;
169 }
170
171 // Checking this variable is only necessary when this could conflict with
172 // the change to enable the allocation limit. All other places will
173 // not ever have a conflict modifying the globals.
174 if (!atomic_exchange(&gGlobalsMutating, true)) {
175 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800176 // If the backing dispatch is GWP-ASan, we should use GWP-ASan as the
177 // intermediate dispatch table during initialisation. It may be possible
178 // at this point in time that heapprofd is *already* the default dispatch,
179 // and as such we don't want to use heapprofd as the backing store
180 // (otherwise infinite recursion occurs).
181 gPreviousDefaultDispatchTable = nullptr;
182 const MallocDispatch* default_dispatch = GetDefaultDispatchTable();
183 if (DispatchIsGwpAsan(default_dispatch)) {
184 gPreviousDefaultDispatchTable = default_dispatch;
185 }
186
Ryan Savitski175c8862020-01-02 19:54:57 +0000187 __libc_globals.mutate([](libc_globals* globals) {
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800188 // Wholesale copy the malloc dispatch table here. If the current/default
189 // dispatch table is pointing to the malloc_dispatch_table, we can't
190 // modify it as it may be racy. This dispatch table copy is ephemeral,
191 // and the dispatch tables will be resolved back to the global
192 // malloc_dispatch_table after initialization finishes.
193 gEphemeralDispatch = globals->malloc_dispatch_table;
194 gEphemeralDispatch.malloc = MallocInitHeapprofdHook;
195
196 atomic_store(&globals->default_dispatch_table, &gEphemeralDispatch);
197 if (!MallocLimitInstalled()) {
198 atomic_store(&globals->current_dispatch_table, &gEphemeralDispatch);
Ryan Savitski175c8862020-01-02 19:54:57 +0000199 }
200 });
201 }
202 atomic_store(&gGlobalsMutating, false);
203 }
204 // Otherwise, we're racing against malloc_limit's enable logic (at most once
205 // per process, and a niche feature). This is highly unlikely, so simply give
206 // up if it does happen.
207}
208
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800209bool HeapprofdShouldLoad() {
210 // First check for heapprofd.enable. If it is set to "all", enable
211 // heapprofd for all processes. Otherwise, check heapprofd.enable.${prog},
212 // if it is set and not 0, enable heap profiling for this process.
213 char property_value[PROP_VALUE_MAX];
214 if (__system_property_get(kHeapprofdPropertyEnable, property_value) == 0) {
215 return false;
216 }
217 if (strcmp(property_value, "all") == 0) {
218 return true;
219 }
220
Florian Mayerf6d221e2019-05-03 16:24:52 +0100221 char program_property[kHeapprofdProgramPropertyPrefixSize + kMaxCmdlineSize];
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800222 if (!GetHeapprofdProgramProperty(program_property,
223 sizeof(program_property))) {
224 return false;
225 }
226 if (__system_property_get(program_property, property_value) == 0) {
227 return false;
228 }
Christopher Ferris503c17b2019-02-22 12:47:23 -0800229 return property_value[0] != '\0';
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800230}
231
Ryan Savitski175c8862020-01-02 19:54:57 +0000232void HeapprofdRememberHookConflict() {
233 atomic_store_explicit(&gHeapprofdIncompatibleHooks, true, memory_order_release);
Christopher Ferris28228562019-02-14 10:23:58 -0800234}
235
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800236static void CommonInstallHooks(libc_globals* globals) {
237 void* impl_handle = atomic_load(&gHeapprofdHandle);
238 bool reusing_handle = impl_handle != nullptr;
239 if (!reusing_handle) {
240 impl_handle = LoadSharedLibrary(kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table);
241 if (impl_handle == nullptr) {
242 return;
243 }
244 } else if (!InitSharedLibrary(impl_handle, kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table)) {
245 return;
246 }
247
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800248 // Before we set the new default_dispatch_table in FinishInstallHooks, save
249 // the previous dispatch table. If DispatchReset() gets called later, we want
250 // to be able to restore the dispatch. We're still under
251 // gHeapprofdInitInProgress locks at this point.
252 gPreviousDefaultDispatchTable = GetDefaultDispatchTable();
253
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800254 if (FinishInstallHooks(globals, nullptr, kHeapprofdPrefix)) {
255 atomic_store(&gHeapprofdHandle, impl_handle);
256 } else if (!reusing_handle) {
257 dlclose(impl_handle);
258 }
259
260 atomic_store(&gHeapprofdInitInProgress, false);
261}
262
263void HeapprofdInstallHooksAtInit(libc_globals* globals) {
264 if (atomic_exchange(&gHeapprofdInitInProgress, true)) {
265 return;
266 }
267 CommonInstallHooks(globals);
268}
269
270static void* InitHeapprofd(void*) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800271 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800272 __libc_globals.mutate([](libc_globals* globals) {
273 CommonInstallHooks(globals);
274 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800275 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800276
277 // Allow to install hook again to re-initialize heap profiling after the
278 // current session finished.
279 atomic_store(&gHeapprofdInitHookInstalled, false);
280 return nullptr;
281}
282
283extern "C" void* MallocInitHeapprofdHook(size_t bytes) {
284 if (!atomic_exchange(&gHeapprofdInitHookInstalled, true)) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800285 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800286 __libc_globals.mutate([](libc_globals* globals) {
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800287 atomic_store(&globals->default_dispatch_table, gPreviousDefaultDispatchTable);
288 if (!MallocLimitInstalled()) {
289 atomic_store(&globals->current_dispatch_table, gPreviousDefaultDispatchTable);
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800290 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800291 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800292 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800293
294 pthread_t thread_id;
295 if (pthread_create(&thread_id, nullptr, InitHeapprofd, nullptr) != 0) {
296 error_log("%s: heapprofd: failed to pthread_create.", getprogname());
297 } else if (pthread_detach(thread_id) != 0) {
298 error_log("%s: heapprofd: failed to pthread_detach", getprogname());
299 }
300 if (pthread_setname_np(thread_id, "heapprofdinit") != 0) {
301 error_log("%s: heapprod: failed to pthread_setname_np", getprogname());
302 }
303 }
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800304 // Get an allocation from libc malloc. If we had a previous dispatch table,
305 // this will come from it - otherwise, we'll get it from the system
306 // allocator.
307 return malloc(bytes);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800308}
309
Ryan Savitski175c8862020-01-02 19:54:57 +0000310bool HeapprofdInitZygoteChildProfiling() {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800311 // Conditionally start "from startup" profiling.
312 if (HeapprofdShouldLoad()) {
Ryan Savitski175c8862020-01-02 19:54:57 +0000313 // Directly call the signal handler codepath (properly protects against
314 // concurrent invocations).
315 HandleHeapprofdSignal();
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800316 }
317 return true;
318}
319
320static bool DispatchReset() {
321 if (!atomic_exchange(&gHeapprofdInitInProgress, true)) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800322 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800323 __libc_globals.mutate([](libc_globals* globals) {
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800324 atomic_store(&globals->default_dispatch_table, gPreviousDefaultDispatchTable);
325 if (!MallocLimitInstalled()) {
326 atomic_store(&globals->current_dispatch_table, gPreviousDefaultDispatchTable);
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800327 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800328 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800329 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800330 atomic_store(&gHeapprofdInitInProgress, false);
331 return true;
332 }
333 errno = EAGAIN;
334 return false;
335}
336
337bool HeapprofdMallopt(int opcode, void* arg, size_t arg_size) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800338 if (opcode == M_RESET_HOOKS) {
339 if (arg != nullptr || arg_size != 0) {
340 errno = EINVAL;
341 return false;
342 }
343 return DispatchReset();
344 }
345 errno = ENOTSUP;
346 return false;
347}