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

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: Create CallStackManager out of LeakDetectorImpl Created 5 years, 3 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 <gperftools/custom_allocator.h>
8 #include <gperftools/malloc_extension.h>
9 #include <gperftools/malloc_hook.h>
10 #include <gperftools/spin_lock_wrapper.h>
11 #include <link.h>
12 #include <stdint.h>
13 #include <unistd.h>
14
15 #include <new>
16
17 #include "base/logging.h"
18 #include "components/metrics/leak_detector/leak_detector_impl.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 bool EnvToBool(const char* envname, const bool default_value) {
43 return !getenv(envname)
44 ? default_value
45 : memchr("tTyY1\0", getenv(envname)[0], 6) != NULL;
46 }
47
48 int EnvToInt(const char* envname, const int default_value) {
49 return !getenv(envname)
50 ? default_value
51 : strtol(getenv(envname), NULL, 10);
52 }
53
54 // Used for sampling allocs and frees. Randomly samples |g_sampling_factor|/256
55 // of the pointers being allocated and freed.
56 int g_sampling_factor = EnvToInt("LEAK_DETECTOR_SAMPLING_FACTOR", 1);
57
58 // The number of call stack levels to unwind when profiling allocations by call
59 // stack.
60 int g_stack_depth = EnvToInt("LEAK_DETECTOR_STACK_DEPTH", 4);
61
62 // Dump allocation stats and check for memory leaks after this many bytes have
63 // been allocated since the last dump/check. Does not get affected by sampling.
64 uint64_t g_dump_interval_bytes =
65 EnvToInt("LEAK_DETECTOR_DUMP_INTERVAL_KB", 32768) * 1024;
66
67 // Enable verbose logging. Dump all leak analysis data, not just analysis
68 // summaries and suspected leak reports.
69 bool g_dump_leak_analysis = EnvToBool("LEAK_DETECTOR_VERBOSE", false);
70
71 // The number of times an allocation size must be suspected as a leak before it
72 // gets reported.
73 int g_size_suspicion_threshold =
74 EnvToInt("LEAK_DETECTOR_SIZE_SUSPICION_THRESHOLD", 4);
75
76 // The number of times a call stack for a particular allocation size must be
77 // suspected as a leak before it gets reported.
78 int g_call_stack_suspicion_threshold =
79 EnvToInt("LEAK_DETECTOR_CALL_STACK_SUSPICION_THRESHOLD", 4);
80
81 // Use a simple spinlock for locking. Don't use a mutex, which can call malloc
82 // and cause infinite recursion.
83 SpinLockWrapper* g_heap_lock = nullptr;
84
85 // Points to the active instance of the leak detector.
86 // Modify this only when locked.
87 LeakDetectorImpl* g_leak_detector = nullptr;
88
89 // Keep track of the total number of bytes allocated.
90 // Modify this only when locked.
91 uint64_t g_total_alloc_size = 0;
92
93 // Keep track of the total alloc size when the last dump occurred.
94 // Modify this only when locked.
95 uint64_t g_last_alloc_dump_size = 0;
96
97 // Dump allocation stats and check for leaks after |g_dump_interval_bytes| bytes
98 // have been allocated since the last time that was done. Should be called with
99 // a lock since it modifies the global variable |g_last_alloc_dump_size|.
100 inline void MaybeDumpStatsAndCheckForLeaks() {
101 if (g_total_alloc_size > g_last_alloc_dump_size + g_dump_interval_bytes) {
102 g_last_alloc_dump_size = g_total_alloc_size;
103
104 InternalVector<InternalLeakReport> reports;
105 g_leak_detector->TestForLeaks(true /* do_logging */, &reports);
106 }
107 }
108
109 // Convert a pointer to a hash value. Returns only the upper eight bits.
110 inline uint64_t PointerToHash(const void* ptr) {
111 // The input data is the pointer address, not the location in memory pointed
112 // to by the pointer.
113 // The multiplier is taken from Farmhash code:
114 // https://github.com/google/farmhash/blob/master/src/farmhash.cc
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 *shared_object,
160 size_t /* size */,
161 void *data) {
162 if (g_dump_leak_analysis) {
163 LOG(ERROR) << "name=" << shared_object->dlpi_name << ", "
164 << "addr=" << std::hex << shared_object->dlpi_phnum;
165 }
166 for (int i = 0; i < shared_object->dlpi_phnum; i++) {
167 // Find the ELF segment header that contains the actual code of the Chrome
168 // binary.
169 const ElfW(Phdr)& segment_header = shared_object->dlpi_phdr[i];
170 if (segment_header.p_type == SHT_PROGBITS &&
171 segment_header.p_offset == 0 && data) {
172 MappingInfo* mapping = static_cast<MappingInfo*>(data);
173
174 // Make sure the fields in the ELF header and MappingInfo have the
175 // same size.
176 static_assert(sizeof(mapping->addr) == sizeof(shared_object->dlpi_addr),
177 "Integer size mismatch between MappingInfo::addr and "
178 "dl_phdr_info::dlpi_addr.");
179 static_assert(sizeof(mapping->size) == sizeof(segment_header.p_offset),
180 "Integer size mismatch between MappingInfo::size and "
181 "ElfW(Phdr)::p_memsz.");
182
183 mapping->addr = shared_object->dlpi_addr + segment_header.p_offset;
184 mapping->size = segment_header.p_memsz;
185 if (g_dump_leak_analysis) {
186 LOG(ERROR) << "Chrome mapped from " << std::hex
187 << mapping->addr << " to "
188 << mapping->addr + mapping->size;
189 }
190 return 1;
191 }
192 }
193 return 0;
194 }
195
196 } // namespace
197
198 void Initialize() {
199 // If the sampling factor is too low, don't bother enabling the leak detector.
200 if (g_sampling_factor < 1) {
201 LOG(ERROR) << "Not enabling leak detector because g_sampling_factor="
202 << g_sampling_factor;
203 return;
204 }
205
206 if (IsInitialized())
207 return;
208
209 // Locate the Chrome binary mapping before doing anything else.
210 dl_iterate_phdr(IterateLoadedObjects, &chrome_mapping);
211
212 // This should be done before the hooks are set up, since it should
213 // call new, and we want that to be accounted for correctly.
214 MallocExtension::Initialize();
215
216 if (CustomAllocator::IsInitialized()) {
217 LOG(ERROR) << "Custom allocator can only be initialized once!";
218 return;
219 }
220 CustomAllocator::Initialize();
221
222 g_heap_lock = new(CustomAllocator::Allocate(sizeof(SpinLockWrapper)))
223 SpinLockWrapper;
224
225 ScopedSpinLockHolder lock(g_heap_lock);
226 if (g_leak_detector)
227 return;
228
229 LOG(ERROR) << "Starting leak detector. Sampling factor: "
230 << g_sampling_factor;
231
232 g_leak_detector = new(CustomAllocator::Allocate(sizeof(LeakDetectorImpl)))
233 LeakDetectorImpl(chrome_mapping.addr,
234 chrome_mapping.size,
235 g_size_suspicion_threshold,
236 g_call_stack_suspicion_threshold,
237 g_dump_leak_analysis);
238
239 // Now set the hooks that capture new/delete and malloc/free. Make sure
240 // nothing is already set.
241 CHECK(MallocHook::SetNewHook(&NewHook) == nullptr);
242 CHECK(MallocHook::SetDeleteHook(&DeleteHook) == nullptr);
243 }
244
245 void Shutdown() {
246 if (!IsInitialized())
247 return;
248
249 {
250 ScopedSpinLockHolder lock(g_heap_lock);
251
252 // Unset our new/delete hooks, checking they were previously set.
253 CHECK_EQ(MallocHook::SetNewHook(nullptr), &NewHook);
254 CHECK_EQ(MallocHook::SetDeleteHook(nullptr), &DeleteHook);
255
256 g_leak_detector->~LeakDetectorImpl();
257 CustomAllocator::Free(g_leak_detector, sizeof(LeakDetectorImpl));
258 g_leak_detector = nullptr;
259 }
260
261 g_heap_lock->~SpinLockWrapper();
262 CustomAllocator::Free(g_heap_lock, sizeof(*g_heap_lock));
263
264 if (!CustomAllocator::Shutdown())
265 LOG(ERROR) << "Memory leak in LeakDetector, allocated objects remain.";
266
267 LOG(ERROR) << "Stopped leak detector.";
268 }
269
270 bool IsInitialized() {
271 return g_leak_detector;
272 }
273
274 } // namespace leak_detector
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698