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

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: Fix portability issues for sizes and addresses 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 uintptr_t addr;
35 size_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
jar (doing other things) 2015/08/15 03:29:01 I didn't understand this comment.
Simon Que 2015/08/15 23:28:31 Forgot to delete this from earlier code.
43 // naming conflict.
44
45 bool EnvToBool(const char* envname, const bool default_value) {
46 return !getenv(envname)
47 ? (default_value)
jar (doing other things) 2015/08/15 03:29:01 nit: delete parens (line 53 as well).
Simon Que 2015/08/15 23:28:31 Done.
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];
jar (doing other things) 2015/08/15 03:29:01 Can you provide better names?
Simon Que 2015/08/15 23:28:31 Done.
168 if (header.p_type == SHT_PROGBITS && header.p_offset == 0 && data) {
169 MappingInfo* mapping = static_cast<MappingInfo*>(data);
170
171 // Make sure the fields in the ELF header and MappingInfo have the
172 // same size.
173 static_assert(sizeof(mapping->addr) == sizeof(info->dlpi_addr),
174 "Integer size mismatch between MappingInfo::addr and "
175 "dl_phdr_info::dlpi_addr.");
176 static_assert(sizeof(mapping->size) == sizeof(header.p_offset),
177 "Integer size mismatch between MappingInfo::size and "
178 "ElfW(Phdr)::p_memsz.");
179
180 mapping->addr = info->dlpi_addr + header.p_offset;
181 mapping->size = header.p_memsz;
182 if (g_dump_leak_analysis) {
183 LOG(ERROR) << "Chrome mapped from " << std::hex
184 << mapping->addr << " to "
185 << mapping->addr + mapping->size;
186 }
187 return 1;
188 }
189 }
190 return 0;
191 }
192
193 } // namespace
194
195 // static
196 void LeakDetector::Initialize() {
197 // If the sampling factor is too low, don't bother enabling the leak detector.
198 if (g_sampling_factor < 1) {
199 LOG(ERROR) << "Not enabling leak detector because g_sampling_factor="
200 << g_sampling_factor;
201 return;
202 }
203
204 if (IsInitialized())
205 return;
206
207 // Locate the Chrome binary mapping before doing anything else.
208 dl_iterate_phdr(IterateLoadedObjects, &chrome_mapping);
209
210 // This should be done before the hooks are set up, since it should
211 // call new, and we want that to be accounted for correctly.
212 MallocExtension::Initialize();
213
214 if (CustomAllocator::IsInitialized()) {
215 LOG(ERROR) << "Custom allocator can only be initialized once!";
216 return;
217 }
218 CustomAllocator::Initialize();
219
220 g_heap_lock = new(CustomAllocator::Allocate(sizeof(SpinLockWrapper)))
221 SpinLockWrapper;
222
223 ScopedSpinLockHolder lock(g_heap_lock);
224 if (g_leak_detector)
225 return;
226
227 LOG(ERROR) << "%d: Starting leak detector. Sampling factor: "
228 << g_sampling_factor;
229
230 g_leak_detector = new(CustomAllocator::Allocate(sizeof(LeakDetectorImpl)))
231 LeakDetectorImpl(chrome_mapping.addr,
232 chrome_mapping.size,
233 g_size_suspicion_threshold,
234 g_call_stack_suspicion_threshold,
235 g_dump_leak_analysis);
236
237 // Now set the hooks that capture new/delete and malloc/free.
238 CHECK_EQ(MallocHook::SetNewHook(&NewHook), nullptr);
239 CHECK_EQ(MallocHook::SetDeleteHook(&DeleteHook), nullptr);
240 }
241
242 // static
243 void LeakDetector::Shutdown() {
244 {
245 ScopedSpinLockHolder lock(g_heap_lock);
246
247 if (!g_leak_detector)
248 return;
249
250 // Unset our new/delete hooks, checking they were previously set.
251 CHECK_EQ(MallocHook::SetNewHook(nullptr), &NewHook);
252 CHECK_EQ(MallocHook::SetDeleteHook(nullptr), &DeleteHook);
253
254 g_leak_detector->~LeakDetectorImpl();
255 CustomAllocator::Free(g_leak_detector, sizeof(LeakDetectorImpl));
256 g_leak_detector = nullptr;
257 }
258
259 g_heap_lock->~SpinLockWrapper();
260 CustomAllocator::Free(g_heap_lock, sizeof(*g_heap_lock));
261
262 if (!CustomAllocator::Shutdown())
263 LOG(ERROR) << "Memory leak in LeakDetector, allocated objects remain.";
264
265 LOG(ERROR) << "Stopped leak detector.";
266 }
267
268 // static
269 bool LeakDetector::IsInitialized() {
270 return g_leak_detector;
271 }
272
273 } // namespace leak_detector
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698