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

Side by Side Diff: third_party/tcmalloc/heap-checker.h

Issue 385049: Implement the memory leak annotations for heap leak checker. (Closed)
Patch Set: Created 11 years, 1 month 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
« no previous file with comments | « base/leak_annotations.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2005, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 // ---
31 // Author: Maxim Lifantsev (with design ideas by Sanjay Ghemawat)
32 //
33 //
34 // Module for detecing heap (memory) leaks.
35 //
36 // For full(er) information, see doc/heap_checker.html
37 //
38 // This module can be linked into programs with
39 // no slowdown caused by this unless you activate the leak-checker:
40 //
41 // 1. Set the environment variable HEAPCHEK to _type_ before
42 // running the program.
43 //
44 // _type_ is usually "normal" but can also be "minimal", "strict", or
45 // "draconian". (See the html file for other options, like 'local'.)
46 //
47 // After that, just run your binary. If the heap-checker detects
48 // a memory leak at program-exit, it will print instructions on how
49 // to track down the leak.
50
51 #ifndef BASE_HEAP_CHECKER_H_
52 #define BASE_HEAP_CHECKER_H_
53
54 #include "config.h"
55
56 #include <sys/types.h> // for size_t
57 #ifdef HAVE_STDINT_H
58 #include <stdint.h> // for uintptr_t
59 #endif
60 #include <stdarg.h> // for va_list
61 #include <vector>
62
63 // Annoying stuff for windows -- makes sure clients can import these functions
64 #ifndef PERFTOOLS_DLL_DECL
65 # ifdef _WIN32
66 # define PERFTOOLS_DLL_DECL __declspec(dllimport)
67 # else
68 # define PERFTOOLS_DLL_DECL
69 # endif
70 #endif
71
72
73 // The class is thread-safe with respect to all the provided static methods,
74 // as well as HeapLeakChecker objects: they can be accessed by multiple threads.
75 class PERFTOOLS_DLL_DECL HeapLeakChecker {
76 public:
77
78 // ----------------------------------------------------------------------- //
79 // Static functions for working with (whole-program) leak checking.
80
81 // If heap leak checking is currently active in some mode
82 // e.g. if leak checking was started (and is still active now)
83 // due to HEAPCHECK=... defined in the environment.
84 // The return value reflects iff HeapLeakChecker objects manually
85 // constructed right now will be doing leak checking or nothing.
86 // Note that we can go from active to inactive state during InitGoogle()
87 // if FLAGS_heap_check gets set to "" by some code before/during InitGoogle().
88 static bool IsActive();
89
90 // Return pointer to the whole-program checker if it has been created
91 // and NULL otherwise.
92 // Once GlobalChecker() returns non-NULL that object will not disappear and
93 // will be returned by all later GlobalChecker calls.
94 // This is mainly to access BytesLeaked() and ObjectsLeaked() (see below)
95 // for the whole-program checker after one calls NoGlobalLeaks()
96 // or similar and gets false.
97 static HeapLeakChecker* GlobalChecker();
98
99 // Do whole-program leak check now (if it was activated for this binary);
100 // return false only if it was activated and has failed.
101 // The mode of the check is controlled by the command-line flags.
102 // This method can be called repeatedly.
103 // Things like GlobalChecker()->SameHeap() can also be called explicitly
104 // to do the desired flavor of the check.
105 static bool NoGlobalLeaks();
106
107 // If whole-program checker if active,
108 // cancel its automatic execution after main() exits.
109 // This requires that some leak check (e.g. NoGlobalLeaks())
110 // has been called at least once on the whole-program checker.
111 static void CancelGlobalCheck();
112
113 // ----------------------------------------------------------------------- //
114 // Non-static functions for starting and doing leak checking.
115
116 // Start checking and name the leak check performed.
117 // The name is used in naming dumped profiles
118 // and needs to be unique only within your binary.
119 // It must also be a string that can be a part of a file name,
120 // in particular not contain path expressions.
121 explicit HeapLeakChecker(const char *name);
122
123 // Destructor (verifies that some *NoLeaks or *SameHeap method
124 // has been called at least once).
125 ~HeapLeakChecker();
126
127 // These used to be different but are all the same now: they return
128 // true iff all memory allocated since this HeapLeakChecker object
129 // was constructor is still reachable from global state.
130 //
131 // Because we fork to convert addresses to symbol-names, and forking
132 // is not thread-safe, and we may be called in a threaded context,
133 // we do not try to symbolize addresses when called manually.
134 bool NoLeaks() { return DoNoLeaks(DO_NOT_SYMBOLIZE); }
135
136 // These forms are obsolete; use NoLeaks() instead.
137 // TODO(csilvers): mark with ATTRIBUTE_DEPRECATED.
138 bool QuickNoLeaks() { return NoLeaks(); }
139 bool BriefNoLeaks() { return NoLeaks(); }
140 bool SameHeap() { return NoLeaks(); }
141 bool QuickSameHeap() { return NoLeaks(); }
142 bool BriefSameHeap() { return NoLeaks(); }
143
144 // Detailed information about the number of leaked bytes and objects
145 // (both of these can be negative as well).
146 // These are available only after a *SameHeap or *NoLeaks
147 // method has been called.
148 // Note that it's possible for both of these to be zero
149 // while SameHeap() or NoLeaks() returned false in case
150 // of a heap state change that is significant
151 // but preserves the byte and object counts.
152 ssize_t BytesLeaked() const;
153 ssize_t ObjectsLeaked() const;
154
155 // ----------------------------------------------------------------------- //
156 // Static helpers to make us ignore certain leaks.
157
158 // Scoped helper class. Should be allocated on the stack inside a
159 // block of code. Any heap allocations done in the code block
160 // covered by the scoped object (including in nested function calls
161 // done by the code block) will not be reported as leaks. This is
162 // the recommended replacement for the GetDisableChecksStart() and
163 // DisableChecksToHereFrom() routines below.
164 //
165 // Example:
166 // void Foo() {
167 // HeapLeakChecker::Disabler disabler;
168 // ... code that allocates objects whose leaks should be ignored ...
169 // }
170 //
171 // REQUIRES: Destructor runs in same thread as constructor
172 class Disabler {
173 public:
174 Disabler();
175 ~Disabler();
176 private:
177 Disabler(const Disabler&); // disallow copy
178 void operator=(const Disabler&); // and assign
179 };
180
181 // Ignore an object located at 'ptr' (can go at the start or into the object)
182 // as well as all heap objects (transitively) referenced from it
183 // for the purposes of heap leak checking.
184 // If 'ptr' does not point to an active allocated object
185 // at the time of this call, it is ignored;
186 // but if it does, the object must not get deleted from the heap later on;
187 // it must also be not already ignored at the time of this call.
188 //
189 // See also HiddenPointer, below, if you need to prevent a pointer from
190 // being traversed by the heap checker but do not wish to transitively
191 // whitelist objects referenced through it.
192 static void IgnoreObject(const void* ptr);
193
194 // Undo what an earlier IgnoreObject() call promised and asked to do.
195 // At the time of this call 'ptr' must point at or inside of an active
196 // allocated object which was previously registered with IgnoreObject().
197 static void UnIgnoreObject(const void* ptr);
198
199 // ----------------------------------------------------------------------- //
200 // Initialization; to be called from main() only.
201
202 // Full starting of recommended whole-program checking.
203 static void InternalInitStart();
204
205 // ----------------------------------------------------------------------- //
206 // Internal types defined in .cc
207
208 class Allocator;
209 struct RangeValue;
210
211 private:
212
213 // ----------------------------------------------------------------------- //
214 // Various helpers
215
216 // Create the name of the heap profile file.
217 // Should be deleted via Allocator::Free().
218 char* MakeProfileNameLocked();
219
220 // Helper for constructors
221 void Create(const char *name, bool make_start_snapshot);
222
223 enum ShouldSymbolize { SYMBOLIZE, DO_NOT_SYMBOLIZE };
224
225 // Helper for *NoLeaks and *SameHeap
226 bool DoNoLeaks(ShouldSymbolize should_symbolize);
227
228 // These used to be public, but they are now deprecated.
229 // Will remove entirely when all internal uses are fixed.
230 // In the meantime, use friendship so the unittest can still test them.
231 static void* GetDisableChecksStart();
232 static void DisableChecksToHereFrom(const void* start_address);
233 static void DisableChecksIn(const char* pattern);
234 friend void RangeDisabledLeaks();
235 friend void NamedTwoDisabledLeaks();
236 friend void* RunNamedDisabledLeaks(void*);
237 friend void TestHeapLeakCheckerNamedDisabling();
238 friend int main(int, char**);
239
240
241 // Helper for DisableChecksIn
242 static void DisableChecksInLocked(const char* pattern);
243
244 // Disable checks based on stack trace entry at a depth <=
245 // max_depth. Used to hide allocations done inside some special
246 // libraries.
247 static void DisableChecksFromToLocked(const void* start_address,
248 const void* end_address,
249 int max_depth);
250
251 // Helper for DoNoLeaks to ignore all objects reachable from all live data
252 static void IgnoreAllLiveObjectsLocked(const void* self_stack_top);
253
254 // Callback we pass to ListAllProcessThreads (see thread_lister.h)
255 // that is invoked when all threads of our process are found and stopped.
256 // The call back does the things needed to ignore live data reachable from
257 // thread stacks and registers for all our threads
258 // as well as do other global-live-data ignoring
259 // (via IgnoreNonThreadLiveObjectsLocked)
260 // during the quiet state of all threads being stopped.
261 // For the argument meaning see the comment by ListAllProcessThreads.
262 // Here we only use num_threads and thread_pids, that ListAllProcessThreads
263 // fills for us with the number and pids of all the threads of our process
264 // it found and attached to.
265 static int IgnoreLiveThreadsLocked(void* parameter,
266 int num_threads,
267 pid_t* thread_pids,
268 va_list ap);
269
270 // Helper for IgnoreAllLiveObjectsLocked and IgnoreLiveThreadsLocked
271 // that we prefer to execute from IgnoreLiveThreadsLocked
272 // while all threads are stopped.
273 // This helper does live object discovery and ignoring
274 // for all objects that are reachable from everything
275 // not related to thread stacks and registers.
276 static void IgnoreNonThreadLiveObjectsLocked();
277
278 // Helper for IgnoreNonThreadLiveObjectsLocked and IgnoreLiveThreadsLocked
279 // to discover and ignore all heap objects
280 // reachable from currently considered live objects
281 // (live_objects static global variable in out .cc file).
282 // "name", "name2" are two strings that we print one after another
283 // in a debug message to describe what kind of live object sources
284 // are being used.
285 static void IgnoreLiveObjectsLocked(const char* name, const char* name2);
286
287 // Runs REGISTER_HEAPCHECK_CLEANUP cleanups and potentially
288 // calls DoMainHeapCheck
289 static void RunHeapCleanups();
290
291 // Do the overall whole-program heap leak check if needed;
292 // returns true when did the leak check.
293 static bool DoMainHeapCheck();
294
295 // Type of task for UseProcMapsLocked
296 enum ProcMapsTask {
297 RECORD_GLOBAL_DATA,
298 DISABLE_LIBRARY_ALLOCS
299 };
300
301 // Success/Error Return codes for UseProcMapsLocked.
302 enum ProcMapsResult {
303 PROC_MAPS_USED,
304 CANT_OPEN_PROC_MAPS,
305 NO_SHARED_LIBS_IN_PROC_MAPS
306 };
307
308 // Read /proc/self/maps, parse it, and do the 'proc_maps_task' for each line.
309 static ProcMapsResult UseProcMapsLocked(ProcMapsTask proc_maps_task);
310
311 // A ProcMapsTask to disable allocations from 'library'
312 // that is mapped to [start_address..end_address)
313 // (only if library is a certain system library).
314 static void DisableLibraryAllocsLocked(const char* library,
315 uintptr_t start_address,
316 uintptr_t end_address);
317
318 // Return true iff "*ptr" points to a heap object
319 // ("*ptr" can point at the start or inside of a heap object
320 // so that this works e.g. for pointers to C++ arrays, C++ strings,
321 // multiple-inherited objects, or pointers to members).
322 // We also fill *object_size for this object then
323 // and we move "*ptr" to point to the very start of the heap object.
324 static inline bool HaveOnHeapLocked(const void** ptr, size_t* object_size);
325
326 // Helper to shutdown heap leak checker when it's not needed
327 // or can't function properly.
328 static void TurnItselfOffLocked();
329
330 // Internally-used c-tor to start whole-executable checking.
331 HeapLeakChecker();
332
333 // ----------------------------------------------------------------------- //
334 // Friends and externally accessed helpers.
335
336 // Helper for VerifyHeapProfileTableStackGet in the unittest
337 // to get the recorded allocation caller for ptr,
338 // which must be a heap object.
339 static const void* GetAllocCaller(void* ptr);
340 friend void VerifyHeapProfileTableStackGet();
341
342 // This gets to execute before constructors for all global objects
343 static void BeforeConstructorsLocked();
344 friend void HeapLeakChecker_BeforeConstructors();
345
346 // This gets to execute after destructors for all global objects
347 friend void HeapLeakChecker_AfterDestructors();
348
349 // ----------------------------------------------------------------------- //
350 // Member data.
351
352 class SpinLock* lock_; // to make HeapLeakChecker objects thread-safe
353 const char* name_; // our remembered name (we own it)
354 // NULL means this leak checker is a noop
355
356 // Snapshot taken when the checker was created. May be NULL
357 // for the global heap checker object. We use void* instead of
358 // HeapProfileTable::Snapshot* to avoid including heap-profile-table.h.
359 void* start_snapshot_;
360
361 bool has_checked_; // if we have done the leak check, so these are ready:
362 ssize_t inuse_bytes_increase_; // bytes-in-use increase for this checker
363 ssize_t inuse_allocs_increase_; // allocations-in-use increase
364 // for this checker
365 bool keep_profiles_; // iff we should keep the heap profiles we've made
366
367 // ----------------------------------------------------------------------- //
368
369 // Disallow "evil" constructors.
370 HeapLeakChecker(const HeapLeakChecker&);
371 void operator=(const HeapLeakChecker&);
372 };
373
374
375 // Holds a pointer that will not be traversed by the heap checker.
376 // Contrast with HeapLeakChecker::IgnoreObject(o), in which o and
377 // all objects reachable from o are ignored by the heap checker.
378 template <class T>
379 class HiddenPointer {
380 public:
381 explicit HiddenPointer(T* t)
382 : masked_t_(reinterpret_cast<uintptr_t>(t) ^ kHideMask) {
383 }
384 // Returns unhidden pointer. Be careful where you save the result.
385 T* get() const { return reinterpret_cast<T*>(masked_t_ ^ kHideMask); }
386
387 private:
388 // Arbitrary value, but not such that xor'ing with it is likely
389 // to map one valid pointer to another valid pointer:
390 static const uintptr_t kHideMask =
391 static_cast<uintptr_t>(0xF03A5F7BF03A5F7Bll);
392 uintptr_t masked_t_;
393 };
394
395 // A class that exists solely to run its destructor. This class should not be
396 // used directly, but instead by the REGISTER_HEAPCHECK_CLEANUP macro below.
397 class PERFTOOLS_DLL_DECL HeapCleaner {
398 public:
399 typedef void (*void_function)(void);
400 HeapCleaner(void_function f);
401 static void RunHeapCleanups();
402 private:
403 static std::vector<void_function>* heap_cleanups_;
404 };
405
406 // A macro to declare module heap check cleanup tasks
407 // (they run only if we are doing heap leak checking.)
408 // 'body' should be the cleanup code to run. 'name' doesn't matter,
409 // but must be unique amongst all REGISTER_HEAPCHECK_CLEANUP calls.
410 #define REGISTER_HEAPCHECK_CLEANUP(name, body) \
411 namespace { \
412 void heapcheck_cleanup_##name() { body; } \
413 static HeapCleaner heapcheck_cleaner_##name(&heapcheck_cleanup_##name); \
414 }
415
416 #endif // BASE_HEAP_CHECKER_H_
OLDNEW
« no previous file with comments | « base/leak_annotations.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698