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