1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/allocator/allocator_extension.h"
6 #include "base/allocator/buildflags.h"
7 #include "base/check.h"
8
9 #if BUILDFLAG(USE_TCMALLOC)
10 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
11 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
12 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_hook.h"
13 #endif
14
15 namespace base {
16 namespace allocator {
17
ReleaseFreeMemory()18 void ReleaseFreeMemory() {
19 #if BUILDFLAG(USE_TCMALLOC)
20 ::MallocExtension::instance()->ReleaseFreeMemory();
21 #endif
22 }
23
GetNumericProperty(const char * name,size_t * value)24 bool GetNumericProperty(const char* name, size_t* value) {
25 #if BUILDFLAG(USE_TCMALLOC)
26 return ::MallocExtension::instance()->GetNumericProperty(name, value);
27 #else
28 return false;
29 #endif
30 }
31
SetNumericProperty(const char * name,size_t value)32 bool SetNumericProperty(const char* name, size_t value) {
33 #if BUILDFLAG(USE_TCMALLOC)
34 return ::MallocExtension::instance()->SetNumericProperty(name, value);
35 #else
36 return false;
37 #endif
38 }
39
GetHeapSample(std::string * writer)40 void GetHeapSample(std::string* writer) {
41 #if BUILDFLAG(USE_TCMALLOC)
42 ::MallocExtension::instance()->GetHeapSample(writer);
43 #endif
44 }
45
IsHeapProfilerRunning()46 bool IsHeapProfilerRunning() {
47 #if BUILDFLAG(USE_TCMALLOC) && defined(ENABLE_PROFILING)
48 return ::IsHeapProfilerRunning();
49 #else
50 return false;
51 #endif
52 }
53
SetHooks(AllocHookFunc alloc_hook,FreeHookFunc free_hook)54 void SetHooks(AllocHookFunc alloc_hook, FreeHookFunc free_hook) {
55 // TODO(sque): Use allocator shim layer instead.
56 #if BUILDFLAG(USE_TCMALLOC)
57 // Make sure no hooks get overwritten.
58 auto prev_alloc_hook = MallocHook::SetNewHook(alloc_hook);
59 if (alloc_hook)
60 DCHECK(!prev_alloc_hook);
61
62 auto prev_free_hook = MallocHook::SetDeleteHook(free_hook);
63 if (free_hook)
64 DCHECK(!prev_free_hook);
65 #endif
66 }
67
GetCallStack(void ** stack,int max_stack_size)68 int GetCallStack(void** stack, int max_stack_size) {
69 #if BUILDFLAG(USE_TCMALLOC)
70 return MallocHook::GetCallerStackTrace(stack, max_stack_size, 0);
71 #else
72 return 0;
73 #endif
74 }
75
76 } // namespace allocator
77 } // namespace base
78