Home | History | Annotate | Download | only in gperftools
      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 <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 for the
    185   // purposes of heap leak checking. Returns 'ptr' so that one can write
    186   //   static T* obj = IgnoreObject(new T(...));
    187   //
    188   // If 'ptr' does not point to an active allocated object at the time of this
    189   // call, it is ignored; but if it does, the object must not get deleted from
    190   // the heap later on.
    191   //
    192   // See also HiddenPointer, below, if you need to prevent a pointer from
    193   // being traversed by the heap checker but do not wish to transitively
    194   // whitelist objects referenced through it.
    195   template <typename T>
    196   static T* IgnoreObject(T* ptr) {
    197     DoIgnoreObject(static_cast<const void*>(const_cast<const T*>(ptr)));
    198     return ptr;
    199   }
    200 
    201   // Undo what an earlier IgnoreObject() call promised and asked to do.
    202   // At the time of this call 'ptr' must point at or inside of an active
    203   // allocated object which was previously registered with IgnoreObject().
    204   static void UnIgnoreObject(const void* ptr);
    205 
    206   // ----------------------------------------------------------------------- //
    207   // Internal types defined in .cc
    208 
    209   class Allocator;
    210   struct RangeValue;
    211 
    212  private:
    213 
    214   // ----------------------------------------------------------------------- //
    215   // Various helpers
    216 
    217   // Create the name of the heap profile file.
    218   // Should be deleted via Allocator::Free().
    219   char* MakeProfileNameLocked();
    220 
    221   // Helper for constructors
    222   void Create(const char *name, bool make_start_snapshot);
    223 
    224   enum ShouldSymbolize { SYMBOLIZE, DO_NOT_SYMBOLIZE };
    225 
    226   // Helper for *NoLeaks and *SameHeap
    227   bool DoNoLeaks(ShouldSymbolize should_symbolize);
    228 
    229   // Helper for NoGlobalLeaks, also called by the global destructor.
    230   static bool NoGlobalLeaksMaybeSymbolize(ShouldSymbolize should_symbolize);
    231 
    232   // These used to be public, but they are now deprecated.
    233   // Will remove entirely when all internal uses are fixed.
    234   // In the meantime, use friendship so the unittest can still test them.
    235   static void* GetDisableChecksStart();
    236   static void DisableChecksToHereFrom(const void* start_address);
    237   static void DisableChecksIn(const char* pattern);
    238   friend void RangeDisabledLeaks();
    239   friend void NamedTwoDisabledLeaks();
    240   friend void* RunNamedDisabledLeaks(void*);
    241   friend void TestHeapLeakCheckerNamedDisabling();
    242   // TODO(csilvers): remove this one, at least
    243   friend int main(int, char**);
    244 
    245 
    246   // Actually implements IgnoreObject().
    247   static void DoIgnoreObject(const void* ptr);
    248 
    249   // Disable checks based on stack trace entry at a depth <=
    250   // max_depth.  Used to hide allocations done inside some special
    251   // libraries.
    252   static void DisableChecksFromToLocked(const void* start_address,
    253                                         const void* end_address,
    254                                         int max_depth);
    255 
    256   // Helper for DoNoLeaks to ignore all objects reachable from all live data
    257   static void IgnoreAllLiveObjectsLocked(const void* self_stack_top);
    258 
    259   // Callback we pass to ListAllProcessThreads (see thread_lister.h)
    260   // that is invoked when all threads of our process are found and stopped.
    261   // The call back does the things needed to ignore live data reachable from
    262   // thread stacks and registers for all our threads
    263   // as well as do other global-live-data ignoring
    264   // (via IgnoreNonThreadLiveObjectsLocked)
    265   // during the quiet state of all threads being stopped.
    266   // For the argument meaning see the comment by ListAllProcessThreads.
    267   // Here we only use num_threads and thread_pids, that ListAllProcessThreads
    268   // fills for us with the number and pids of all the threads of our process
    269   // it found and attached to.
    270   static int IgnoreLiveThreadsLocked(void* parameter,
    271                                      int num_threads,
    272                                      pid_t* thread_pids,
    273                                      va_list ap);
    274 
    275   // Helper for IgnoreAllLiveObjectsLocked and IgnoreLiveThreadsLocked
    276   // that we prefer to execute from IgnoreLiveThreadsLocked
    277   // while all threads are stopped.
    278   // This helper does live object discovery and ignoring
    279   // for all objects that are reachable from everything
    280   // not related to thread stacks and registers.
    281   static void IgnoreNonThreadLiveObjectsLocked();
    282 
    283   // Helper for IgnoreNonThreadLiveObjectsLocked and IgnoreLiveThreadsLocked
    284   // to discover and ignore all heap objects
    285   // reachable from currently considered live objects
    286   // (live_objects static global variable in out .cc file).
    287   // "name", "name2" are two strings that we print one after another
    288   // in a debug message to describe what kind of live object sources
    289   // are being used.
    290   static void IgnoreLiveObjectsLocked(const char* name, const char* name2);
    291 
    292   // Do the overall whole-program heap leak check if needed;
    293   // returns true when did the leak check.
    294   static bool DoMainHeapCheck();
    295 
    296   // Type of task for UseProcMapsLocked
    297   enum ProcMapsTask {
    298     RECORD_GLOBAL_DATA,
    299     DISABLE_LIBRARY_ALLOCS
    300   };
    301 
    302   // Success/Error Return codes for UseProcMapsLocked.
    303   enum ProcMapsResult {
    304     PROC_MAPS_USED,
    305     CANT_OPEN_PROC_MAPS,
    306     NO_SHARED_LIBS_IN_PROC_MAPS
    307   };
    308 
    309   // Read /proc/self/maps, parse it, and do the 'proc_maps_task' for each line.
    310   static ProcMapsResult UseProcMapsLocked(ProcMapsTask proc_maps_task);
    311 
    312   // A ProcMapsTask to disable allocations from 'library'
    313   // that is mapped to [start_address..end_address)
    314   // (only if library is a certain system library).
    315   static void DisableLibraryAllocsLocked(const char* library,
    316                                          uintptr_t start_address,
    317                                          uintptr_t end_address);
    318 
    319   // Return true iff "*ptr" points to a heap object
    320   // ("*ptr" can point at the start or inside of a heap object
    321   //  so that this works e.g. for pointers to C++ arrays, C++ strings,
    322   //  multiple-inherited objects, or pointers to members).
    323   // We also fill *object_size for this object then
    324   // and we move "*ptr" to point to the very start of the heap object.
    325   static inline bool HaveOnHeapLocked(const void** ptr, size_t* object_size);
    326 
    327   // Helper to shutdown heap leak checker when it's not needed
    328   // or can't function properly.
    329   static void TurnItselfOffLocked();
    330 
    331   // Internally-used c-tor to start whole-executable checking.
    332   HeapLeakChecker();
    333 
    334   // ----------------------------------------------------------------------- //
    335   // Friends and externally accessed helpers.
    336 
    337   // Helper for VerifyHeapProfileTableStackGet in the unittest
    338   // to get the recorded allocation caller for ptr,
    339   // which must be a heap object.
    340   static const void* GetAllocCaller(void* ptr);
    341   friend void VerifyHeapProfileTableStackGet();
    342 
    343   // This gets to execute before constructors for all global objects
    344   static void BeforeConstructorsLocked();
    345   friend void HeapLeakChecker_BeforeConstructors();
    346 
    347   // This gets to execute after destructors for all global objects
    348   friend void HeapLeakChecker_AfterDestructors();
    349 
    350   // Full starting of recommended whole-program checking.
    351   friend void HeapLeakChecker_InternalInitStart();
    352 
    353   // Runs REGISTER_HEAPCHECK_CLEANUP cleanups and potentially
    354   // calls DoMainHeapCheck
    355   friend void HeapLeakChecker_RunHeapCleanups();
    356 
    357   // ----------------------------------------------------------------------- //
    358   // Member data.
    359 
    360   class SpinLock* lock_;  // to make HeapLeakChecker objects thread-safe
    361   const char* name_;  // our remembered name (we own it)
    362                       // NULL means this leak checker is a noop
    363 
    364   // Snapshot taken when the checker was created.  May be NULL
    365   // for the global heap checker object.  We use void* instead of
    366   // HeapProfileTable::Snapshot* to avoid including heap-profile-table.h.
    367   void* start_snapshot_;
    368 
    369   bool has_checked_;  // if we have done the leak check, so these are ready:
    370   ssize_t inuse_bytes_increase_;  // bytes-in-use increase for this checker
    371   ssize_t inuse_allocs_increase_;  // allocations-in-use increase
    372                                    // for this checker
    373   bool keep_profiles_;  // iff we should keep the heap profiles we've made
    374 
    375   // ----------------------------------------------------------------------- //
    376 
    377   // Disallow "evil" constructors.
    378   HeapLeakChecker(const HeapLeakChecker&);
    379   void operator=(const HeapLeakChecker&);
    380 };
    381 
    382 
    383 // Holds a pointer that will not be traversed by the heap checker.
    384 // Contrast with HeapLeakChecker::IgnoreObject(o), in which o and
    385 // all objects reachable from o are ignored by the heap checker.
    386 template <class T>
    387 class HiddenPointer {
    388  public:
    389   explicit HiddenPointer(T* t)
    390       : masked_t_(reinterpret_cast<uintptr_t>(t) ^ kHideMask) {
    391   }
    392   // Returns unhidden pointer.  Be careful where you save the result.
    393   T* get() const { return reinterpret_cast<T*>(masked_t_ ^ kHideMask); }
    394 
    395  private:
    396   // Arbitrary value, but not such that xor'ing with it is likely
    397   // to map one valid pointer to another valid pointer:
    398   static const uintptr_t kHideMask =
    399       static_cast<uintptr_t>(0xF03A5F7BF03A5F7Bll);
    400   uintptr_t masked_t_;
    401 };
    402 
    403 // A class that exists solely to run its destructor.  This class should not be
    404 // used directly, but instead by the REGISTER_HEAPCHECK_CLEANUP macro below.
    405 class PERFTOOLS_DLL_DECL HeapCleaner {
    406  public:
    407   typedef void (*void_function)(void);
    408   HeapCleaner(void_function f);
    409   static void RunHeapCleanups();
    410  private:
    411   static std::vector<void_function>* heap_cleanups_;
    412 };
    413 
    414 // A macro to declare module heap check cleanup tasks
    415 // (they run only if we are doing heap leak checking.)
    416 // 'body' should be the cleanup code to run.  'name' doesn't matter,
    417 // but must be unique amongst all REGISTER_HEAPCHECK_CLEANUP calls.
    418 #define REGISTER_HEAPCHECK_CLEANUP(name, body)  \
    419   namespace { \
    420   void heapcheck_cleanup_##name() { body; } \
    421   static HeapCleaner heapcheck_cleaner_##name(&heapcheck_cleanup_##name); \
    422   }
    423 
    424 #endif  // BASE_HEAP_CHECKER_H_
    425