blob: 681d8a23d55e4492b6926b9c3cc6d864f737a483 [file] [log] [blame]
Austin Schuh745610d2015-09-06 18:19:50 -07001// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
2// Copyright (c) 2005, Google Inc.
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 are
7// met:
8//
9// * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11// * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15// * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// ---
32// Author: Sanjay Ghemawat <opensource@google.com>
33
34#include <config.h>
35
36// Disable the glibc prototype of mremap(), as older versions of the
37// system headers define this function with only four arguments,
38// whereas newer versions allow an optional fifth argument:
39#ifdef HAVE_MMAP
40# define mremap glibc_mremap
41# include <sys/mman.h>
42# undef mremap
43#endif
44
45#include <stddef.h>
46#ifdef HAVE_STDINT_H
47#include <stdint.h>
48#endif
49#include <algorithm>
50#include "base/logging.h"
51#include "base/spinlock.h"
52#include "maybe_threads.h"
53#include "malloc_hook-inl.h"
54#include <gperftools/malloc_hook.h>
55
56// This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if
57// you're porting to a system where you really can't get a stacktrace.
58#ifdef NO_TCMALLOC_SAMPLES
59 // We use #define so code compiles even if you #include stacktrace.h somehow.
60# define GetStackTrace(stack, depth, skip) (0)
61#else
62# include <gperftools/stacktrace.h>
63#endif
64
65// __THROW is defined in glibc systems. It means, counter-intuitively,
66// "This function will never throw an exception." It's an optional
67// optimization tool, but we may need to use it to match glibc prototypes.
68#ifndef __THROW // I guess we're not on a glibc system
69# define __THROW // __THROW is just an optimization, so ok to make it ""
70#endif
71
72using std::copy;
73
74
75// Declaration of default weak initialization function, that can be overridden
76// by linking-in a strong definition (as heap-checker.cc does). This is
77// extern "C" so that it doesn't trigger gold's --detect-odr-violations warning,
78// which only looks at C++ symbols.
79//
80// This function is declared here as weak, and defined later, rather than a more
81// straightforward simple weak definition, as a workround for an icc compiler
82// issue ((Intel reference 290819). This issue causes icc to resolve weak
83// symbols too early, at compile rather than link time. By declaring it (weak)
84// here, then defining it below after its use, we can avoid the problem.
85extern "C" {
86ATTRIBUTE_WEAK void MallocHook_InitAtFirstAllocation_HeapLeakChecker();
87}
88
89namespace {
90
91void RemoveInitialHooksAndCallInitializers(); // below.
92
93pthread_once_t once = PTHREAD_ONCE_INIT;
94
95// These hooks are installed in MallocHook as the only initial hooks. The first
96// hook that is called will run RemoveInitialHooksAndCallInitializers (see the
97// definition below) and then redispatch to any malloc hooks installed by
98// RemoveInitialHooksAndCallInitializers.
99//
100// Note(llib): there is a possibility of a race in the event that there are
101// multiple threads running before the first allocation. This is pretty
102// difficult to achieve, but if it is then multiple threads may concurrently do
103// allocations. The first caller will call
104// RemoveInitialHooksAndCallInitializers via one of the initial hooks. A
105// concurrent allocation may, depending on timing either:
106// * still have its initial malloc hook installed, run that and block on waiting
107// for the first caller to finish its call to
108// RemoveInitialHooksAndCallInitializers, and proceed normally.
109// * occur some time during the RemoveInitialHooksAndCallInitializers call, at
110// which point there could be no initial hooks and the subsequent hooks that
111// are about to be set up by RemoveInitialHooksAndCallInitializers haven't
112// been installed yet. I think the worst we can get is that some allocations
113// will not get reported to some hooks set by the initializers called from
114// RemoveInitialHooksAndCallInitializers.
115
116void InitialNewHook(const void* ptr, size_t size) {
117 perftools_pthread_once(&once, &RemoveInitialHooksAndCallInitializers);
118 MallocHook::InvokeNewHook(ptr, size);
119}
120
121void InitialPreMMapHook(const void* start,
122 size_t size,
123 int protection,
124 int flags,
125 int fd,
126 off_t offset) {
127 perftools_pthread_once(&once, &RemoveInitialHooksAndCallInitializers);
128 MallocHook::InvokePreMmapHook(start, size, protection, flags, fd, offset);
129}
130
131void InitialPreSbrkHook(ptrdiff_t increment) {
132 perftools_pthread_once(&once, &RemoveInitialHooksAndCallInitializers);
133 MallocHook::InvokePreSbrkHook(increment);
134}
135
136// This function is called at most once by one of the above initial malloc
137// hooks. It removes all initial hooks and initializes all other clients that
138// want to get control at the very first memory allocation. The initializers
139// may assume that the initial malloc hooks have been removed. The initializers
140// may set up malloc hooks and allocate memory.
141void RemoveInitialHooksAndCallInitializers() {
142 RAW_CHECK(MallocHook::RemoveNewHook(&InitialNewHook), "");
143 RAW_CHECK(MallocHook::RemovePreMmapHook(&InitialPreMMapHook), "");
144 RAW_CHECK(MallocHook::RemovePreSbrkHook(&InitialPreSbrkHook), "");
145
146 // HeapLeakChecker is currently the only module that needs to get control on
147 // the first memory allocation, but one can add other modules by following the
148 // same weak/strong function pattern.
149 MallocHook_InitAtFirstAllocation_HeapLeakChecker();
150}
151
152} // namespace
153
154// Weak default initialization function that must go after its use.
155extern "C" void MallocHook_InitAtFirstAllocation_HeapLeakChecker() {
156 // Do nothing.
157}
158
159namespace base { namespace internal {
160
161// This lock is shared between all implementations of HookList::Add & Remove.
162// The potential for contention is very small. This needs to be a SpinLock and
163// not a Mutex since it's possible for Mutex locking to allocate memory (e.g.,
164// per-thread allocation in debug builds), which could cause infinite recursion.
165static SpinLock hooklist_spinlock(base::LINKER_INITIALIZED);
166
167template <typename T>
168bool HookList<T>::Add(T value_as_t) {
169 AtomicWord value = bit_cast<AtomicWord>(value_as_t);
170 if (value == 0) {
171 return false;
172 }
173 SpinLockHolder l(&hooklist_spinlock);
174 // Find the first slot in data that is 0.
175 int index = 0;
176 while ((index < kHookListMaxValues) &&
177 (base::subtle::NoBarrier_Load(&priv_data[index]) != 0)) {
178 ++index;
179 }
180 if (index == kHookListMaxValues) {
181 return false;
182 }
183 AtomicWord prev_num_hooks = base::subtle::Acquire_Load(&priv_end);
184 base::subtle::NoBarrier_Store(&priv_data[index], value);
185 if (prev_num_hooks <= index) {
186 base::subtle::NoBarrier_Store(&priv_end, index + 1);
187 }
188 return true;
189}
190
191template <typename T>
192void HookList<T>::FixupPrivEndLocked() {
193 AtomicWord hooks_end = base::subtle::NoBarrier_Load(&priv_end);
194 while ((hooks_end > 0) &&
195 (base::subtle::NoBarrier_Load(&priv_data[hooks_end - 1]) == 0)) {
196 --hooks_end;
197 }
198 base::subtle::NoBarrier_Store(&priv_end, hooks_end);
199}
200
201template <typename T>
202bool HookList<T>::Remove(T value_as_t) {
203 if (value_as_t == 0) {
204 return false;
205 }
206 SpinLockHolder l(&hooklist_spinlock);
207 AtomicWord hooks_end = base::subtle::NoBarrier_Load(&priv_end);
208 int index = 0;
209 while (index < hooks_end && value_as_t != bit_cast<T>(
210 base::subtle::NoBarrier_Load(&priv_data[index]))) {
211 ++index;
212 }
213 if (index == hooks_end) {
214 return false;
215 }
216 base::subtle::NoBarrier_Store(&priv_data[index], 0);
217 FixupPrivEndLocked();
218 return true;
219}
220
221template <typename T>
222int HookList<T>::Traverse(T* output_array, int n) const {
223 AtomicWord hooks_end = base::subtle::Acquire_Load(&priv_end);
224 int actual_hooks_end = 0;
225 for (int i = 0; i < hooks_end && n > 0; ++i) {
226 AtomicWord data = base::subtle::Acquire_Load(&priv_data[i]);
227 if (data != 0) {
228 *output_array++ = bit_cast<T>(data);
229 ++actual_hooks_end;
230 --n;
231 }
232 }
233 return actual_hooks_end;
234}
235
236template <typename T>
237T HookList<T>::ExchangeSingular(T value_as_t) {
238 AtomicWord value = bit_cast<AtomicWord>(value_as_t);
239 AtomicWord old_value;
240 SpinLockHolder l(&hooklist_spinlock);
241 old_value = base::subtle::NoBarrier_Load(&priv_data[kHookListSingularIdx]);
242 base::subtle::NoBarrier_Store(&priv_data[kHookListSingularIdx], value);
243 if (value != 0) {
244 base::subtle::NoBarrier_Store(&priv_end, kHookListSingularIdx + 1);
245 } else {
246 FixupPrivEndLocked();
247 }
248 return bit_cast<T>(old_value);
249}
250
251// Initialize a HookList (optionally with the given initial_value in index 0).
252#define INIT_HOOK_LIST { 0 }
253#define INIT_HOOK_LIST_WITH_VALUE(initial_value) \
254 { 1, { reinterpret_cast<AtomicWord>(initial_value) } }
255
256// Explicit instantiation for malloc_hook_test.cc. This ensures all the methods
257// are instantiated.
258template struct HookList<MallocHook::NewHook>;
259
260HookList<MallocHook::NewHook> new_hooks_ =
261 INIT_HOOK_LIST_WITH_VALUE(&InitialNewHook);
262HookList<MallocHook::DeleteHook> delete_hooks_ = INIT_HOOK_LIST;
263HookList<MallocHook::PreMmapHook> premmap_hooks_ =
264 INIT_HOOK_LIST_WITH_VALUE(&InitialPreMMapHook);
265HookList<MallocHook::MmapHook> mmap_hooks_ = INIT_HOOK_LIST;
266HookList<MallocHook::MunmapHook> munmap_hooks_ = INIT_HOOK_LIST;
267HookList<MallocHook::MremapHook> mremap_hooks_ = INIT_HOOK_LIST;
268HookList<MallocHook::PreSbrkHook> presbrk_hooks_ =
269 INIT_HOOK_LIST_WITH_VALUE(InitialPreSbrkHook);
270HookList<MallocHook::SbrkHook> sbrk_hooks_ = INIT_HOOK_LIST;
271
272// These lists contain either 0 or 1 hooks.
273HookList<MallocHook::MmapReplacement> mmap_replacement_ = { 0 };
274HookList<MallocHook::MunmapReplacement> munmap_replacement_ = { 0 };
275
276#undef INIT_HOOK_LIST_WITH_VALUE
277#undef INIT_HOOK_LIST
278
279} } // namespace base::internal
280
281using base::internal::kHookListMaxValues;
282using base::internal::new_hooks_;
283using base::internal::delete_hooks_;
284using base::internal::premmap_hooks_;
285using base::internal::mmap_hooks_;
286using base::internal::mmap_replacement_;
287using base::internal::munmap_hooks_;
288using base::internal::munmap_replacement_;
289using base::internal::mremap_hooks_;
290using base::internal::presbrk_hooks_;
291using base::internal::sbrk_hooks_;
292
293// These are available as C bindings as well as C++, hence their
294// definition outside the MallocHook class.
295extern "C"
296int MallocHook_AddNewHook(MallocHook_NewHook hook) {
297 RAW_VLOG(10, "AddNewHook(%p)", hook);
298 return new_hooks_.Add(hook);
299}
300
301extern "C"
302int MallocHook_RemoveNewHook(MallocHook_NewHook hook) {
303 RAW_VLOG(10, "RemoveNewHook(%p)", hook);
304 return new_hooks_.Remove(hook);
305}
306
307extern "C"
308int MallocHook_AddDeleteHook(MallocHook_DeleteHook hook) {
309 RAW_VLOG(10, "AddDeleteHook(%p)", hook);
310 return delete_hooks_.Add(hook);
311}
312
313extern "C"
314int MallocHook_RemoveDeleteHook(MallocHook_DeleteHook hook) {
315 RAW_VLOG(10, "RemoveDeleteHook(%p)", hook);
316 return delete_hooks_.Remove(hook);
317}
318
319extern "C"
320int MallocHook_AddPreMmapHook(MallocHook_PreMmapHook hook) {
321 RAW_VLOG(10, "AddPreMmapHook(%p)", hook);
322 return premmap_hooks_.Add(hook);
323}
324
325extern "C"
326int MallocHook_RemovePreMmapHook(MallocHook_PreMmapHook hook) {
327 RAW_VLOG(10, "RemovePreMmapHook(%p)", hook);
328 return premmap_hooks_.Remove(hook);
329}
330
331extern "C"
332int MallocHook_SetMmapReplacement(MallocHook_MmapReplacement hook) {
333 RAW_VLOG(10, "SetMmapReplacement(%p)", hook);
334 // NOTE this is a best effort CHECK. Concurrent sets could succeed since
335 // this test is outside of the Add spin lock.
336 RAW_CHECK(mmap_replacement_.empty(), "Only one MMapReplacement is allowed.");
337 return mmap_replacement_.Add(hook);
338}
339
340extern "C"
341int MallocHook_RemoveMmapReplacement(MallocHook_MmapReplacement hook) {
342 RAW_VLOG(10, "RemoveMmapReplacement(%p)", hook);
343 return mmap_replacement_.Remove(hook);
344}
345
346extern "C"
347int MallocHook_AddMmapHook(MallocHook_MmapHook hook) {
348 RAW_VLOG(10, "AddMmapHook(%p)", hook);
349 return mmap_hooks_.Add(hook);
350}
351
352extern "C"
353int MallocHook_RemoveMmapHook(MallocHook_MmapHook hook) {
354 RAW_VLOG(10, "RemoveMmapHook(%p)", hook);
355 return mmap_hooks_.Remove(hook);
356}
357
358extern "C"
359int MallocHook_AddMunmapHook(MallocHook_MunmapHook hook) {
360 RAW_VLOG(10, "AddMunmapHook(%p)", hook);
361 return munmap_hooks_.Add(hook);
362}
363
364extern "C"
365int MallocHook_RemoveMunmapHook(MallocHook_MunmapHook hook) {
366 RAW_VLOG(10, "RemoveMunmapHook(%p)", hook);
367 return munmap_hooks_.Remove(hook);
368}
369
370extern "C"
371int MallocHook_SetMunmapReplacement(MallocHook_MunmapReplacement hook) {
372 RAW_VLOG(10, "SetMunmapReplacement(%p)", hook);
373 // NOTE this is a best effort CHECK. Concurrent sets could succeed since
374 // this test is outside of the Add spin lock.
375 RAW_CHECK(munmap_replacement_.empty(),
376 "Only one MunmapReplacement is allowed.");
377 return munmap_replacement_.Add(hook);
378}
379
380extern "C"
381int MallocHook_RemoveMunmapReplacement(MallocHook_MunmapReplacement hook) {
382 RAW_VLOG(10, "RemoveMunmapReplacement(%p)", hook);
383 return munmap_replacement_.Remove(hook);
384}
385
386extern "C"
387int MallocHook_AddMremapHook(MallocHook_MremapHook hook) {
388 RAW_VLOG(10, "AddMremapHook(%p)", hook);
389 return mremap_hooks_.Add(hook);
390}
391
392extern "C"
393int MallocHook_RemoveMremapHook(MallocHook_MremapHook hook) {
394 RAW_VLOG(10, "RemoveMremapHook(%p)", hook);
395 return mremap_hooks_.Remove(hook);
396}
397
398extern "C"
399int MallocHook_AddPreSbrkHook(MallocHook_PreSbrkHook hook) {
400 RAW_VLOG(10, "AddPreSbrkHook(%p)", hook);
401 return presbrk_hooks_.Add(hook);
402}
403
404extern "C"
405int MallocHook_RemovePreSbrkHook(MallocHook_PreSbrkHook hook) {
406 RAW_VLOG(10, "RemovePreSbrkHook(%p)", hook);
407 return presbrk_hooks_.Remove(hook);
408}
409
410extern "C"
411int MallocHook_AddSbrkHook(MallocHook_SbrkHook hook) {
412 RAW_VLOG(10, "AddSbrkHook(%p)", hook);
413 return sbrk_hooks_.Add(hook);
414}
415
416extern "C"
417int MallocHook_RemoveSbrkHook(MallocHook_SbrkHook hook) {
418 RAW_VLOG(10, "RemoveSbrkHook(%p)", hook);
419 return sbrk_hooks_.Remove(hook);
420}
421
422// The code below is DEPRECATED.
423extern "C"
424MallocHook_NewHook MallocHook_SetNewHook(MallocHook_NewHook hook) {
425 RAW_VLOG(10, "SetNewHook(%p)", hook);
426 return new_hooks_.ExchangeSingular(hook);
427}
428
429extern "C"
430MallocHook_DeleteHook MallocHook_SetDeleteHook(MallocHook_DeleteHook hook) {
431 RAW_VLOG(10, "SetDeleteHook(%p)", hook);
432 return delete_hooks_.ExchangeSingular(hook);
433}
434
435extern "C"
436MallocHook_PreMmapHook MallocHook_SetPreMmapHook(MallocHook_PreMmapHook hook) {
437 RAW_VLOG(10, "SetPreMmapHook(%p)", hook);
438 return premmap_hooks_.ExchangeSingular(hook);
439}
440
441extern "C"
442MallocHook_MmapHook MallocHook_SetMmapHook(MallocHook_MmapHook hook) {
443 RAW_VLOG(10, "SetMmapHook(%p)", hook);
444 return mmap_hooks_.ExchangeSingular(hook);
445}
446
447extern "C"
448MallocHook_MunmapHook MallocHook_SetMunmapHook(MallocHook_MunmapHook hook) {
449 RAW_VLOG(10, "SetMunmapHook(%p)", hook);
450 return munmap_hooks_.ExchangeSingular(hook);
451}
452
453extern "C"
454MallocHook_MremapHook MallocHook_SetMremapHook(MallocHook_MremapHook hook) {
455 RAW_VLOG(10, "SetMremapHook(%p)", hook);
456 return mremap_hooks_.ExchangeSingular(hook);
457}
458
459extern "C"
460MallocHook_PreSbrkHook MallocHook_SetPreSbrkHook(MallocHook_PreSbrkHook hook) {
461 RAW_VLOG(10, "SetPreSbrkHook(%p)", hook);
462 return presbrk_hooks_.ExchangeSingular(hook);
463}
464
465extern "C"
466MallocHook_SbrkHook MallocHook_SetSbrkHook(MallocHook_SbrkHook hook) {
467 RAW_VLOG(10, "SetSbrkHook(%p)", hook);
468 return sbrk_hooks_.ExchangeSingular(hook);
469}
470// End of DEPRECATED code section.
471
472// Note: embedding the function calls inside the traversal of HookList would be
473// very confusing, as it is legal for a hook to remove itself and add other
474// hooks. Doing traversal first, and then calling the hooks ensures we only
475// call the hooks registered at the start.
476#define INVOKE_HOOKS(HookType, hook_list, args) do { \
477 HookType hooks[kHookListMaxValues]; \
478 int num_hooks = hook_list.Traverse(hooks, kHookListMaxValues); \
479 for (int i = 0; i < num_hooks; ++i) { \
480 (*hooks[i])args; \
481 } \
482 } while (0)
483
484// There should only be one replacement. Return the result of the first
485// one, or false if there is none.
486#define INVOKE_REPLACEMENT(HookType, hook_list, args) do { \
487 HookType hooks[kHookListMaxValues]; \
488 int num_hooks = hook_list.Traverse(hooks, kHookListMaxValues); \
489 return (num_hooks > 0 && (*hooks[0])args); \
490 } while (0)
491
492
493void MallocHook::InvokeNewHookSlow(const void* p, size_t s) {
494 INVOKE_HOOKS(NewHook, new_hooks_, (p, s));
495}
496
497void MallocHook::InvokeDeleteHookSlow(const void* p) {
498 INVOKE_HOOKS(DeleteHook, delete_hooks_, (p));
499}
500
501void MallocHook::InvokePreMmapHookSlow(const void* start,
502 size_t size,
503 int protection,
504 int flags,
505 int fd,
506 off_t offset) {
507 INVOKE_HOOKS(PreMmapHook, premmap_hooks_, (start, size, protection, flags, fd,
508 offset));
509}
510
511void MallocHook::InvokeMmapHookSlow(const void* result,
512 const void* start,
513 size_t size,
514 int protection,
515 int flags,
516 int fd,
517 off_t offset) {
518 INVOKE_HOOKS(MmapHook, mmap_hooks_, (result, start, size, protection, flags,
519 fd, offset));
520}
521
522bool MallocHook::InvokeMmapReplacementSlow(const void* start,
523 size_t size,
524 int protection,
525 int flags,
526 int fd,
527 off_t offset,
528 void** result) {
529 INVOKE_REPLACEMENT(MmapReplacement, mmap_replacement_,
530 (start, size, protection, flags, fd, offset, result));
531}
532
533void MallocHook::InvokeMunmapHookSlow(const void* p, size_t s) {
534 INVOKE_HOOKS(MunmapHook, munmap_hooks_, (p, s));
535}
536
537bool MallocHook::InvokeMunmapReplacementSlow(const void* p,
538 size_t s,
539 int* result) {
540 INVOKE_REPLACEMENT(MunmapReplacement, munmap_replacement_, (p, s, result));
541}
542
543void MallocHook::InvokeMremapHookSlow(const void* result,
544 const void* old_addr,
545 size_t old_size,
546 size_t new_size,
547 int flags,
548 const void* new_addr) {
549 INVOKE_HOOKS(MremapHook, mremap_hooks_, (result, old_addr, old_size, new_size,
550 flags, new_addr));
551}
552
553void MallocHook::InvokePreSbrkHookSlow(ptrdiff_t increment) {
554 INVOKE_HOOKS(PreSbrkHook, presbrk_hooks_, (increment));
555}
556
557void MallocHook::InvokeSbrkHookSlow(const void* result, ptrdiff_t increment) {
558 INVOKE_HOOKS(SbrkHook, sbrk_hooks_, (result, increment));
559}
560
561#undef INVOKE_HOOKS
562
563DEFINE_ATTRIBUTE_SECTION_VARS(google_malloc);
564DECLARE_ATTRIBUTE_SECTION_VARS(google_malloc);
565 // actual functions are in debugallocation.cc or tcmalloc.cc
566DEFINE_ATTRIBUTE_SECTION_VARS(malloc_hook);
567DECLARE_ATTRIBUTE_SECTION_VARS(malloc_hook);
568 // actual functions are in this file, malloc_hook.cc, and low_level_alloc.cc
569
570#define ADDR_IN_ATTRIBUTE_SECTION(addr, name) \
571 (reinterpret_cast<uintptr_t>(ATTRIBUTE_SECTION_START(name)) <= \
572 reinterpret_cast<uintptr_t>(addr) && \
573 reinterpret_cast<uintptr_t>(addr) < \
574 reinterpret_cast<uintptr_t>(ATTRIBUTE_SECTION_STOP(name)))
575
576// Return true iff 'caller' is a return address within a function
577// that calls one of our hooks via MallocHook:Invoke*.
578// A helper for GetCallerStackTrace.
579static inline bool InHookCaller(const void* caller) {
580 return ADDR_IN_ATTRIBUTE_SECTION(caller, google_malloc) ||
581 ADDR_IN_ATTRIBUTE_SECTION(caller, malloc_hook);
582 // We can use one section for everything except tcmalloc_or_debug
583 // due to its special linkage mode, which prevents merging of the sections.
584}
585
586#undef ADDR_IN_ATTRIBUTE_SECTION
587
588static bool checked_sections = false;
589
590static inline void CheckInHookCaller() {
591 if (!checked_sections) {
592 INIT_ATTRIBUTE_SECTION_VARS(google_malloc);
593 if (ATTRIBUTE_SECTION_START(google_malloc) ==
594 ATTRIBUTE_SECTION_STOP(google_malloc)) {
595 RAW_LOG(ERROR, "google_malloc section is missing, "
596 "thus InHookCaller is broken!");
597 }
598 INIT_ATTRIBUTE_SECTION_VARS(malloc_hook);
599 if (ATTRIBUTE_SECTION_START(malloc_hook) ==
600 ATTRIBUTE_SECTION_STOP(malloc_hook)) {
601 RAW_LOG(ERROR, "malloc_hook section is missing, "
602 "thus InHookCaller is broken!");
603 }
604 checked_sections = true;
605 }
606}
607
608// We can improve behavior/compactness of this function
609// if we pass a generic test function (with a generic arg)
610// into the implementations for GetStackTrace instead of the skip_count.
611extern "C" int MallocHook_GetCallerStackTrace(void** result, int max_depth,
612 int skip_count) {
613#if defined(NO_TCMALLOC_SAMPLES)
614 return 0;
615#elif !defined(HAVE_ATTRIBUTE_SECTION_START)
616 // Fall back to GetStackTrace and good old but fragile frame skip counts.
617 // Note: this path is inaccurate when a hook is not called directly by an
618 // allocation function but is daisy-chained through another hook,
619 // search for MallocHook::(Get|Set|Invoke)* to find such cases.
620 return GetStackTrace(result, max_depth, skip_count + int(DEBUG_MODE));
621 // due to -foptimize-sibling-calls in opt mode
622 // there's no need for extra frame skip here then
623#else
624 CheckInHookCaller();
625 // MallocHook caller determination via InHookCaller works, use it:
626 static const int kMaxSkip = 32 + 6 + 3;
627 // Constant tuned to do just one GetStackTrace call below in practice
628 // and not get many frames that we don't actually need:
629 // currently max passsed max_depth is 32,
630 // max passed/needed skip_count is 6
631 // and 3 is to account for some hook daisy chaining.
632 static const int kStackSize = kMaxSkip + 1;
633 void* stack[kStackSize];
634 int depth = GetStackTrace(stack, kStackSize, 1); // skip this function frame
635 if (depth == 0) // silenty propagate cases when GetStackTrace does not work
636 return 0;
637 for (int i = 0; i < depth; ++i) { // stack[0] is our immediate caller
638 if (InHookCaller(stack[i])) {
639 RAW_VLOG(10, "Found hooked allocator at %d: %p <- %p",
640 i, stack[i], stack[i+1]);
641 i += 1; // skip hook caller frame
642 depth -= i; // correct depth
643 if (depth > max_depth) depth = max_depth;
644 copy(stack + i, stack + i + depth, result);
645 if (depth < max_depth && depth + i == kStackSize) {
646 // get frames for the missing depth
647 depth +=
648 GetStackTrace(result + depth, max_depth - depth, 1 + kStackSize);
649 }
650 return depth;
651 }
652 }
653 RAW_LOG(WARNING, "Hooked allocator frame not found, returning empty trace");
654 // If this happens try increasing kMaxSkip
655 // or else something must be wrong with InHookCaller,
656 // e.g. for every section used in InHookCaller
657 // all functions in that section must be inside the same library.
658 return 0;
659#endif
660}
661
662// On systems where we know how, we override mmap/munmap/mremap/sbrk
663// to provide support for calling the related hooks (in addition,
664// of course, to doing what these functions normally do).
665
666#if defined(__linux)
667# include "malloc_hook_mmap_linux.h"
668
669#elif defined(__FreeBSD__)
670# include "malloc_hook_mmap_freebsd.h"
671
672#else
673
674/*static*/void* MallocHook::UnhookedMMap(void *start, size_t length, int prot,
675 int flags, int fd, off_t offset) {
676 void* result;
677 if (!MallocHook::InvokeMmapReplacement(
678 start, length, prot, flags, fd, offset, &result)) {
679 result = mmap(start, length, prot, flags, fd, offset);
680 }
681 return result;
682}
683
684/*static*/int MallocHook::UnhookedMUnmap(void *start, size_t length) {
685 int result;
686 if (!MallocHook::InvokeMunmapReplacement(start, length, &result)) {
687 result = munmap(start, length);
688 }
689 return result;
690}
691
692#endif