Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(550)

Side by Side Diff: components/metrics/leak_detector/leak_detector.cc

Issue 986503002: components/metrics: Add runtime memory leak detector (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Add LeakDetector class; Remove tcmalloc dependencies; Add export classes to gperftools; Remove farm… Created 5 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2015 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 "components/metrics/leak_detector/leak_detector.h"
6
7 #include <link.h>
8 #include <stdint.h>
9 #include <unistd.h>
10
11 #include <new>
12
13 #include "base/logging.h"
14 #include "components/metrics/leak_detector/leak_detector_impl.h"
15 #include <gperftools/custom_allocator.h>
16 #include <gperftools/malloc_extension.h>
17 #include <gperftools/malloc_hook.h>
18 #include <gperftools/spin_lock_wrapper.h>
19
20 namespace leak_detector {
21
22 namespace {
23
24 // We strip out different number of stack frames in debug mode
25 // because less inlining happens in that case
26 #ifdef NDEBUG
27 static const int kStripFrames = 2;
28 #else
29 static const int kStripFrames = 3;
30 #endif
31
32 // For storing the address range of the Chrome binary in memory.
33 struct MappingInfo {
34 uint64_t addr;
35 uint64_t size;
36 } chrome_mapping;
37
38 // TODO(sque): This is a temporary solution for leak detector params. Eventually
39 // params should be passed in from elsewhere in Chromium, and this file should
40 // be deleted.
41
42 // Remove existing macro definitions for the following functions so there is no
43 // naming conflict.
44
45 bool EnvToBool(const char* envname, const bool default_value) {
46 return !getenv(envname)
47 ? (default_value)
48 : memchr("tTyY1\0", getenv(envname)[0], 6) != NULL;
49 }
50
51 int EnvToInt(const char* envname, const int default_value) {
52 return !getenv(envname)
53 ? (default_value)
54 : strtol(getenv(envname), NULL, 10);
55 }
56
57 // Used for sampling allocs and frees. Randomly samples |g_sampling_factor|/256
58 // of the pointers being allocated and freed.
59 int g_sampling_factor = EnvToInt("LEAK_DETECTOR_SAMPLING_FACTOR", 1);
60
61 // The number of call stack levels to unwind when profiling allocations by call
62 // stack.
63 int g_stack_depth = EnvToInt("LEAK_DETECTOR_STACK_DEPTH", 4);
64
65 // Dump allocation stats and check for memory leaks after this many bytes have
66 // been allocated since the last dump/check. Does not get affected by sampling.
67 uint64_t g_dump_interval_bytes =
68 EnvToInt("LEAK_DETECTOR_DUMP_INTERVAL_KB", 32768) * 1024;
69
70 // Enable verbose logging. Dump all leak analysis data, not just analysis
71 // summaries and suspected leak reports.
72 bool g_dump_leak_analysis = EnvToBool("LEAK_DETECTOR_VERBOSE", false);
73
74 // The number of times an allocation size must be suspected as a leak before it
75 // gets reported.
76 int g_size_suspicion_threshold =
77 EnvToInt("LEAK_DETECTOR_SIZE_SUSPICION_THRESHOLD", 4);
78
79 // The number of times a call stack for a particular allocation size must be
80 // suspected as a leak before it gets reported.
81 int g_call_stack_suspicion_threshold =
82 EnvToInt("LEAK_DETECTOR_CALL_STACK_SUSPICION_THRESHOLD", 4);
83
84 // Use a simple spinlock for locking. Don't use a mutex, which can call malloc
85 // and cause infinite recursion.
86 SpinLockWrapper* g_heap_lock = nullptr;
87
88 // Points to the active instance of the leak detector.
89 // Modify this only when locked.
90 LeakDetectorImpl* g_leak_detector = nullptr;
91
92 // Keep track of the total number of bytes allocated.
93 // Modify this only when locked.
94 uint64_t g_total_alloc_size = 0;
95
96 // Keep track of the total alloc size when the last dump occurred.
97 // Modify this only when locked.
98 uint64_t g_last_alloc_dump_size = 0;
99
100 // Dump allocation stats and check for leaks after |g_dump_interval_bytes| bytes
101 // have been allocated since the last time that was done. Should be called with
102 // a lock since it modifies the global variable |g_last_alloc_dump_size|.
103 inline void MaybeDumpStatsAndCheckForLeaks() {
104 if (g_total_alloc_size > g_last_alloc_dump_size + g_dump_interval_bytes) {
105 g_leak_detector->DumpStats();
106 g_last_alloc_dump_size = g_total_alloc_size;
107 g_leak_detector->TestForLeaks();
108 }
109 }
110
111 // Convert a pointer to a hash value. Returns only the upper eight bits.
112 inline uint64_t PointerToHash(const void* ptr) {
113 // The input data is the pointer address, not the location in memory pointed
114 // to by the pointer.
115 const uint64_t kMultiplier = 0x9ddfea08eb382d69ULL;
116 uint64_t value = reinterpret_cast<uint64_t>(ptr) * kMultiplier;
117 return value >> 56;
118 }
119
120 // Uses PointerToHash() to pseudorandomly sample |ptr|.
121 inline bool ShouldSample(const void* ptr) {
122 return PointerToHash(ptr) < static_cast<uint64_t>(g_sampling_factor);
123 }
124
125 // Allocation/deallocation hooks for MallocHook.
126 void NewHook(const void* ptr, size_t size) {
127 {
128 ScopedSpinLockHolder lock(g_heap_lock);
129 g_total_alloc_size += size;
130 }
131
132 if (!ShouldSample(ptr) || !ptr || !g_leak_detector)
133 return;
134
135 // Take the stack trace outside the critical section.
136 // |g_leak_detector->ShouldGetStackTraceForSize()| is const; there is no need
137 // for a lock.
138 void* stack[g_stack_depth];
139 int depth = 0;
140 if (g_leak_detector->ShouldGetStackTraceForSize(size)) {
141 depth = MallocHook::GetCallerStackTrace(
142 stack, g_stack_depth, kStripFrames + 1);
143 }
144
145 ScopedSpinLockHolder lock(g_heap_lock);
146 g_leak_detector->RecordAlloc(ptr, size, depth, stack);
147 MaybeDumpStatsAndCheckForLeaks();
148 }
149
150 void DeleteHook(const void* ptr) {
151 if (!ShouldSample(ptr) || !ptr || !g_leak_detector)
152 return;
153
154 ScopedSpinLockHolder lock(g_heap_lock);
155 g_leak_detector->RecordFree(ptr);
156 }
157
158 // Callback for dl_iterate_phdr() to find the Chrome binary mapping.
159 int IterateLoadedObjects(struct dl_phdr_info *info,
160 size_t /* size */,
161 void *data) {
162 if (g_dump_leak_analysis) {
163 LOG(ERROR) << "name=" << info->dlpi_name << ", "
164 << "addr=" << std::hex << info->dlpi_phnum;
165 }
166 for (int i = 0; i < info->dlpi_phnum; i++) {
167 const ElfW(Phdr)& header = info->dlpi_phdr[i];
168 if (header.p_type == SHT_PROGBITS && header.p_offset == 0 && data) {
169 MappingInfo* mapping = static_cast<MappingInfo*>(data);
170 mapping->addr = info->dlpi_addr + header.p_offset;
171 mapping->size = header.p_memsz;
172 if (g_dump_leak_analysis) {
173 LOG(ERROR) << "Chrome mapped from " << std::hex
174 << mapping->addr << " to "
175 << mapping->addr + mapping->size;
176 }
177 return 1;
178 }
179 }
180 return 0;
181 }
182
183 } // namespace
184
185 // static
186 void LeakDetector::Initialize() {
187 // If the sampling factor is too low, don't bother enabling the leak detector.
188 if (g_sampling_factor < 1) {
189 LOG(ERROR) << "Not enabling leak detector because g_sampling_factor="
190 << g_sampling_factor;
191 return;
192 }
193
194 if (IsInitialized())
195 return;
196
197 // Locate the Chrome binary mapping before doing anything else.
198 dl_iterate_phdr(IterateLoadedObjects, &chrome_mapping);
199
200 // This should be done before the hooks are set up, since it should
201 // call new, and we want that to be accounted for correctly.
202 MallocExtension::Initialize();
203
204 if (CustomAllocator::IsInitialized()) {
205 LOG(ERROR) << "Custom allocator can only be initialized once!";
206 return;
207 }
208 CustomAllocator::Initialize();
209
210 g_heap_lock = new(CustomAllocator::Allocate(sizeof(SpinLockWrapper)))
211 SpinLockWrapper;
212
213 ScopedSpinLockHolder lock(g_heap_lock);
214 if (g_leak_detector)
215 return;
216
217 LOG(ERROR) << "%d: Starting leak detector. Sampling factor: "
218 << g_sampling_factor;
219
220 g_leak_detector = new(CustomAllocator::Allocate(sizeof(LeakDetectorImpl)))
221 LeakDetectorImpl(chrome_mapping.addr,
222 chrome_mapping.size,
223 g_size_suspicion_threshold,
224 g_call_stack_suspicion_threshold,
225 g_dump_leak_analysis);
226
227 // Now set the hooks that capture new/delete and malloc/free.
228 CHECK_EQ(MallocHook::SetNewHook(&NewHook), nullptr);
229 CHECK_EQ(MallocHook::SetDeleteHook(&DeleteHook), nullptr);
230 }
231
232 // static
233 void LeakDetector::Shutdown() {
234 {
235 ScopedSpinLockHolder lock(g_heap_lock);
236
237 if (!g_leak_detector)
238 return;
239
240 // Unset our new/delete hooks, checking they were previously set.
241 CHECK_EQ(MallocHook::SetNewHook(nullptr), &NewHook);
242 CHECK_EQ(MallocHook::SetDeleteHook(nullptr), &DeleteHook);
243
244 g_leak_detector->~LeakDetectorImpl();
245 CustomAllocator::Free(g_leak_detector, sizeof(LeakDetectorImpl));
246 g_leak_detector = nullptr;
247 }
248
249 g_heap_lock->~SpinLockWrapper();
250 CustomAllocator::Free(g_heap_lock, sizeof(*g_heap_lock));
251
252 if (!CustomAllocator::Shutdown())
253 LOG(ERROR) << "Memory leak in LeakDetector, allocated objects remain.";
254
255 LOG(ERROR) << "Stopped leak detector.";
256 }
257
258 // static
259 bool LeakDetector::IsInitialized() {
260 return g_leak_detector;
261 }
262
263 } // namespace leak_detector
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698