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