blob: b2a9e3ef576ccc1305771097a43a1de21fc50b65 [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 const MallocDispatch* default_dispatch = GetDefaultDispatchTable();
Mitch Phillips5f91bf42020-02-26 11:28:11 -0800177
178 // Below, we initialize heapprofd lazily by redirecting libc's malloc() to
179 // call MallocInitHeapprofdHook, which spawns off a thread and initializes
180 // heapprofd. During the short period between now and when heapprofd is
181 // initialized, allocations may need to be serviced. There are three
182 // possible configurations:
183
184 if (default_dispatch == nullptr) {
185 // 1. No malloc hooking has been done (heapprofd, GWP-ASan, etc.). In
186 // this case, everything but malloc() should come from the system
187 // allocator.
188 gPreviousDefaultDispatchTable = nullptr;
189 gEphemeralDispatch = *NativeAllocatorDispatch();
190 } else if (DispatchIsGwpAsan(default_dispatch)) {
191 // 2. GWP-ASan was installed. We should use GWP-ASan for everything but
192 // malloc() in the interim period before heapprofd is properly
193 // installed. After heapprofd is finished installing, we will use
194 // GWP-ASan as heapprofd's backing allocator to allow heapprofd and
195 // GWP-ASan to coexist.
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800196 gPreviousDefaultDispatchTable = default_dispatch;
Mitch Phillips5f91bf42020-02-26 11:28:11 -0800197 gEphemeralDispatch = *default_dispatch;
198 } else {
199 // 3. It may be possible at this point in time that heapprofd is
200 // *already* the default dispatch, and as such we don't want to use
201 // heapprofd as the backing store for itself (otherwise infinite
202 // recursion occurs). We will use the system allocator functions. Note:
203 // We've checked that no other malloc interceptors are being used by
204 // validating `gHeapprofdIncompatibleHooks` above, so we don't need to
205 // worry about that case here.
206 gPreviousDefaultDispatchTable = nullptr;
207 gEphemeralDispatch = *NativeAllocatorDispatch();
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800208 }
209
Mitch Phillips5f91bf42020-02-26 11:28:11 -0800210 // Now, replace the malloc function so that the next call to malloc() will
211 // initialize heapprofd.
212 gEphemeralDispatch.malloc = MallocInitHeapprofdHook;
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800213
Mitch Phillips5f91bf42020-02-26 11:28:11 -0800214 // And finally, install these new malloc-family interceptors.
215 __libc_globals.mutate([](libc_globals* globals) {
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800216 atomic_store(&globals->default_dispatch_table, &gEphemeralDispatch);
217 if (!MallocLimitInstalled()) {
218 atomic_store(&globals->current_dispatch_table, &gEphemeralDispatch);
Ryan Savitski175c8862020-01-02 19:54:57 +0000219 }
220 });
221 }
222 atomic_store(&gGlobalsMutating, false);
223 }
224 // Otherwise, we're racing against malloc_limit's enable logic (at most once
225 // per process, and a niche feature). This is highly unlikely, so simply give
226 // up if it does happen.
227}
228
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800229bool HeapprofdShouldLoad() {
230 // First check for heapprofd.enable. If it is set to "all", enable
231 // heapprofd for all processes. Otherwise, check heapprofd.enable.${prog},
232 // if it is set and not 0, enable heap profiling for this process.
233 char property_value[PROP_VALUE_MAX];
234 if (__system_property_get(kHeapprofdPropertyEnable, property_value) == 0) {
235 return false;
236 }
237 if (strcmp(property_value, "all") == 0) {
238 return true;
239 }
240
Florian Mayerf6d221e2019-05-03 16:24:52 +0100241 char program_property[kHeapprofdProgramPropertyPrefixSize + kMaxCmdlineSize];
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800242 if (!GetHeapprofdProgramProperty(program_property,
243 sizeof(program_property))) {
244 return false;
245 }
246 if (__system_property_get(program_property, property_value) == 0) {
247 return false;
248 }
Christopher Ferris503c17b2019-02-22 12:47:23 -0800249 return property_value[0] != '\0';
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800250}
251
Ryan Savitski175c8862020-01-02 19:54:57 +0000252void HeapprofdRememberHookConflict() {
253 atomic_store_explicit(&gHeapprofdIncompatibleHooks, true, memory_order_release);
Christopher Ferris28228562019-02-14 10:23:58 -0800254}
255
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800256static void CommonInstallHooks(libc_globals* globals) {
257 void* impl_handle = atomic_load(&gHeapprofdHandle);
258 bool reusing_handle = impl_handle != nullptr;
259 if (!reusing_handle) {
260 impl_handle = LoadSharedLibrary(kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table);
261 if (impl_handle == nullptr) {
262 return;
263 }
264 } else if (!InitSharedLibrary(impl_handle, kHeapprofdSharedLib, kHeapprofdPrefix, &globals->malloc_dispatch_table)) {
265 return;
266 }
267
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800268 // Before we set the new default_dispatch_table in FinishInstallHooks, save
269 // the previous dispatch table. If DispatchReset() gets called later, we want
270 // to be able to restore the dispatch. We're still under
271 // gHeapprofdInitInProgress locks at this point.
272 gPreviousDefaultDispatchTable = GetDefaultDispatchTable();
273
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800274 if (FinishInstallHooks(globals, nullptr, kHeapprofdPrefix)) {
275 atomic_store(&gHeapprofdHandle, impl_handle);
276 } else if (!reusing_handle) {
277 dlclose(impl_handle);
278 }
279
280 atomic_store(&gHeapprofdInitInProgress, false);
281}
282
283void HeapprofdInstallHooksAtInit(libc_globals* globals) {
284 if (atomic_exchange(&gHeapprofdInitInProgress, true)) {
285 return;
286 }
287 CommonInstallHooks(globals);
288}
289
290static void* InitHeapprofd(void*) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800291 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800292 __libc_globals.mutate([](libc_globals* globals) {
293 CommonInstallHooks(globals);
294 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800295 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800296
297 // Allow to install hook again to re-initialize heap profiling after the
298 // current session finished.
299 atomic_store(&gHeapprofdInitHookInstalled, false);
300 return nullptr;
301}
302
303extern "C" void* MallocInitHeapprofdHook(size_t bytes) {
304 if (!atomic_exchange(&gHeapprofdInitHookInstalled, true)) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800305 pthread_mutex_lock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800306 __libc_globals.mutate([](libc_globals* globals) {
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800307 atomic_store(&globals->default_dispatch_table, gPreviousDefaultDispatchTable);
308 if (!MallocLimitInstalled()) {
309 atomic_store(&globals->current_dispatch_table, gPreviousDefaultDispatchTable);
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800310 }
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 }
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800324 // Get an allocation from libc malloc. If we had a previous dispatch table,
325 // this will come from it - otherwise, we'll get it from the system
326 // allocator.
327 return malloc(bytes);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800328}
329
Ryan Savitski175c8862020-01-02 19:54:57 +0000330bool HeapprofdInitZygoteChildProfiling() {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800331 // Conditionally start "from startup" profiling.
332 if (HeapprofdShouldLoad()) {
Ryan Savitski175c8862020-01-02 19:54:57 +0000333 // Directly call the signal handler codepath (properly protects against
334 // concurrent invocations).
335 HandleHeapprofdSignal();
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800336 }
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) {
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800344 atomic_store(&globals->default_dispatch_table, gPreviousDefaultDispatchTable);
345 if (!MallocLimitInstalled()) {
346 atomic_store(&globals->current_dispatch_table, gPreviousDefaultDispatchTable);
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800347 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800348 });
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800349 pthread_mutex_unlock(&gGlobalsMutateLock);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800350 atomic_store(&gHeapprofdInitInProgress, false);
351 return true;
352 }
353 errno = EAGAIN;
354 return false;
355}
356
357bool HeapprofdMallopt(int opcode, void* arg, size_t arg_size) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800358 if (opcode == M_RESET_HOOKS) {
359 if (arg != nullptr || arg_size != 0) {
360 errno = EINVAL;
361 return false;
362 }
363 return DispatchReset();
364 }
365 errno = ENOTSUP;
366 return false;
367}