heap-checker.cc 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388
  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. // All Rights Reserved.
  32. //
  33. // Author: Maxim Lifantsev
  34. //
  35. #include "config.h"
  36. #include <fcntl.h> // for O_RDONLY (we use syscall to do actual reads)
  37. #include <string.h>
  38. #include <errno.h>
  39. #ifdef HAVE_UNISTD_H
  40. #include <unistd.h>
  41. #endif
  42. #ifdef HAVE_MMAP
  43. #include <sys/mman.h>
  44. #endif
  45. #ifdef HAVE_PTHREAD
  46. #include <pthread.h>
  47. #endif
  48. #include <sys/stat.h>
  49. #include <sys/types.h>
  50. #include <time.h>
  51. #include <assert.h>
  52. #if defined(HAVE_LINUX_PTRACE_H)
  53. #include <linux/ptrace.h>
  54. #endif
  55. #ifdef HAVE_SYS_SYSCALL_H
  56. #include <sys/syscall.h>
  57. #endif
  58. #if defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__MINGW32__)
  59. #include <wtypes.h>
  60. #include <winbase.h>
  61. #undef ERROR // windows defines these as macros, which can cause trouble
  62. #undef max
  63. #undef min
  64. #endif
  65. #include <string>
  66. #include <vector>
  67. #include <map>
  68. #include <set>
  69. #include <algorithm>
  70. #include <functional>
  71. #include <gperftools/heap-checker.h>
  72. #include "base/basictypes.h"
  73. #include "base/googleinit.h"
  74. #include "base/logging.h"
  75. #include <gperftools/stacktrace.h>
  76. #include "base/commandlineflags.h"
  77. #include "base/elfcore.h" // for i386_regs
  78. #include "base/thread_lister.h"
  79. #include "heap-profile-table.h"
  80. #include "base/low_level_alloc.h"
  81. #include "malloc_hook-inl.h"
  82. #include <gperftools/malloc_hook.h>
  83. #include <gperftools/malloc_extension.h>
  84. #include "maybe_threads.h"
  85. #include "memory_region_map.h"
  86. #include "base/spinlock.h"
  87. #include "base/sysinfo.h"
  88. #include "base/stl_allocator.h"
  89. using std::string;
  90. using std::basic_string;
  91. using std::pair;
  92. using std::map;
  93. using std::set;
  94. using std::vector;
  95. using std::swap;
  96. using std::make_pair;
  97. using std::min;
  98. using std::max;
  99. using std::less;
  100. using std::char_traits;
  101. // If current process is being ptrace()d, 'TracerPid' in /proc/self/status
  102. // will be non-zero.
  103. static bool IsDebuggerAttached(void) { // only works under linux, probably
  104. char buf[256]; // TracerPid comes relatively earlier in status output
  105. int fd = open("/proc/self/status", O_RDONLY);
  106. if (fd == -1) {
  107. return false; // Can't tell for sure.
  108. }
  109. const int len = read(fd, buf, sizeof(buf));
  110. bool rc = false;
  111. if (len > 0) {
  112. const char *const kTracerPid = "TracerPid:\t";
  113. buf[len - 1] = '\0';
  114. const char *p = strstr(buf, kTracerPid);
  115. if (p != NULL) {
  116. rc = (strncmp(p + strlen(kTracerPid), "0\n", 2) != 0);
  117. }
  118. }
  119. close(fd);
  120. return rc;
  121. }
  122. // This is the default if you don't link in -lprofiler
  123. extern "C" {
  124. ATTRIBUTE_WEAK PERFTOOLS_DLL_DECL bool ProfilingIsEnabledForAllThreads();
  125. bool ProfilingIsEnabledForAllThreads() { return false; }
  126. }
  127. //----------------------------------------------------------------------
  128. // Flags that control heap-checking
  129. //----------------------------------------------------------------------
  130. DEFINE_string(heap_check,
  131. EnvToString("HEAPCHECK", ""),
  132. "The heap leak checking to be done over the whole executable: "
  133. "\"minimal\", \"normal\", \"strict\", "
  134. "\"draconian\", \"as-is\", and \"local\" "
  135. " or the empty string are the supported choices. "
  136. "(See HeapLeakChecker_InternalInitStart for details.)");
  137. DEFINE_bool(heap_check_report, true, "Obsolete");
  138. DEFINE_bool(heap_check_before_constructors,
  139. true,
  140. "deprecated; pretty much always true now");
  141. DEFINE_bool(heap_check_after_destructors,
  142. EnvToBool("HEAP_CHECK_AFTER_DESTRUCTORS", false),
  143. "If overall heap check is to end after global destructors "
  144. "or right after all REGISTER_HEAPCHECK_CLEANUP's");
  145. DEFINE_bool(heap_check_strict_check, true, "Obsolete");
  146. DEFINE_bool(heap_check_ignore_global_live,
  147. EnvToBool("HEAP_CHECK_IGNORE_GLOBAL_LIVE", true),
  148. "If overall heap check is to ignore heap objects reachable "
  149. "from the global data");
  150. DEFINE_bool(heap_check_identify_leaks,
  151. EnvToBool("HEAP_CHECK_IDENTIFY_LEAKS", false),
  152. "If heap check should generate the addresses of the leaked "
  153. "objects in the memory leak profiles. This may be useful "
  154. "in tracking down leaks where only a small fraction of "
  155. "objects allocated at the same stack trace are leaked.");
  156. DEFINE_bool(heap_check_ignore_thread_live,
  157. EnvToBool("HEAP_CHECK_IGNORE_THREAD_LIVE", true),
  158. "If set to true, objects reachable from thread stacks "
  159. "and registers are not reported as leaks");
  160. DEFINE_bool(heap_check_test_pointer_alignment,
  161. EnvToBool("HEAP_CHECK_TEST_POINTER_ALIGNMENT", false),
  162. "Set to true to check if the found leak can be due to "
  163. "use of unaligned pointers");
  164. // Alignment at which all pointers in memory are supposed to be located;
  165. // use 1 if any alignment is ok.
  166. // heap_check_test_pointer_alignment flag guides if we try the value of 1.
  167. // The larger it can be, the lesser is the chance of missing real leaks.
  168. static const size_t kPointerSourceAlignment = sizeof(void*);
  169. DEFINE_int32(heap_check_pointer_source_alignment,
  170. EnvToInt("HEAP_CHECK_POINTER_SOURCE_ALIGNMENT",
  171. kPointerSourceAlignment),
  172. "Alignment at which all pointers in memory are supposed to be "
  173. "located. Use 1 if any alignment is ok.");
  174. // A reasonable default to handle pointers inside of typical class objects:
  175. // Too low and we won't be able to traverse pointers to normally-used
  176. // nested objects and base parts of multiple-inherited objects.
  177. // Too high and it will both slow down leak checking (FindInsideAlloc
  178. // in HaveOnHeapLocked will get slower when there are large on-heap objects)
  179. // and make it probabilistically more likely to miss leaks
  180. // of large-sized objects.
  181. static const int64 kHeapCheckMaxPointerOffset = 1024;
  182. DEFINE_int64(heap_check_max_pointer_offset,
  183. EnvToInt("HEAP_CHECK_MAX_POINTER_OFFSET",
  184. kHeapCheckMaxPointerOffset),
  185. "Largest pointer offset for which we traverse "
  186. "pointers going inside of heap allocated objects. "
  187. "Set to -1 to use the actual largest heap object size.");
  188. DEFINE_bool(heap_check_run_under_gdb,
  189. EnvToBool("HEAP_CHECK_RUN_UNDER_GDB", false),
  190. "If false, turns off heap-checking library when running under gdb "
  191. "(normally, set to 'true' only when debugging the heap-checker)");
  192. DEFINE_int32(heap_check_delay_seconds, 0,
  193. "Number of seconds to delay on-exit heap checking."
  194. " If you set this flag,"
  195. " you may also want to set exit_timeout_seconds in order to"
  196. " avoid exit timeouts.\n"
  197. "NOTE: This flag is to be used only to help diagnose issues"
  198. " where it is suspected that the heap checker is reporting"
  199. " false leaks that will disappear if the heap checker delays"
  200. " its checks. Report any such issues to the heap-checker"
  201. " maintainer(s).");
  202. //----------------------------------------------------------------------
  203. DEFINE_string(heap_profile_pprof,
  204. EnvToString("PPROF_PATH", "pprof"),
  205. "OBSOLETE; not used");
  206. DEFINE_string(heap_check_dump_directory,
  207. EnvToString("HEAP_CHECK_DUMP_DIRECTORY", "/tmp"),
  208. "Directory to put heap-checker leak dump information");
  209. //----------------------------------------------------------------------
  210. // HeapLeakChecker global data
  211. //----------------------------------------------------------------------
  212. // Global lock for all the global data of this module.
  213. static SpinLock heap_checker_lock(SpinLock::LINKER_INITIALIZED);
  214. //----------------------------------------------------------------------
  215. // Heap profile prefix for leak checking profiles.
  216. // Gets assigned once when leak checking is turned on, then never modified.
  217. static const string* profile_name_prefix = NULL;
  218. // Whole-program heap leak checker.
  219. // Gets assigned once when leak checking is turned on,
  220. // then main_heap_checker is never deleted.
  221. static HeapLeakChecker* main_heap_checker = NULL;
  222. // Whether we will use main_heap_checker to do a check at program exit
  223. // automatically. In any case user can ask for more checks on main_heap_checker
  224. // via GlobalChecker().
  225. static bool do_main_heap_check = false;
  226. // The heap profile we use to collect info about the heap.
  227. // This is created in HeapLeakChecker::BeforeConstructorsLocked
  228. // together with setting heap_checker_on (below) to true
  229. // and registering our new/delete malloc hooks;
  230. // similarly all are unset in HeapLeakChecker::TurnItselfOffLocked.
  231. static HeapProfileTable* heap_profile = NULL;
  232. // If we are doing (or going to do) any kind of heap-checking.
  233. static bool heap_checker_on = false;
  234. // pid of the process that does whole-program heap leak checking
  235. static pid_t heap_checker_pid = 0;
  236. // If we did heap profiling during global constructors execution
  237. static bool constructor_heap_profiling = false;
  238. // RAW_VLOG level we dump key INFO messages at. If you want to turn
  239. // off these messages, set the environment variable PERFTOOLS_VERBOSE=-1.
  240. static const int heap_checker_info_level = 0;
  241. //----------------------------------------------------------------------
  242. // HeapLeakChecker's own memory allocator that is
  243. // independent of the normal program allocator.
  244. //----------------------------------------------------------------------
  245. // Wrapper of LowLevelAlloc for STL_Allocator and direct use.
  246. // We always access this class under held heap_checker_lock,
  247. // this allows us to in particular protect the period when threads are stopped
  248. // at random spots with TCMalloc_ListAllProcessThreads by heap_checker_lock,
  249. // w/o worrying about the lock in LowLevelAlloc::Arena.
  250. // We rely on the fact that we use an own arena with an own lock here.
  251. class HeapLeakChecker::Allocator {
  252. public:
  253. static void Init() {
  254. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  255. RAW_DCHECK(arena_ == NULL, "");
  256. arena_ = LowLevelAlloc::NewArena(0, LowLevelAlloc::DefaultArena());
  257. }
  258. static void Shutdown() {
  259. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  260. if (!LowLevelAlloc::DeleteArena(arena_) || alloc_count_ != 0) {
  261. RAW_LOG(FATAL, "Internal heap checker leak of %d objects", alloc_count_);
  262. }
  263. }
  264. static int alloc_count() {
  265. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  266. return alloc_count_;
  267. }
  268. static void* Allocate(size_t n) {
  269. RAW_DCHECK(arena_ && heap_checker_lock.IsHeld(), "");
  270. void* p = LowLevelAlloc::AllocWithArena(n, arena_);
  271. if (p) alloc_count_ += 1;
  272. return p;
  273. }
  274. static void Free(void* p) {
  275. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  276. if (p) alloc_count_ -= 1;
  277. LowLevelAlloc::Free(p);
  278. }
  279. static void Free(void* p, size_t /* n */) {
  280. Free(p);
  281. }
  282. // destruct, free, and make *p to be NULL
  283. template<typename T> static void DeleteAndNull(T** p) {
  284. (*p)->~T();
  285. Free(*p);
  286. *p = NULL;
  287. }
  288. template<typename T> static void DeleteAndNullIfNot(T** p) {
  289. if (*p != NULL) DeleteAndNull(p);
  290. }
  291. private:
  292. static LowLevelAlloc::Arena* arena_;
  293. static int alloc_count_;
  294. };
  295. LowLevelAlloc::Arena* HeapLeakChecker::Allocator::arena_ = NULL;
  296. int HeapLeakChecker::Allocator::alloc_count_ = 0;
  297. //----------------------------------------------------------------------
  298. // HeapLeakChecker live object tracking components
  299. //----------------------------------------------------------------------
  300. // Cases of live object placement we distinguish
  301. enum ObjectPlacement {
  302. MUST_BE_ON_HEAP, // Must point to a live object of the matching size in the
  303. // heap_profile map of the heap when we get to it
  304. IGNORED_ON_HEAP, // Is a live (ignored) object on heap
  305. MAYBE_LIVE, // Is a piece of writable memory from /proc/self/maps
  306. IN_GLOBAL_DATA, // Is part of global data region of the executable
  307. THREAD_DATA, // Part of a thread stack and a thread descriptor with TLS
  308. THREAD_REGISTERS, // Values in registers of some thread
  309. };
  310. // Information about an allocated object
  311. struct AllocObject {
  312. const void* ptr; // the object
  313. uintptr_t size; // its size
  314. ObjectPlacement place; // where ptr points to
  315. AllocObject(const void* p, size_t s, ObjectPlacement l)
  316. : ptr(p), size(s), place(l) { }
  317. };
  318. // All objects (memory ranges) ignored via HeapLeakChecker::IgnoreObject
  319. // Key is the object's address; value is its size.
  320. typedef map<uintptr_t, size_t, less<uintptr_t>,
  321. STL_Allocator<pair<const uintptr_t, size_t>,
  322. HeapLeakChecker::Allocator>
  323. > IgnoredObjectsMap;
  324. static IgnoredObjectsMap* ignored_objects = NULL;
  325. // All objects (memory ranges) that we consider to be the sources of pointers
  326. // to live (not leaked) objects.
  327. // At different times this holds (what can be reached from) global data regions
  328. // and the objects we've been told to ignore.
  329. // For any AllocObject::ptr "live_objects" is supposed to contain at most one
  330. // record at any time. We maintain this by checking with the heap_profile map
  331. // of the heap and removing the live heap objects we've handled from it.
  332. // This vector is maintained as a stack and the frontier of reachable
  333. // live heap objects in our flood traversal of them.
  334. typedef vector<AllocObject,
  335. STL_Allocator<AllocObject, HeapLeakChecker::Allocator>
  336. > LiveObjectsStack;
  337. static LiveObjectsStack* live_objects = NULL;
  338. // A special string type that uses my allocator
  339. typedef basic_string<char, char_traits<char>,
  340. STL_Allocator<char, HeapLeakChecker::Allocator>
  341. > HCL_string;
  342. // A placeholder to fill-in the starting values for live_objects
  343. // for each library so we can keep the library-name association for logging.
  344. typedef map<HCL_string, LiveObjectsStack, less<HCL_string>,
  345. STL_Allocator<pair<const HCL_string, LiveObjectsStack>,
  346. HeapLeakChecker::Allocator>
  347. > LibraryLiveObjectsStacks;
  348. static LibraryLiveObjectsStacks* library_live_objects = NULL;
  349. // Value stored in the map of disabled address ranges;
  350. // its key is the end of the address range.
  351. // We'll ignore allocations with a return address in a disabled range
  352. // if the address occurs at 'max_depth' or less in the stack trace.
  353. struct HeapLeakChecker::RangeValue {
  354. uintptr_t start_address; // the start of the range
  355. int max_depth; // the maximal stack depth to disable at
  356. };
  357. typedef map<uintptr_t, HeapLeakChecker::RangeValue, less<uintptr_t>,
  358. STL_Allocator<pair<const uintptr_t, HeapLeakChecker::RangeValue>,
  359. HeapLeakChecker::Allocator>
  360. > DisabledRangeMap;
  361. // The disabled program counter address ranges for profile dumping
  362. // that are registered with HeapLeakChecker::DisableChecksFromToLocked.
  363. static DisabledRangeMap* disabled_ranges = NULL;
  364. // Set of stack tops.
  365. // These are used to consider live only appropriate chunks of the memory areas
  366. // that are used for stacks (and maybe thread-specific data as well)
  367. // so that we do not treat pointers from outdated stack frames as live.
  368. typedef set<uintptr_t, less<uintptr_t>,
  369. STL_Allocator<uintptr_t, HeapLeakChecker::Allocator>
  370. > StackTopSet;
  371. static StackTopSet* stack_tops = NULL;
  372. // A map of ranges of code addresses for the system libraries
  373. // that can mmap/mremap/sbrk-allocate memory regions for stacks
  374. // and thread-local storage that we want to consider as live global data.
  375. // Maps from the end address to the start address.
  376. typedef map<uintptr_t, uintptr_t, less<uintptr_t>,
  377. STL_Allocator<pair<const uintptr_t, uintptr_t>,
  378. HeapLeakChecker::Allocator>
  379. > GlobalRegionCallerRangeMap;
  380. static GlobalRegionCallerRangeMap* global_region_caller_ranges = NULL;
  381. // TODO(maxim): make our big data structs into own modules
  382. // Disabler is implemented by keeping track of a per-thread count
  383. // of active Disabler objects. Any objects allocated while the
  384. // count > 0 are not reported.
  385. #ifdef HAVE_TLS
  386. static __thread int thread_disable_counter
  387. // The "inital exec" model is faster than the default TLS model, at
  388. // the cost you can't dlopen this library. But dlopen on heap-checker
  389. // doesn't work anyway -- it must run before main -- so this is a good
  390. // trade-off.
  391. # ifdef HAVE___ATTRIBUTE__
  392. __attribute__ ((tls_model ("initial-exec")))
  393. # endif
  394. ;
  395. inline int get_thread_disable_counter() {
  396. return thread_disable_counter;
  397. }
  398. inline void set_thread_disable_counter(int value) {
  399. thread_disable_counter = value;
  400. }
  401. #else // #ifdef HAVE_TLS
  402. static pthread_key_t thread_disable_counter_key;
  403. static int main_thread_counter; // storage for use before main()
  404. static bool use_main_thread_counter = true;
  405. // TODO(csilvers): this is called from NewHook, in the middle of malloc().
  406. // If perftools_pthread_getspecific calls malloc, that will lead to an
  407. // infinite loop. I don't know how to fix that, so I hope it never happens!
  408. inline int get_thread_disable_counter() {
  409. if (use_main_thread_counter) // means we're running really early
  410. return main_thread_counter;
  411. void* p = perftools_pthread_getspecific(thread_disable_counter_key);
  412. return (intptr_t)p; // kinda evil: store the counter directly in the void*
  413. }
  414. inline void set_thread_disable_counter(int value) {
  415. if (use_main_thread_counter) { // means we're running really early
  416. main_thread_counter = value;
  417. return;
  418. }
  419. intptr_t pointer_sized_value = value;
  420. // kinda evil: store the counter directly in the void*
  421. void* p = (void*)pointer_sized_value;
  422. // NOTE: this may call malloc, which will call NewHook which will call
  423. // get_thread_disable_counter() which will call pthread_getspecific(). I
  424. // don't know if anything bad can happen if we call getspecific() in the
  425. // middle of a setspecific() call. It seems to work ok in practice...
  426. perftools_pthread_setspecific(thread_disable_counter_key, p);
  427. }
  428. // The idea here is that this initializer will run pretty late: after
  429. // pthreads have been totally set up. At this point we can call
  430. // pthreads routines, so we set those up.
  431. class InitThreadDisableCounter {
  432. public:
  433. InitThreadDisableCounter() {
  434. perftools_pthread_key_create(&thread_disable_counter_key, NULL);
  435. // Set up the main thread's value, which we have a special variable for.
  436. void* p = (void*)main_thread_counter; // store the counter directly
  437. perftools_pthread_setspecific(thread_disable_counter_key, p);
  438. use_main_thread_counter = false;
  439. }
  440. };
  441. InitThreadDisableCounter init_thread_disable_counter;
  442. #endif // #ifdef HAVE_TLS
  443. HeapLeakChecker::Disabler::Disabler() {
  444. // It is faster to unconditionally increment the thread-local
  445. // counter than to check whether or not heap-checking is on
  446. // in a thread-safe manner.
  447. int counter = get_thread_disable_counter();
  448. set_thread_disable_counter(counter + 1);
  449. RAW_VLOG(10, "Increasing thread disable counter to %d", counter + 1);
  450. }
  451. HeapLeakChecker::Disabler::~Disabler() {
  452. int counter = get_thread_disable_counter();
  453. RAW_DCHECK(counter > 0, "");
  454. if (counter > 0) {
  455. set_thread_disable_counter(counter - 1);
  456. RAW_VLOG(10, "Decreasing thread disable counter to %d", counter);
  457. } else {
  458. RAW_VLOG(0, "Thread disable counter underflow : %d", counter);
  459. }
  460. }
  461. //----------------------------------------------------------------------
  462. // The size of the largest heap object allocated so far.
  463. static size_t max_heap_object_size = 0;
  464. // The possible range of addresses that can point
  465. // into one of the elements of heap_objects.
  466. static uintptr_t min_heap_address = uintptr_t(-1LL);
  467. static uintptr_t max_heap_address = 0;
  468. //----------------------------------------------------------------------
  469. // Simple casting helpers for uintptr_t and void*:
  470. template<typename T>
  471. inline static const void* AsPtr(T addr) {
  472. return reinterpret_cast<void*>(addr);
  473. }
  474. inline static uintptr_t AsInt(const void* ptr) {
  475. return reinterpret_cast<uintptr_t>(ptr);
  476. }
  477. //----------------------------------------------------------------------
  478. // We've seen reports that strstr causes heap-checker crashes in some
  479. // libc's (?):
  480. // http://code.google.com/p/gperftools/issues/detail?id=263
  481. // It's simple enough to use our own. This is not in time-critical code.
  482. static const char* hc_strstr(const char* s1, const char* s2) {
  483. const size_t len = strlen(s2);
  484. RAW_CHECK(len > 0, "Unexpected empty string passed to strstr()");
  485. for (const char* p = strchr(s1, *s2); p != NULL; p = strchr(p+1, *s2)) {
  486. if (strncmp(p, s2, len) == 0) {
  487. return p;
  488. }
  489. }
  490. return NULL;
  491. }
  492. //----------------------------------------------------------------------
  493. // Our hooks for MallocHook
  494. static void NewHook(const void* ptr, size_t size) {
  495. if (ptr != NULL) {
  496. const int counter = get_thread_disable_counter();
  497. const bool ignore = (counter > 0);
  498. RAW_VLOG(16, "Recording Alloc: %p of %" PRIuS "; %d", ptr, size,
  499. int(counter));
  500. // Fetch the caller's stack trace before acquiring heap_checker_lock.
  501. void* stack[HeapProfileTable::kMaxStackDepth];
  502. int depth = HeapProfileTable::GetCallerStackTrace(0, stack);
  503. { SpinLockHolder l(&heap_checker_lock);
  504. if (size > max_heap_object_size) max_heap_object_size = size;
  505. uintptr_t addr = AsInt(ptr);
  506. if (addr < min_heap_address) min_heap_address = addr;
  507. addr += size;
  508. if (addr > max_heap_address) max_heap_address = addr;
  509. if (heap_checker_on) {
  510. heap_profile->RecordAlloc(ptr, size, depth, stack);
  511. if (ignore) {
  512. heap_profile->MarkAsIgnored(ptr);
  513. }
  514. }
  515. }
  516. RAW_VLOG(17, "Alloc Recorded: %p of %" PRIuS "", ptr, size);
  517. }
  518. }
  519. static void DeleteHook(const void* ptr) {
  520. if (ptr != NULL) {
  521. RAW_VLOG(16, "Recording Free %p", ptr);
  522. { SpinLockHolder l(&heap_checker_lock);
  523. if (heap_checker_on) heap_profile->RecordFree(ptr);
  524. }
  525. RAW_VLOG(17, "Free Recorded: %p", ptr);
  526. }
  527. }
  528. //----------------------------------------------------------------------
  529. enum StackDirection {
  530. GROWS_TOWARDS_HIGH_ADDRESSES,
  531. GROWS_TOWARDS_LOW_ADDRESSES,
  532. UNKNOWN_DIRECTION
  533. };
  534. // Determine which way the stack grows:
  535. static StackDirection ATTRIBUTE_NOINLINE GetStackDirection(
  536. const uintptr_t *const ptr) {
  537. uintptr_t x;
  538. if (&x < ptr)
  539. return GROWS_TOWARDS_LOW_ADDRESSES;
  540. if (ptr < &x)
  541. return GROWS_TOWARDS_HIGH_ADDRESSES;
  542. RAW_CHECK(0, ""); // Couldn't determine the stack direction.
  543. return UNKNOWN_DIRECTION;
  544. }
  545. // Direction of stack growth (will initialize via GetStackDirection())
  546. static StackDirection stack_direction = UNKNOWN_DIRECTION;
  547. // This routine is called for every thread stack we know about to register it.
  548. static void RegisterStackLocked(const void* top_ptr) {
  549. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  550. RAW_DCHECK(MemoryRegionMap::LockIsHeld(), "");
  551. RAW_VLOG(10, "Thread stack at %p", top_ptr);
  552. uintptr_t top = AsInt(top_ptr);
  553. stack_tops->insert(top); // add for later use
  554. // make sure stack_direction is initialized
  555. if (stack_direction == UNKNOWN_DIRECTION) {
  556. stack_direction = GetStackDirection(&top);
  557. }
  558. // Find memory region with this stack
  559. MemoryRegionMap::Region region;
  560. if (MemoryRegionMap::FindAndMarkStackRegion(top, &region)) {
  561. // Make the proper portion of the stack live:
  562. if (stack_direction == GROWS_TOWARDS_LOW_ADDRESSES) {
  563. RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes",
  564. top_ptr, region.end_addr - top);
  565. live_objects->push_back(AllocObject(top_ptr, region.end_addr - top,
  566. THREAD_DATA));
  567. } else { // GROWS_TOWARDS_HIGH_ADDRESSES
  568. RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes",
  569. AsPtr(region.start_addr),
  570. top - region.start_addr);
  571. live_objects->push_back(AllocObject(AsPtr(region.start_addr),
  572. top - region.start_addr,
  573. THREAD_DATA));
  574. }
  575. // not in MemoryRegionMap, look in library_live_objects:
  576. } else if (FLAGS_heap_check_ignore_global_live) {
  577. for (LibraryLiveObjectsStacks::iterator lib = library_live_objects->begin();
  578. lib != library_live_objects->end(); ++lib) {
  579. for (LiveObjectsStack::iterator span = lib->second.begin();
  580. span != lib->second.end(); ++span) {
  581. uintptr_t start = AsInt(span->ptr);
  582. uintptr_t end = start + span->size;
  583. if (start <= top && top < end) {
  584. RAW_VLOG(11, "Stack at %p is inside /proc/self/maps chunk %p..%p",
  585. top_ptr, AsPtr(start), AsPtr(end));
  586. // Shrink start..end region by chopping away the memory regions in
  587. // MemoryRegionMap that land in it to undo merging of regions
  588. // in /proc/self/maps, so that we correctly identify what portion
  589. // of start..end is actually the stack region.
  590. uintptr_t stack_start = start;
  591. uintptr_t stack_end = end;
  592. // can optimize-away this loop, but it does not run often
  593. RAW_DCHECK(MemoryRegionMap::LockIsHeld(), "");
  594. for (MemoryRegionMap::RegionIterator r =
  595. MemoryRegionMap::BeginRegionLocked();
  596. r != MemoryRegionMap::EndRegionLocked(); ++r) {
  597. if (top < r->start_addr && r->start_addr < stack_end) {
  598. stack_end = r->start_addr;
  599. }
  600. if (stack_start < r->end_addr && r->end_addr <= top) {
  601. stack_start = r->end_addr;
  602. }
  603. }
  604. if (stack_start != start || stack_end != end) {
  605. RAW_VLOG(11, "Stack at %p is actually inside memory chunk %p..%p",
  606. top_ptr, AsPtr(stack_start), AsPtr(stack_end));
  607. }
  608. // Make the proper portion of the stack live:
  609. if (stack_direction == GROWS_TOWARDS_LOW_ADDRESSES) {
  610. RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes",
  611. top_ptr, stack_end - top);
  612. live_objects->push_back(
  613. AllocObject(top_ptr, stack_end - top, THREAD_DATA));
  614. } else { // GROWS_TOWARDS_HIGH_ADDRESSES
  615. RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes",
  616. AsPtr(stack_start), top - stack_start);
  617. live_objects->push_back(
  618. AllocObject(AsPtr(stack_start), top - stack_start, THREAD_DATA));
  619. }
  620. lib->second.erase(span); // kill the rest of the region
  621. // Put the non-stack part(s) of the region back:
  622. if (stack_start != start) {
  623. lib->second.push_back(AllocObject(AsPtr(start), stack_start - start,
  624. MAYBE_LIVE));
  625. }
  626. if (stack_end != end) {
  627. lib->second.push_back(AllocObject(AsPtr(stack_end), end - stack_end,
  628. MAYBE_LIVE));
  629. }
  630. return;
  631. }
  632. }
  633. }
  634. RAW_LOG(ERROR, "Memory region for stack at %p not found. "
  635. "Will likely report false leak positives.", top_ptr);
  636. }
  637. }
  638. // Iterator for heap allocation map data to make ignored objects "live"
  639. // (i.e., treated as roots for the mark-and-sweep phase)
  640. static void MakeIgnoredObjectsLiveCallbackLocked(
  641. const void* ptr, const HeapProfileTable::AllocInfo& info) {
  642. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  643. if (info.ignored) {
  644. live_objects->push_back(AllocObject(ptr, info.object_size,
  645. MUST_BE_ON_HEAP));
  646. }
  647. }
  648. // Iterator for heap allocation map data to make objects allocated from
  649. // disabled regions of code to be live.
  650. static void MakeDisabledLiveCallbackLocked(
  651. const void* ptr, const HeapProfileTable::AllocInfo& info) {
  652. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  653. bool stack_disable = false;
  654. bool range_disable = false;
  655. for (int depth = 0; depth < info.stack_depth; depth++) {
  656. uintptr_t addr = AsInt(info.call_stack[depth]);
  657. if (disabled_ranges) {
  658. DisabledRangeMap::const_iterator iter
  659. = disabled_ranges->upper_bound(addr);
  660. if (iter != disabled_ranges->end()) {
  661. RAW_DCHECK(iter->first > addr, "");
  662. if (iter->second.start_address < addr &&
  663. iter->second.max_depth > depth) {
  664. range_disable = true; // in range; dropping
  665. break;
  666. }
  667. }
  668. }
  669. }
  670. if (stack_disable || range_disable) {
  671. uintptr_t start_address = AsInt(ptr);
  672. uintptr_t end_address = start_address + info.object_size;
  673. StackTopSet::const_iterator iter
  674. = stack_tops->lower_bound(start_address);
  675. if (iter != stack_tops->end()) {
  676. RAW_DCHECK(*iter >= start_address, "");
  677. if (*iter < end_address) {
  678. // We do not disable (treat as live) whole allocated regions
  679. // if they are used to hold thread call stacks
  680. // (i.e. when we find a stack inside).
  681. // The reason is that we'll treat as live the currently used
  682. // stack portions anyway (see RegisterStackLocked),
  683. // and the rest of the region where the stack lives can well
  684. // contain outdated stack variables which are not live anymore,
  685. // hence should not be treated as such.
  686. RAW_VLOG(11, "Not %s-disabling %" PRIuS " bytes at %p"
  687. ": have stack inside: %p",
  688. (stack_disable ? "stack" : "range"),
  689. info.object_size, ptr, AsPtr(*iter));
  690. return;
  691. }
  692. }
  693. RAW_VLOG(11, "%s-disabling %" PRIuS " bytes at %p",
  694. (stack_disable ? "Stack" : "Range"), info.object_size, ptr);
  695. live_objects->push_back(AllocObject(ptr, info.object_size,
  696. MUST_BE_ON_HEAP));
  697. }
  698. }
  699. static const char kUnnamedProcSelfMapEntry[] = "UNNAMED";
  700. // This function takes some fields from a /proc/self/maps line:
  701. //
  702. // start_address start address of a memory region.
  703. // end_address end address of a memory region
  704. // permissions rwx + private/shared bit
  705. // filename filename of the mapped file
  706. //
  707. // If the region is not writeable, then it cannot have any heap
  708. // pointers in it, otherwise we record it as a candidate live region
  709. // to get filtered later.
  710. static void RecordGlobalDataLocked(uintptr_t start_address,
  711. uintptr_t end_address,
  712. const char* permissions,
  713. const char* filename) {
  714. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  715. // Ignore non-writeable regions.
  716. if (strchr(permissions, 'w') == NULL) return;
  717. if (filename == NULL || *filename == '\0') {
  718. filename = kUnnamedProcSelfMapEntry;
  719. }
  720. RAW_VLOG(11, "Looking into %s: 0x%" PRIxPTR "..0x%" PRIxPTR,
  721. filename, start_address, end_address);
  722. (*library_live_objects)[filename].
  723. push_back(AllocObject(AsPtr(start_address),
  724. end_address - start_address,
  725. MAYBE_LIVE));
  726. }
  727. // See if 'library' from /proc/self/maps has base name 'library_base'
  728. // i.e. contains it and has '.' or '-' after it.
  729. static bool IsLibraryNamed(const char* library, const char* library_base) {
  730. const char* p = hc_strstr(library, library_base);
  731. size_t sz = strlen(library_base);
  732. return p != NULL && (p[sz] == '.' || p[sz] == '-');
  733. }
  734. // static
  735. void HeapLeakChecker::DisableLibraryAllocsLocked(const char* library,
  736. uintptr_t start_address,
  737. uintptr_t end_address) {
  738. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  739. int depth = 0;
  740. // TODO(maxim): maybe this should be extended to also use objdump
  741. // and pick the text portion of the library more precisely.
  742. if (IsLibraryNamed(library, "/libpthread") ||
  743. // libpthread has a lot of small "system" leaks we don't care about.
  744. // In particular it allocates memory to store data supplied via
  745. // pthread_setspecific (which can be the only pointer to a heap object).
  746. IsLibraryNamed(library, "/libdl") ||
  747. // library loaders leak some "system" heap that we don't care about
  748. IsLibraryNamed(library, "/libcrypto") ||
  749. // Sometimes libcrypto of OpenSSH is compiled with -fomit-frame-pointer
  750. // (any library can be, of course, but this one often is because speed
  751. // is so important for making crypto usable). We ignore all its
  752. // allocations because we can't see the call stacks. We'd prefer
  753. // to ignore allocations done in files/symbols that match
  754. // "default_malloc_ex|default_realloc_ex"
  755. // but that doesn't work when the end-result binary is stripped.
  756. IsLibraryNamed(library, "/libjvm") ||
  757. // JVM has a lot of leaks we don't care about.
  758. IsLibraryNamed(library, "/libzip")
  759. // The JVM leaks java.util.zip.Inflater after loading classes.
  760. ) {
  761. depth = 1; // only disable allocation calls directly from the library code
  762. } else if (IsLibraryNamed(library, "/ld")
  763. // library loader leaks some "system" heap
  764. // (e.g. thread-local storage) that we don't care about
  765. ) {
  766. depth = 2; // disable allocation calls directly from the library code
  767. // and at depth 2 from it.
  768. // We need depth 2 here solely because of a libc bug that
  769. // forces us to jump through __memalign_hook and MemalignOverride hoops
  770. // in tcmalloc.cc.
  771. // Those buggy __libc_memalign() calls are in ld-linux.so and happen for
  772. // thread-local storage allocations that we want to ignore here.
  773. // We go with the depth-2 hack as a workaround for this libc bug:
  774. // otherwise we'd need to extend MallocHook interface
  775. // so that correct stack depth adjustment can be propagated from
  776. // the exceptional case of MemalignOverride.
  777. // Using depth 2 here should not mask real leaks because ld-linux.so
  778. // does not call user code.
  779. }
  780. if (depth) {
  781. RAW_VLOG(10, "Disabling allocations from %s at depth %d:", library, depth);
  782. DisableChecksFromToLocked(AsPtr(start_address), AsPtr(end_address), depth);
  783. if (IsLibraryNamed(library, "/libpthread") ||
  784. IsLibraryNamed(library, "/libdl") ||
  785. IsLibraryNamed(library, "/ld")) {
  786. RAW_VLOG(10, "Global memory regions made by %s will be live data",
  787. library);
  788. if (global_region_caller_ranges == NULL) {
  789. global_region_caller_ranges =
  790. new(Allocator::Allocate(sizeof(GlobalRegionCallerRangeMap)))
  791. GlobalRegionCallerRangeMap;
  792. }
  793. global_region_caller_ranges
  794. ->insert(make_pair(end_address, start_address));
  795. }
  796. }
  797. }
  798. // static
  799. HeapLeakChecker::ProcMapsResult HeapLeakChecker::UseProcMapsLocked(
  800. ProcMapsTask proc_maps_task) {
  801. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  802. // Need to provide own scratch memory to ProcMapsIterator:
  803. ProcMapsIterator::Buffer buffer;
  804. ProcMapsIterator it(0, &buffer);
  805. if (!it.Valid()) {
  806. int errsv = errno;
  807. RAW_LOG(ERROR, "Could not open /proc/self/maps: errno=%d. "
  808. "Libraries will not be handled correctly.", errsv);
  809. return CANT_OPEN_PROC_MAPS;
  810. }
  811. uint64 start_address, end_address, file_offset;
  812. int64 inode;
  813. char *permissions, *filename;
  814. bool saw_shared_lib = false;
  815. bool saw_nonzero_inode = false;
  816. bool saw_shared_lib_with_nonzero_inode = false;
  817. while (it.Next(&start_address, &end_address, &permissions,
  818. &file_offset, &inode, &filename)) {
  819. if (start_address >= end_address) {
  820. // Warn if a line we can be interested in is ill-formed:
  821. if (inode != 0) {
  822. RAW_LOG(ERROR, "Errors reading /proc/self/maps. "
  823. "Some global memory regions will not "
  824. "be handled correctly.");
  825. }
  826. // Silently skip other ill-formed lines: some are possible
  827. // probably due to the interplay of how /proc/self/maps is updated
  828. // while we read it in chunks in ProcMapsIterator and
  829. // do things in this loop.
  830. continue;
  831. }
  832. // Determine if any shared libraries are present (this is the same
  833. // list of extensions as is found in pprof). We want to ignore
  834. // 'fake' libraries with inode 0 when determining. However, some
  835. // systems don't share inodes via /proc, so we turn off this check
  836. // if we don't see any evidence that we're getting inode info.
  837. if (inode != 0) {
  838. saw_nonzero_inode = true;
  839. }
  840. if ((hc_strstr(filename, "lib") && hc_strstr(filename, ".so")) ||
  841. hc_strstr(filename, ".dll") ||
  842. // not all .dylib filenames start with lib. .dylib is big enough
  843. // that we are unlikely to get false matches just checking that.
  844. hc_strstr(filename, ".dylib") || hc_strstr(filename, ".bundle")) {
  845. saw_shared_lib = true;
  846. if (inode != 0) {
  847. saw_shared_lib_with_nonzero_inode = true;
  848. }
  849. }
  850. switch (proc_maps_task) {
  851. case DISABLE_LIBRARY_ALLOCS:
  852. // All lines starting like
  853. // "401dc000-4030f000 r??p 00132000 03:01 13991972 lib/bin"
  854. // identify a data and code sections of a shared library or our binary
  855. if (inode != 0 && strncmp(permissions, "r-xp", 4) == 0) {
  856. DisableLibraryAllocsLocked(filename, start_address, end_address);
  857. }
  858. break;
  859. case RECORD_GLOBAL_DATA:
  860. RecordGlobalDataLocked(start_address, end_address,
  861. permissions, filename);
  862. break;
  863. default:
  864. RAW_CHECK(0, "");
  865. }
  866. }
  867. // If /proc/self/maps is reporting inodes properly (we saw a
  868. // non-zero inode), then we only say we saw a shared lib if we saw a
  869. // 'real' one, with a non-zero inode.
  870. if (saw_nonzero_inode) {
  871. saw_shared_lib = saw_shared_lib_with_nonzero_inode;
  872. }
  873. if (!saw_shared_lib) {
  874. RAW_LOG(ERROR, "No shared libs detected. Will likely report false leak "
  875. "positives for statically linked executables.");
  876. return NO_SHARED_LIBS_IN_PROC_MAPS;
  877. }
  878. return PROC_MAPS_USED;
  879. }
  880. // Total number and size of live objects dropped from the profile;
  881. // (re)initialized in IgnoreAllLiveObjectsLocked.
  882. static int64 live_objects_total;
  883. static int64 live_bytes_total;
  884. // pid of the thread that is doing the current leak check
  885. // (protected by our lock; IgnoreAllLiveObjectsLocked sets it)
  886. static pid_t self_thread_pid = 0;
  887. // Status of our thread listing callback execution
  888. // (protected by our lock; used from within IgnoreAllLiveObjectsLocked)
  889. static enum {
  890. CALLBACK_NOT_STARTED,
  891. CALLBACK_STARTED,
  892. CALLBACK_COMPLETED,
  893. } thread_listing_status = CALLBACK_NOT_STARTED;
  894. // Ideally to avoid deadlocks this function should not result in any libc
  895. // or other function calls that might need to lock a mutex:
  896. // It is called when all threads of a process are stopped
  897. // at arbitrary points thus potentially holding those locks.
  898. //
  899. // In practice we are calling some simple i/o and sprintf-type library functions
  900. // for logging messages, but use only our own LowLevelAlloc::Arena allocator.
  901. //
  902. // This is known to be buggy: the library i/o function calls are able to cause
  903. // deadlocks when they request a lock that a stopped thread happens to hold.
  904. // This issue as far as we know have so far not resulted in any deadlocks
  905. // in practice, so for now we are taking our chance that the deadlocks
  906. // have insignificant frequency.
  907. //
  908. // If such deadlocks become a problem we should make the i/o calls
  909. // into appropriately direct system calls (or eliminate them),
  910. // in particular write() is not safe and vsnprintf() is potentially dangerous
  911. // due to reliance on locale functions (these are called through RAW_LOG
  912. // and in other ways).
  913. //
  914. #if defined(HAVE_LINUX_PTRACE_H) && defined(HAVE_SYS_SYSCALL_H) && defined(DUMPER)
  915. # if (defined(__i386__) || defined(__x86_64))
  916. # define THREAD_REGS i386_regs
  917. # elif defined(__PPC__)
  918. # define THREAD_REGS ppc_regs
  919. # endif
  920. #endif
  921. /*static*/ int HeapLeakChecker::IgnoreLiveThreadsLocked(void* parameter,
  922. int num_threads,
  923. pid_t* thread_pids,
  924. va_list /*ap*/) {
  925. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  926. thread_listing_status = CALLBACK_STARTED;
  927. RAW_VLOG(11, "Found %d threads (from pid %d)", num_threads, getpid());
  928. if (FLAGS_heap_check_ignore_global_live) {
  929. UseProcMapsLocked(RECORD_GLOBAL_DATA);
  930. }
  931. // We put the registers from other threads here
  932. // to make pointers stored in them live.
  933. vector<void*, STL_Allocator<void*, Allocator> > thread_registers;
  934. int failures = 0;
  935. for (int i = 0; i < num_threads; ++i) {
  936. // the leak checking thread itself is handled
  937. // specially via self_thread_stack, not here:
  938. if (thread_pids[i] == self_thread_pid) continue;
  939. RAW_VLOG(11, "Handling thread with pid %d", thread_pids[i]);
  940. #ifdef THREAD_REGS
  941. THREAD_REGS thread_regs;
  942. #define sys_ptrace(r, p, a, d) syscall(SYS_ptrace, (r), (p), (a), (d))
  943. // We use sys_ptrace to avoid thread locking
  944. // because this is called from TCMalloc_ListAllProcessThreads
  945. // when all but this thread are suspended.
  946. if (sys_ptrace(PTRACE_GETREGS, thread_pids[i], NULL, &thread_regs) == 0) {
  947. // Need to use SP to get all the data from the very last stack frame:
  948. COMPILE_ASSERT(sizeof(thread_regs.SP) == sizeof(void*),
  949. SP_register_does_not_look_like_a_pointer);
  950. RegisterStackLocked(reinterpret_cast<void*>(thread_regs.SP));
  951. // Make registers live (just in case PTRACE_ATTACH resulted in some
  952. // register pointers still being in the registers and not on the stack):
  953. for (void** p = reinterpret_cast<void**>(&thread_regs);
  954. p < reinterpret_cast<void**>(&thread_regs + 1); ++p) {
  955. RAW_VLOG(12, "Thread register %p", *p);
  956. thread_registers.push_back(*p);
  957. }
  958. } else {
  959. failures += 1;
  960. }
  961. #else
  962. failures += 1;
  963. #endif
  964. }
  965. // Use all the collected thread (stack) liveness sources:
  966. IgnoreLiveObjectsLocked("threads stack data", "");
  967. if (thread_registers.size()) {
  968. // Make thread registers be live heap data sources.
  969. // we rely here on the fact that vector is in one memory chunk:
  970. RAW_VLOG(11, "Live registers at %p of %" PRIuS " bytes",
  971. &thread_registers[0], thread_registers.size() * sizeof(void*));
  972. live_objects->push_back(AllocObject(&thread_registers[0],
  973. thread_registers.size() * sizeof(void*),
  974. THREAD_REGISTERS));
  975. IgnoreLiveObjectsLocked("threads register data", "");
  976. }
  977. // Do all other liveness walking while all threads are stopped:
  978. IgnoreNonThreadLiveObjectsLocked();
  979. // Can now resume the threads:
  980. TCMalloc_ResumeAllProcessThreads(num_threads, thread_pids);
  981. thread_listing_status = CALLBACK_COMPLETED;
  982. return failures;
  983. }
  984. // Stack top of the thread that is doing the current leak check
  985. // (protected by our lock; IgnoreAllLiveObjectsLocked sets it)
  986. static const void* self_thread_stack_top;
  987. // static
  988. void HeapLeakChecker::IgnoreNonThreadLiveObjectsLocked() {
  989. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  990. RAW_DCHECK(MemoryRegionMap::LockIsHeld(), "");
  991. RAW_VLOG(11, "Handling self thread with pid %d", self_thread_pid);
  992. // Register our own stack:
  993. // Important that all stack ranges (including the one here)
  994. // are known before we start looking at them
  995. // in MakeDisabledLiveCallbackLocked:
  996. RegisterStackLocked(self_thread_stack_top);
  997. IgnoreLiveObjectsLocked("stack data", "");
  998. // Make objects we were told to ignore live:
  999. if (ignored_objects) {
  1000. for (IgnoredObjectsMap::const_iterator object = ignored_objects->begin();
  1001. object != ignored_objects->end(); ++object) {
  1002. const void* ptr = AsPtr(object->first);
  1003. RAW_VLOG(11, "Ignored live object at %p of %" PRIuS " bytes",
  1004. ptr, object->second);
  1005. live_objects->
  1006. push_back(AllocObject(ptr, object->second, MUST_BE_ON_HEAP));
  1007. // we do this liveness check for ignored_objects before doing any
  1008. // live heap walking to make sure it does not fail needlessly:
  1009. size_t object_size;
  1010. if (!(heap_profile->FindAlloc(ptr, &object_size) &&
  1011. object->second == object_size)) {
  1012. RAW_LOG(FATAL, "Object at %p of %" PRIuS " bytes from an"
  1013. " IgnoreObject() has disappeared", ptr, object->second);
  1014. }
  1015. }
  1016. IgnoreLiveObjectsLocked("ignored objects", "");
  1017. }
  1018. // Treat objects that were allocated when a Disabler was live as
  1019. // roots. I.e., if X was allocated while a Disabler was active,
  1020. // and Y is reachable from X, arrange that neither X nor Y are
  1021. // treated as leaks.
  1022. heap_profile->IterateAllocs(MakeIgnoredObjectsLiveCallbackLocked);
  1023. IgnoreLiveObjectsLocked("disabled objects", "");
  1024. // Make code-address-disabled objects live and ignored:
  1025. // This in particular makes all thread-specific data live
  1026. // because the basic data structure to hold pointers to thread-specific data
  1027. // is allocated from libpthreads and we have range-disabled that
  1028. // library code with UseProcMapsLocked(DISABLE_LIBRARY_ALLOCS);
  1029. // so now we declare all thread-specific data reachable from there as live.
  1030. heap_profile->IterateAllocs(MakeDisabledLiveCallbackLocked);
  1031. IgnoreLiveObjectsLocked("disabled code", "");
  1032. // Actually make global data live:
  1033. if (FLAGS_heap_check_ignore_global_live) {
  1034. bool have_null_region_callers = false;
  1035. for (LibraryLiveObjectsStacks::iterator l = library_live_objects->begin();
  1036. l != library_live_objects->end(); ++l) {
  1037. RAW_CHECK(live_objects->empty(), "");
  1038. // Process library_live_objects in l->second
  1039. // filtering them by MemoryRegionMap:
  1040. // It's safe to iterate over MemoryRegionMap
  1041. // w/o locks here as we are inside MemoryRegionMap::Lock():
  1042. RAW_DCHECK(MemoryRegionMap::LockIsHeld(), "");
  1043. // The only change to MemoryRegionMap possible in this loop
  1044. // is region addition as a result of allocating more memory
  1045. // for live_objects. This won't invalidate the RegionIterator
  1046. // or the intent of the loop.
  1047. // --see the comment by MemoryRegionMap::BeginRegionLocked().
  1048. for (MemoryRegionMap::RegionIterator region =
  1049. MemoryRegionMap::BeginRegionLocked();
  1050. region != MemoryRegionMap::EndRegionLocked(); ++region) {
  1051. // "region" from MemoryRegionMap is to be subtracted from
  1052. // (tentatively live) regions in l->second
  1053. // if it has a stack inside or it was allocated by
  1054. // a non-special caller (not one covered by a range
  1055. // in global_region_caller_ranges).
  1056. // This will in particular exclude all memory chunks used
  1057. // by the heap itself as well as what's been allocated with
  1058. // any allocator on top of mmap.
  1059. bool subtract = true;
  1060. if (!region->is_stack && global_region_caller_ranges) {
  1061. if (region->caller() == static_cast<uintptr_t>(NULL)) {
  1062. have_null_region_callers = true;
  1063. } else {
  1064. GlobalRegionCallerRangeMap::const_iterator iter
  1065. = global_region_caller_ranges->upper_bound(region->caller());
  1066. if (iter != global_region_caller_ranges->end()) {
  1067. RAW_DCHECK(iter->first > region->caller(), "");
  1068. if (iter->second < region->caller()) { // in special region
  1069. subtract = false;
  1070. }
  1071. }
  1072. }
  1073. }
  1074. if (subtract) {
  1075. // The loop puts the result of filtering l->second into live_objects:
  1076. for (LiveObjectsStack::const_iterator i = l->second.begin();
  1077. i != l->second.end(); ++i) {
  1078. // subtract *region from *i
  1079. uintptr_t start = AsInt(i->ptr);
  1080. uintptr_t end = start + i->size;
  1081. if (region->start_addr <= start && end <= region->end_addr) {
  1082. // full deletion due to subsumption
  1083. } else if (start < region->start_addr &&
  1084. region->end_addr < end) { // cutting-out split
  1085. live_objects->push_back(AllocObject(i->ptr,
  1086. region->start_addr - start,
  1087. IN_GLOBAL_DATA));
  1088. live_objects->push_back(AllocObject(AsPtr(region->end_addr),
  1089. end - region->end_addr,
  1090. IN_GLOBAL_DATA));
  1091. } else if (region->end_addr > start &&
  1092. region->start_addr <= start) { // cut from start
  1093. live_objects->push_back(AllocObject(AsPtr(region->end_addr),
  1094. end - region->end_addr,
  1095. IN_GLOBAL_DATA));
  1096. } else if (region->start_addr > start &&
  1097. region->start_addr < end) { // cut from end
  1098. live_objects->push_back(AllocObject(i->ptr,
  1099. region->start_addr - start,
  1100. IN_GLOBAL_DATA));
  1101. } else { // pass: no intersection
  1102. live_objects->push_back(AllocObject(i->ptr, i->size,
  1103. IN_GLOBAL_DATA));
  1104. }
  1105. }
  1106. // Move live_objects back into l->second
  1107. // for filtering by the next region.
  1108. live_objects->swap(l->second);
  1109. live_objects->clear();
  1110. }
  1111. }
  1112. // Now get and use live_objects from the final version of l->second:
  1113. if (VLOG_IS_ON(11)) {
  1114. for (LiveObjectsStack::const_iterator i = l->second.begin();
  1115. i != l->second.end(); ++i) {
  1116. RAW_VLOG(11, "Library live region at %p of %" PRIuPTR " bytes",
  1117. i->ptr, i->size);
  1118. }
  1119. }
  1120. live_objects->swap(l->second);
  1121. IgnoreLiveObjectsLocked("in globals of\n ", l->first.c_str());
  1122. }
  1123. if (have_null_region_callers) {
  1124. RAW_LOG(ERROR, "Have memory regions w/o callers: "
  1125. "might report false leaks");
  1126. }
  1127. Allocator::DeleteAndNull(&library_live_objects);
  1128. }
  1129. }
  1130. // Callback for TCMalloc_ListAllProcessThreads in IgnoreAllLiveObjectsLocked below
  1131. // to test/verify that we have just the one main thread, in which case
  1132. // we can do everything in that main thread,
  1133. // so that CPU profiler can collect all its samples.
  1134. // Returns the number of threads in the process.
  1135. static int IsOneThread(void* parameter, int num_threads,
  1136. pid_t* thread_pids, va_list ap) {
  1137. if (num_threads != 1) {
  1138. RAW_LOG(WARNING, "Have threads: Won't CPU-profile the bulk of leak "
  1139. "checking work happening in IgnoreLiveThreadsLocked!");
  1140. }
  1141. TCMalloc_ResumeAllProcessThreads(num_threads, thread_pids);
  1142. return num_threads;
  1143. }
  1144. // Dummy for IgnoreAllLiveObjectsLocked below.
  1145. // Making it global helps with compiler warnings.
  1146. static va_list dummy_ap;
  1147. // static
  1148. void HeapLeakChecker::IgnoreAllLiveObjectsLocked(const void* self_stack_top) {
  1149. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  1150. RAW_CHECK(live_objects == NULL, "");
  1151. live_objects = new(Allocator::Allocate(sizeof(LiveObjectsStack)))
  1152. LiveObjectsStack;
  1153. stack_tops = new(Allocator::Allocate(sizeof(StackTopSet))) StackTopSet;
  1154. // reset the counts
  1155. live_objects_total = 0;
  1156. live_bytes_total = 0;
  1157. // Reduce max_heap_object_size to FLAGS_heap_check_max_pointer_offset
  1158. // for the time of leak check.
  1159. // FLAGS_heap_check_max_pointer_offset caps max_heap_object_size
  1160. // to manage reasonably low chances of random bytes
  1161. // appearing to be pointing into large actually leaked heap objects.
  1162. const size_t old_max_heap_object_size = max_heap_object_size;
  1163. max_heap_object_size = (
  1164. FLAGS_heap_check_max_pointer_offset != -1
  1165. ? min(size_t(FLAGS_heap_check_max_pointer_offset), max_heap_object_size)
  1166. : max_heap_object_size);
  1167. // Record global data as live:
  1168. if (FLAGS_heap_check_ignore_global_live) {
  1169. library_live_objects =
  1170. new(Allocator::Allocate(sizeof(LibraryLiveObjectsStacks)))
  1171. LibraryLiveObjectsStacks;
  1172. }
  1173. // Ignore all thread stacks:
  1174. thread_listing_status = CALLBACK_NOT_STARTED;
  1175. bool need_to_ignore_non_thread_objects = true;
  1176. self_thread_pid = getpid();
  1177. self_thread_stack_top = self_stack_top;
  1178. if (FLAGS_heap_check_ignore_thread_live) {
  1179. // In case we are doing CPU profiling we'd like to do all the work
  1180. // in the main thread, not in the special thread created by
  1181. // TCMalloc_ListAllProcessThreads, so that CPU profiler can
  1182. // collect all its samples. The machinery of
  1183. // TCMalloc_ListAllProcessThreads conflicts with the CPU profiler
  1184. // by also relying on signals and ::sigaction. We can do this
  1185. // (run everything in the main thread) safely only if there's just
  1186. // the main thread itself in our process. This variable reflects
  1187. // these two conditions:
  1188. bool want_and_can_run_in_main_thread =
  1189. ProfilingIsEnabledForAllThreads() &&
  1190. TCMalloc_ListAllProcessThreads(NULL, IsOneThread) == 1;
  1191. // When the normal path of TCMalloc_ListAllProcessThreads below is taken,
  1192. // we fully suspend the threads right here before any liveness checking
  1193. // and keep them suspended for the whole time of liveness checking
  1194. // inside of the IgnoreLiveThreadsLocked callback.
  1195. // (The threads can't (de)allocate due to lock on the delete hook but
  1196. // if not suspended they could still mess with the pointer
  1197. // graph while we walk it).
  1198. int r = want_and_can_run_in_main_thread
  1199. ? IgnoreLiveThreadsLocked(NULL, 1, &self_thread_pid, dummy_ap)
  1200. : TCMalloc_ListAllProcessThreads(NULL, IgnoreLiveThreadsLocked);
  1201. need_to_ignore_non_thread_objects = r < 0;
  1202. if (r < 0) {
  1203. RAW_LOG(WARNING, "Thread finding failed with %d errno=%d", r, errno);
  1204. if (thread_listing_status == CALLBACK_COMPLETED) {
  1205. RAW_LOG(INFO, "Thread finding callback "
  1206. "finished ok; hopefully everything is fine");
  1207. need_to_ignore_non_thread_objects = false;
  1208. } else if (thread_listing_status == CALLBACK_STARTED) {
  1209. RAW_LOG(FATAL, "Thread finding callback was "
  1210. "interrupted or crashed; can't fix this");
  1211. } else { // CALLBACK_NOT_STARTED
  1212. RAW_LOG(ERROR, "Could not find thread stacks. "
  1213. "Will likely report false leak positives.");
  1214. }
  1215. } else if (r != 0) {
  1216. RAW_LOG(ERROR, "Thread stacks not found for %d threads. "
  1217. "Will likely report false leak positives.", r);
  1218. } else {
  1219. RAW_VLOG(11, "Thread stacks appear to be found for all threads");
  1220. }
  1221. } else {
  1222. RAW_LOG(WARNING, "Not looking for thread stacks; "
  1223. "objects reachable only from there "
  1224. "will be reported as leaks");
  1225. }
  1226. // Do all other live data ignoring here if we did not do it
  1227. // within thread listing callback with all threads stopped.
  1228. if (need_to_ignore_non_thread_objects) {
  1229. if (FLAGS_heap_check_ignore_global_live) {
  1230. UseProcMapsLocked(RECORD_GLOBAL_DATA);
  1231. }
  1232. IgnoreNonThreadLiveObjectsLocked();
  1233. }
  1234. if (live_objects_total) {
  1235. RAW_VLOG(10, "Ignoring %" PRId64 " reachable objects of %" PRId64 " bytes",
  1236. live_objects_total, live_bytes_total);
  1237. }
  1238. // Free these: we made them here and heap_profile never saw them
  1239. Allocator::DeleteAndNull(&live_objects);
  1240. Allocator::DeleteAndNull(&stack_tops);
  1241. max_heap_object_size = old_max_heap_object_size; // reset this var
  1242. }
  1243. // Alignment at which we should consider pointer positions
  1244. // in IgnoreLiveObjectsLocked. Will normally use the value of
  1245. // FLAGS_heap_check_pointer_source_alignment.
  1246. static size_t pointer_source_alignment = kPointerSourceAlignment;
  1247. // Global lock for HeapLeakChecker::DoNoLeaks
  1248. // to protect pointer_source_alignment.
  1249. static SpinLock alignment_checker_lock(SpinLock::LINKER_INITIALIZED);
  1250. // This function changes the live bits in the heap_profile-table's state:
  1251. // we only record the live objects to be skipped.
  1252. //
  1253. // When checking if a byte sequence points to a heap object we use
  1254. // HeapProfileTable::FindInsideAlloc to handle both pointers to
  1255. // the start and inside of heap-allocated objects.
  1256. // The "inside" case needs to be checked to support
  1257. // at least the following relatively common cases:
  1258. // - C++ arrays allocated with new FooClass[size] for classes
  1259. // with destructors have their size recorded in a sizeof(int) field
  1260. // before the place normal pointers point to.
  1261. // - basic_string<>-s for e.g. the C++ library of gcc 3.4
  1262. // have the meta-info in basic_string<...>::_Rep recorded
  1263. // before the place normal pointers point to.
  1264. // - Multiple-inherited objects have their pointers when cast to
  1265. // different base classes pointing inside of the actually
  1266. // allocated object.
  1267. // - Sometimes reachability pointers point to member objects of heap objects,
  1268. // and then those member objects point to the full heap object.
  1269. // - Third party UnicodeString: it stores a 32-bit refcount
  1270. // (in both 32-bit and 64-bit binaries) as the first uint32
  1271. // in the allocated memory and a normal pointer points at
  1272. // the second uint32 behind the refcount.
  1273. // By finding these additional objects here
  1274. // we slightly increase the chance to mistake random memory bytes
  1275. // for a pointer and miss a leak in a particular run of a binary.
  1276. //
  1277. /*static*/ void HeapLeakChecker::IgnoreLiveObjectsLocked(const char* name,
  1278. const char* name2) {
  1279. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  1280. int64 live_object_count = 0;
  1281. int64 live_byte_count = 0;
  1282. while (!live_objects->empty()) {
  1283. const char* object =
  1284. reinterpret_cast<const char*>(live_objects->back().ptr);
  1285. size_t size = live_objects->back().size;
  1286. const ObjectPlacement place = live_objects->back().place;
  1287. live_objects->pop_back();
  1288. if (place == MUST_BE_ON_HEAP && heap_profile->MarkAsLive(object)) {
  1289. live_object_count += 1;
  1290. live_byte_count += size;
  1291. }
  1292. RAW_VLOG(13, "Looking for heap pointers in %p of %" PRIuS " bytes",
  1293. object, size);
  1294. const char* const whole_object = object;
  1295. size_t const whole_size = size;
  1296. // Try interpretting any byte sequence in object,size as a heap pointer:
  1297. const size_t remainder = AsInt(object) % pointer_source_alignment;
  1298. if (remainder) {
  1299. object += pointer_source_alignment - remainder;
  1300. if (size >= pointer_source_alignment - remainder) {
  1301. size -= pointer_source_alignment - remainder;
  1302. } else {
  1303. size = 0;
  1304. }
  1305. }
  1306. if (size < sizeof(void*)) continue;
  1307. #ifdef NO_FRAME_POINTER
  1308. // Frame pointer omission requires us to use libunwind, which uses direct
  1309. // mmap and munmap system calls, and that needs special handling.
  1310. if (name2 == kUnnamedProcSelfMapEntry) {
  1311. static const uintptr_t page_mask = ~(getpagesize() - 1);
  1312. const uintptr_t addr = reinterpret_cast<uintptr_t>(object);
  1313. if ((addr & page_mask) == 0 && (size & page_mask) == 0) {
  1314. // This is an object we slurped from /proc/self/maps.
  1315. // It may or may not be readable at this point.
  1316. //
  1317. // In case all the above conditions made a mistake, and the object is
  1318. // not related to libunwind, we also verify that it's not readable
  1319. // before ignoring it.
  1320. if (msync(const_cast<char*>(object), size, MS_ASYNC) != 0) {
  1321. // Skip unreadable object, so we don't crash trying to sweep it.
  1322. RAW_VLOG(0, "Ignoring inaccessible object [%p, %p) "
  1323. "(msync error %d (%s))",
  1324. object, object + size, errno, strerror(errno));
  1325. continue;
  1326. }
  1327. }
  1328. }
  1329. #endif
  1330. const char* const max_object = object + size - sizeof(void*);
  1331. while (object <= max_object) {
  1332. // potentially unaligned load:
  1333. const uintptr_t addr = *reinterpret_cast<const uintptr_t*>(object);
  1334. // Do fast check before the more expensive HaveOnHeapLocked lookup:
  1335. // this code runs for all memory words that are potentially pointers:
  1336. const bool can_be_on_heap =
  1337. // Order tests by the likelyhood of the test failing in 64/32 bit modes.
  1338. // Yes, this matters: we either lose 5..6% speed in 32 bit mode
  1339. // (which is already slower) or by a factor of 1.5..1.91 in 64 bit mode.
  1340. // After the alignment test got dropped the above performance figures
  1341. // must have changed; might need to revisit this.
  1342. #if defined(__x86_64__)
  1343. addr <= max_heap_address && // <= is for 0-sized object with max addr
  1344. min_heap_address <= addr;
  1345. #else
  1346. min_heap_address <= addr &&
  1347. addr <= max_heap_address; // <= is for 0-sized object with max addr
  1348. #endif
  1349. if (can_be_on_heap) {
  1350. const void* ptr = reinterpret_cast<const void*>(addr);
  1351. // Too expensive (inner loop): manually uncomment when debugging:
  1352. // RAW_VLOG(17, "Trying pointer to %p at %p", ptr, object);
  1353. size_t object_size;
  1354. if (HaveOnHeapLocked(&ptr, &object_size) &&
  1355. heap_profile->MarkAsLive(ptr)) {
  1356. // We take the (hopefully low) risk here of encountering by accident
  1357. // a byte sequence in memory that matches an address of
  1358. // a heap object which is in fact leaked.
  1359. // I.e. in very rare and probably not repeatable/lasting cases
  1360. // we might miss some real heap memory leaks.
  1361. RAW_VLOG(14, "Found pointer to %p of %" PRIuS " bytes at %p "
  1362. "inside %p of size %" PRIuS "",
  1363. ptr, object_size, object, whole_object, whole_size);
  1364. if (VLOG_IS_ON(15)) {
  1365. // log call stacks to help debug how come something is not a leak
  1366. HeapProfileTable::AllocInfo alloc;
  1367. if (!heap_profile->FindAllocDetails(ptr, &alloc)) {
  1368. RAW_LOG(FATAL, "FindAllocDetails failed on ptr %p", ptr);
  1369. }
  1370. RAW_LOG(INFO, "New live %p object's alloc stack:", ptr);
  1371. for (int i = 0; i < alloc.stack_depth; ++i) {
  1372. RAW_LOG(INFO, " @ %p", alloc.call_stack[i]);
  1373. }
  1374. }
  1375. live_object_count += 1;
  1376. live_byte_count += object_size;
  1377. live_objects->push_back(AllocObject(ptr, object_size,
  1378. IGNORED_ON_HEAP));
  1379. }
  1380. }
  1381. object += pointer_source_alignment;
  1382. }
  1383. }
  1384. live_objects_total += live_object_count;
  1385. live_bytes_total += live_byte_count;
  1386. if (live_object_count) {
  1387. RAW_VLOG(10, "Removed %" PRId64 " live heap objects of %" PRId64 " bytes: %s%s",
  1388. live_object_count, live_byte_count, name, name2);
  1389. }
  1390. }
  1391. //----------------------------------------------------------------------
  1392. // HeapLeakChecker leak check disabling components
  1393. //----------------------------------------------------------------------
  1394. // static
  1395. void HeapLeakChecker::DisableChecksIn(const char* pattern) {
  1396. RAW_LOG(WARNING, "DisableChecksIn(%s) is ignored", pattern);
  1397. }
  1398. // static
  1399. void HeapLeakChecker::DoIgnoreObject(const void* ptr) {
  1400. SpinLockHolder l(&heap_checker_lock);
  1401. if (!heap_checker_on) return;
  1402. size_t object_size;
  1403. if (!HaveOnHeapLocked(&ptr, &object_size)) {
  1404. RAW_LOG(ERROR, "No live heap object at %p to ignore", ptr);
  1405. } else {
  1406. RAW_VLOG(10, "Going to ignore live object at %p of %" PRIuS " bytes",
  1407. ptr, object_size);
  1408. if (ignored_objects == NULL) {
  1409. ignored_objects = new(Allocator::Allocate(sizeof(IgnoredObjectsMap)))
  1410. IgnoredObjectsMap;
  1411. }
  1412. if (!ignored_objects->insert(make_pair(AsInt(ptr), object_size)).second) {
  1413. RAW_LOG(WARNING, "Object at %p is already being ignored", ptr);
  1414. }
  1415. }
  1416. }
  1417. // static
  1418. void HeapLeakChecker::UnIgnoreObject(const void* ptr) {
  1419. SpinLockHolder l(&heap_checker_lock);
  1420. if (!heap_checker_on) return;
  1421. size_t object_size;
  1422. if (!HaveOnHeapLocked(&ptr, &object_size)) {
  1423. RAW_LOG(FATAL, "No live heap object at %p to un-ignore", ptr);
  1424. } else {
  1425. bool found = false;
  1426. if (ignored_objects) {
  1427. IgnoredObjectsMap::iterator object = ignored_objects->find(AsInt(ptr));
  1428. if (object != ignored_objects->end() && object_size == object->second) {
  1429. ignored_objects->erase(object);
  1430. found = true;
  1431. RAW_VLOG(10, "Now not going to ignore live object "
  1432. "at %p of %" PRIuS " bytes", ptr, object_size);
  1433. }
  1434. }
  1435. if (!found) RAW_LOG(FATAL, "Object at %p has not been ignored", ptr);
  1436. }
  1437. }
  1438. //----------------------------------------------------------------------
  1439. // HeapLeakChecker non-static functions
  1440. //----------------------------------------------------------------------
  1441. char* HeapLeakChecker::MakeProfileNameLocked() {
  1442. RAW_DCHECK(lock_->IsHeld(), "");
  1443. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  1444. const int len = profile_name_prefix->size() + strlen(name_) + 5 +
  1445. strlen(HeapProfileTable::kFileExt) + 1;
  1446. char* file_name = reinterpret_cast<char*>(Allocator::Allocate(len));
  1447. snprintf(file_name, len, "%s.%s-end%s",
  1448. profile_name_prefix->c_str(), name_,
  1449. HeapProfileTable::kFileExt);
  1450. return file_name;
  1451. }
  1452. void HeapLeakChecker::Create(const char *name, bool make_start_snapshot) {
  1453. SpinLockHolder l(lock_);
  1454. name_ = NULL; // checker is inactive
  1455. start_snapshot_ = NULL;
  1456. has_checked_ = false;
  1457. inuse_bytes_increase_ = 0;
  1458. inuse_allocs_increase_ = 0;
  1459. keep_profiles_ = false;
  1460. char* n = new char[strlen(name) + 1]; // do this before we lock
  1461. IgnoreObject(n); // otherwise it might be treated as live due to our stack
  1462. { // Heap activity in other threads is paused for this whole scope.
  1463. SpinLockHolder al(&alignment_checker_lock);
  1464. SpinLockHolder hl(&heap_checker_lock);
  1465. MemoryRegionMap::LockHolder ml;
  1466. if (heap_checker_on && profile_name_prefix != NULL) {
  1467. RAW_DCHECK(strchr(name, '/') == NULL, "must be a simple name");
  1468. memcpy(n, name, strlen(name) + 1);
  1469. name_ = n; // checker is active
  1470. if (make_start_snapshot) {
  1471. start_snapshot_ = heap_profile->TakeSnapshot();
  1472. }
  1473. const HeapProfileTable::Stats& t = heap_profile->total();
  1474. const size_t start_inuse_bytes = t.alloc_size - t.free_size;
  1475. const size_t start_inuse_allocs = t.allocs - t.frees;
  1476. RAW_VLOG(10, "Start check \"%s\" profile: %" PRIuS " bytes "
  1477. "in %" PRIuS " objects",
  1478. name_, start_inuse_bytes, start_inuse_allocs);
  1479. } else {
  1480. RAW_LOG(WARNING, "Heap checker is not active, "
  1481. "hence checker \"%s\" will do nothing!", name);
  1482. RAW_LOG(WARNING, "To activate set the HEAPCHECK environment variable.\n");
  1483. }
  1484. }
  1485. if (name_ == NULL) {
  1486. UnIgnoreObject(n);
  1487. delete[] n; // must be done after we unlock
  1488. }
  1489. }
  1490. HeapLeakChecker::HeapLeakChecker(const char *name) : lock_(new SpinLock) {
  1491. RAW_DCHECK(strcmp(name, "_main_") != 0, "_main_ is reserved");
  1492. Create(name, true/*create start_snapshot_*/);
  1493. }
  1494. HeapLeakChecker::HeapLeakChecker() : lock_(new SpinLock) {
  1495. if (FLAGS_heap_check_before_constructors) {
  1496. // We want to check for leaks of objects allocated during global
  1497. // constructors (i.e., objects allocated already). So we do not
  1498. // create a baseline snapshot and hence check for leaks of objects
  1499. // that may have already been created.
  1500. Create("_main_", false);
  1501. } else {
  1502. // We want to ignore leaks of objects allocated during global
  1503. // constructors (i.e., objects allocated already). So we snapshot
  1504. // the current heap contents and use them as a baseline that is
  1505. // not reported by the leak checker.
  1506. Create("_main_", true);
  1507. }
  1508. }
  1509. ssize_t HeapLeakChecker::BytesLeaked() const {
  1510. SpinLockHolder l(lock_);
  1511. if (!has_checked_) {
  1512. RAW_LOG(FATAL, "*NoLeaks|SameHeap must execute before this call");
  1513. }
  1514. return inuse_bytes_increase_;
  1515. }
  1516. ssize_t HeapLeakChecker::ObjectsLeaked() const {
  1517. SpinLockHolder l(lock_);
  1518. if (!has_checked_) {
  1519. RAW_LOG(FATAL, "*NoLeaks|SameHeap must execute before this call");
  1520. }
  1521. return inuse_allocs_increase_;
  1522. }
  1523. // Save pid of main thread for using in naming dump files
  1524. static int32 main_thread_pid = getpid();
  1525. #ifdef HAVE_PROGRAM_INVOCATION_NAME
  1526. #ifdef __UCLIBC__
  1527. extern const char* program_invocation_name;
  1528. extern const char* program_invocation_short_name;
  1529. #else
  1530. extern char* program_invocation_name;
  1531. extern char* program_invocation_short_name;
  1532. #endif
  1533. static const char* invocation_name() { return program_invocation_short_name; }
  1534. static string invocation_path() { return program_invocation_name; }
  1535. #else
  1536. static const char* invocation_name() { return "<your binary>"; }
  1537. static string invocation_path() { return "<your binary>"; }
  1538. #endif
  1539. // Prints commands that users can run to get more information
  1540. // about the reported leaks.
  1541. static void SuggestPprofCommand(const char* pprof_file_arg) {
  1542. // Extra help information to print for the user when the test is
  1543. // being run in a way where the straightforward pprof command will
  1544. // not suffice.
  1545. string extra_help;
  1546. // Common header info to print for remote runs
  1547. const string remote_header =
  1548. "This program is being executed remotely and therefore the pprof\n"
  1549. "command printed above will not work. Either run this program\n"
  1550. "locally, or adjust the pprof command as follows to allow it to\n"
  1551. "work on your local machine:\n";
  1552. // Extra command for fetching remote data
  1553. string fetch_cmd;
  1554. RAW_LOG(WARNING,
  1555. "\n\n"
  1556. "If the preceding stack traces are not enough to find "
  1557. "the leaks, try running THIS shell command:\n\n"
  1558. "%s%s %s \"%s\" --inuse_objects --lines --heapcheck "
  1559. " --edgefraction=1e-10 --nodefraction=1e-10 --gv\n"
  1560. "\n"
  1561. "%s"
  1562. "If you are still puzzled about why the leaks are "
  1563. "there, try rerunning this program with "
  1564. "HEAP_CHECK_TEST_POINTER_ALIGNMENT=1 and/or with "
  1565. "HEAP_CHECK_MAX_POINTER_OFFSET=-1\n"
  1566. "If the leak report occurs in a small fraction of runs, "
  1567. "try running with TCMALLOC_MAX_FREE_QUEUE_SIZE of few hundred MB "
  1568. "or with TCMALLOC_RECLAIM_MEMORY=false, " // only works for debugalloc
  1569. "it might help find leaks more repeatably\n",
  1570. fetch_cmd.c_str(),
  1571. "pprof", // works as long as pprof is on your path
  1572. invocation_path().c_str(),
  1573. pprof_file_arg,
  1574. extra_help.c_str()
  1575. );
  1576. }
  1577. bool HeapLeakChecker::DoNoLeaks(ShouldSymbolize should_symbolize) {
  1578. SpinLockHolder l(lock_);
  1579. // The locking also helps us keep the messages
  1580. // for the two checks close together.
  1581. SpinLockHolder al(&alignment_checker_lock);
  1582. // thread-safe: protected by alignment_checker_lock
  1583. static bool have_disabled_hooks_for_symbolize = false;
  1584. // Once we've checked for leaks and symbolized the results once, it's
  1585. // not safe to do it again. This is because in order to symbolize
  1586. // safely, we had to disable all the malloc hooks here, so we no
  1587. // longer can be confident we've collected all the data we need.
  1588. if (have_disabled_hooks_for_symbolize) {
  1589. RAW_LOG(FATAL, "Must not call heap leak checker manually after "
  1590. " program-exit's automatic check.");
  1591. }
  1592. HeapProfileTable::Snapshot* leaks = NULL;
  1593. char* pprof_file = NULL;
  1594. {
  1595. // Heap activity in other threads is paused during this function
  1596. // (i.e. until we got all profile difference info).
  1597. SpinLockHolder hl(&heap_checker_lock);
  1598. if (heap_checker_on == false) {
  1599. if (name_ != NULL) { // leak checking enabled when created the checker
  1600. RAW_LOG(WARNING, "Heap leak checker got turned off after checker "
  1601. "\"%s\" has been created, no leak check is being done for it!",
  1602. name_);
  1603. }
  1604. return true;
  1605. }
  1606. // Update global_region_caller_ranges. They may need to change since
  1607. // e.g. initialization because shared libraries might have been loaded or
  1608. // unloaded.
  1609. Allocator::DeleteAndNullIfNot(&global_region_caller_ranges);
  1610. ProcMapsResult pm_result = UseProcMapsLocked(DISABLE_LIBRARY_ALLOCS);
  1611. RAW_CHECK(pm_result == PROC_MAPS_USED, "");
  1612. // Keep track of number of internally allocated objects so we
  1613. // can detect leaks in the heap-leak-checket itself
  1614. const int initial_allocs = Allocator::alloc_count();
  1615. if (name_ == NULL) {
  1616. RAW_LOG(FATAL, "Heap leak checker must not be turned on "
  1617. "after construction of a HeapLeakChecker");
  1618. }
  1619. MemoryRegionMap::LockHolder ml;
  1620. int a_local_var; // Use our stack ptr to make stack data live:
  1621. // Make the heap profile, other threads are locked out.
  1622. HeapProfileTable::Snapshot* base =
  1623. reinterpret_cast<HeapProfileTable::Snapshot*>(start_snapshot_);
  1624. RAW_DCHECK(FLAGS_heap_check_pointer_source_alignment > 0, "");
  1625. pointer_source_alignment = FLAGS_heap_check_pointer_source_alignment;
  1626. IgnoreAllLiveObjectsLocked(&a_local_var);
  1627. leaks = heap_profile->NonLiveSnapshot(base);
  1628. inuse_bytes_increase_ = static_cast<ssize_t>(leaks->total().alloc_size);
  1629. inuse_allocs_increase_ = static_cast<ssize_t>(leaks->total().allocs);
  1630. if (leaks->Empty()) {
  1631. heap_profile->ReleaseSnapshot(leaks);
  1632. leaks = NULL;
  1633. // We can only check for internal leaks along the no-user-leak
  1634. // path since in the leak path we temporarily release
  1635. // heap_checker_lock and another thread can come in and disturb
  1636. // allocation counts.
  1637. if (Allocator::alloc_count() != initial_allocs) {
  1638. RAW_LOG(FATAL, "Internal HeapChecker leak of %d objects ; %d -> %d",
  1639. Allocator::alloc_count() - initial_allocs,
  1640. initial_allocs, Allocator::alloc_count());
  1641. }
  1642. } else if (FLAGS_heap_check_test_pointer_alignment) {
  1643. if (pointer_source_alignment == 1) {
  1644. RAW_LOG(WARNING, "--heap_check_test_pointer_alignment has no effect: "
  1645. "--heap_check_pointer_source_alignment was already set to 1");
  1646. } else {
  1647. // Try with reduced pointer aligment
  1648. pointer_source_alignment = 1;
  1649. IgnoreAllLiveObjectsLocked(&a_local_var);
  1650. HeapProfileTable::Snapshot* leaks_wo_align =
  1651. heap_profile->NonLiveSnapshot(base);
  1652. pointer_source_alignment = FLAGS_heap_check_pointer_source_alignment;
  1653. if (leaks_wo_align->Empty()) {
  1654. RAW_LOG(WARNING, "Found no leaks without pointer alignment: "
  1655. "something might be placing pointers at "
  1656. "unaligned addresses! This needs to be fixed.");
  1657. } else {
  1658. RAW_LOG(INFO, "Found leaks without pointer alignment as well: "
  1659. "unaligned pointers must not be the cause of leaks.");
  1660. RAW_LOG(INFO, "--heap_check_test_pointer_alignment did not help "
  1661. "to diagnose the leaks.");
  1662. }
  1663. heap_profile->ReleaseSnapshot(leaks_wo_align);
  1664. }
  1665. }
  1666. if (leaks != NULL) {
  1667. pprof_file = MakeProfileNameLocked();
  1668. }
  1669. }
  1670. has_checked_ = true;
  1671. if (leaks == NULL) {
  1672. if (FLAGS_heap_check_max_pointer_offset == -1) {
  1673. RAW_LOG(WARNING,
  1674. "Found no leaks without max_pointer_offset restriction: "
  1675. "it's possible that the default value of "
  1676. "heap_check_max_pointer_offset flag is too low. "
  1677. "Do you use pointers with larger than that offsets "
  1678. "pointing in the middle of heap-allocated objects?");
  1679. }
  1680. const HeapProfileTable::Stats& stats = heap_profile->total();
  1681. RAW_VLOG(heap_checker_info_level,
  1682. "No leaks found for check \"%s\" "
  1683. "(but no 100%% guarantee that there aren't any): "
  1684. "found %" PRId64 " reachable heap objects of %" PRId64 " bytes",
  1685. name_,
  1686. int64(stats.allocs - stats.frees),
  1687. int64(stats.alloc_size - stats.free_size));
  1688. } else {
  1689. if (should_symbolize == SYMBOLIZE) {
  1690. // To turn addresses into symbols, we need to fork, which is a
  1691. // problem if both parent and child end up trying to call the
  1692. // same malloc-hooks we've set up, at the same time. To avoid
  1693. // trouble, we turn off the hooks before symbolizing. Note that
  1694. // this makes it unsafe to ever leak-report again! Luckily, we
  1695. // typically only want to report once in a program's run, at the
  1696. // very end.
  1697. if (MallocHook::GetNewHook() == NewHook)
  1698. MallocHook::SetNewHook(NULL);
  1699. if (MallocHook::GetDeleteHook() == DeleteHook)
  1700. MallocHook::SetDeleteHook(NULL);
  1701. MemoryRegionMap::Shutdown();
  1702. // Make sure all the hooks really got unset:
  1703. RAW_CHECK(MallocHook::GetNewHook() == NULL, "");
  1704. RAW_CHECK(MallocHook::GetDeleteHook() == NULL, "");
  1705. RAW_CHECK(MallocHook::GetMmapHook() == NULL, "");
  1706. RAW_CHECK(MallocHook::GetSbrkHook() == NULL, "");
  1707. have_disabled_hooks_for_symbolize = true;
  1708. leaks->ReportLeaks(name_, pprof_file, true); // true = should_symbolize
  1709. } else {
  1710. leaks->ReportLeaks(name_, pprof_file, false);
  1711. }
  1712. if (FLAGS_heap_check_identify_leaks) {
  1713. leaks->ReportIndividualObjects();
  1714. }
  1715. SuggestPprofCommand(pprof_file);
  1716. {
  1717. SpinLockHolder hl(&heap_checker_lock);
  1718. heap_profile->ReleaseSnapshot(leaks);
  1719. Allocator::Free(pprof_file);
  1720. }
  1721. }
  1722. return (leaks == NULL);
  1723. }
  1724. HeapLeakChecker::~HeapLeakChecker() {
  1725. if (name_ != NULL) { // had leak checking enabled when created the checker
  1726. if (!has_checked_) {
  1727. RAW_LOG(FATAL, "Some *NoLeaks|SameHeap method"
  1728. " must be called on any created HeapLeakChecker");
  1729. }
  1730. // Deallocate any snapshot taken at start
  1731. if (start_snapshot_ != NULL) {
  1732. SpinLockHolder l(&heap_checker_lock);
  1733. heap_profile->ReleaseSnapshot(
  1734. reinterpret_cast<HeapProfileTable::Snapshot*>(start_snapshot_));
  1735. }
  1736. UnIgnoreObject(name_);
  1737. delete[] name_;
  1738. name_ = NULL;
  1739. }
  1740. delete lock_;
  1741. }
  1742. //----------------------------------------------------------------------
  1743. // HeapLeakChecker overall heap check components
  1744. //----------------------------------------------------------------------
  1745. // static
  1746. bool HeapLeakChecker::IsActive() {
  1747. SpinLockHolder l(&heap_checker_lock);
  1748. return heap_checker_on;
  1749. }
  1750. vector<HeapCleaner::void_function>* HeapCleaner::heap_cleanups_ = NULL;
  1751. // When a HeapCleaner object is intialized, add its function to the static list
  1752. // of cleaners to be run before leaks checking.
  1753. HeapCleaner::HeapCleaner(void_function f) {
  1754. if (heap_cleanups_ == NULL)
  1755. heap_cleanups_ = new vector<HeapCleaner::void_function>;
  1756. heap_cleanups_->push_back(f);
  1757. }
  1758. // Run all of the cleanup functions and delete the vector.
  1759. void HeapCleaner::RunHeapCleanups() {
  1760. if (!heap_cleanups_)
  1761. return;
  1762. for (int i = 0; i < heap_cleanups_->size(); i++) {
  1763. void (*f)(void) = (*heap_cleanups_)[i];
  1764. f();
  1765. }
  1766. delete heap_cleanups_;
  1767. heap_cleanups_ = NULL;
  1768. }
  1769. // Program exit heap cleanup registered as a module object destructor.
  1770. // Will not get executed when we crash on a signal.
  1771. //
  1772. void HeapLeakChecker_RunHeapCleanups() {
  1773. if (FLAGS_heap_check == "local") // don't check heap in this mode
  1774. return;
  1775. { SpinLockHolder l(&heap_checker_lock);
  1776. // can get here (via forks?) with other pids
  1777. if (heap_checker_pid != getpid()) return;
  1778. }
  1779. HeapCleaner::RunHeapCleanups();
  1780. if (!FLAGS_heap_check_after_destructors) HeapLeakChecker::DoMainHeapCheck();
  1781. }
  1782. static bool internal_init_start_has_run = false;
  1783. // Called exactly once, before main() (but hopefully just before).
  1784. // This picks a good unique name for the dumped leak checking heap profiles.
  1785. //
  1786. // Because we crash when InternalInitStart is called more than once,
  1787. // it's fine that we hold heap_checker_lock only around pieces of
  1788. // this function: this is still enough for thread-safety w.r.t. other functions
  1789. // of this module.
  1790. // We can't hold heap_checker_lock throughout because it would deadlock
  1791. // on a memory allocation since our new/delete hooks can be on.
  1792. //
  1793. void HeapLeakChecker_InternalInitStart() {
  1794. { SpinLockHolder l(&heap_checker_lock);
  1795. RAW_CHECK(!internal_init_start_has_run,
  1796. "Heap-check constructor called twice. Perhaps you both linked"
  1797. " in the heap checker, and also used LD_PRELOAD to load it?");
  1798. internal_init_start_has_run = true;
  1799. #ifdef ADDRESS_SANITIZER
  1800. // AddressSanitizer's custom malloc conflicts with HeapChecker.
  1801. FLAGS_heap_check = "";
  1802. #endif
  1803. if (FLAGS_heap_check.empty()) {
  1804. // turns out we do not need checking in the end; can stop profiling
  1805. HeapLeakChecker::TurnItselfOffLocked();
  1806. return;
  1807. } else if (RunningOnValgrind()) {
  1808. // There is no point in trying -- we'll just fail.
  1809. RAW_LOG(WARNING, "Can't run under Valgrind; will turn itself off");
  1810. HeapLeakChecker::TurnItselfOffLocked();
  1811. return;
  1812. }
  1813. }
  1814. // Changing this to false can be useful when debugging heap-checker itself:
  1815. if (!FLAGS_heap_check_run_under_gdb && IsDebuggerAttached()) {
  1816. RAW_LOG(WARNING, "Someone is ptrace()ing us; will turn itself off");
  1817. SpinLockHolder l(&heap_checker_lock);
  1818. HeapLeakChecker::TurnItselfOffLocked();
  1819. return;
  1820. }
  1821. { SpinLockHolder l(&heap_checker_lock);
  1822. if (!constructor_heap_profiling) {
  1823. RAW_LOG(FATAL, "Can not start so late. You have to enable heap checking "
  1824. "with HEAPCHECK=<mode>.");
  1825. }
  1826. }
  1827. // Set all flags
  1828. RAW_DCHECK(FLAGS_heap_check_pointer_source_alignment > 0, "");
  1829. if (FLAGS_heap_check == "minimal") {
  1830. // The least we can check.
  1831. FLAGS_heap_check_before_constructors = false; // from after main
  1832. // (ignore more)
  1833. FLAGS_heap_check_after_destructors = false; // to after cleanup
  1834. // (most data is live)
  1835. FLAGS_heap_check_ignore_thread_live = true; // ignore all live
  1836. FLAGS_heap_check_ignore_global_live = true; // ignore all live
  1837. } else if (FLAGS_heap_check == "normal") {
  1838. // Faster than 'minimal' and not much stricter.
  1839. FLAGS_heap_check_before_constructors = true; // from no profile (fast)
  1840. FLAGS_heap_check_after_destructors = false; // to after cleanup
  1841. // (most data is live)
  1842. FLAGS_heap_check_ignore_thread_live = true; // ignore all live
  1843. FLAGS_heap_check_ignore_global_live = true; // ignore all live
  1844. } else if (FLAGS_heap_check == "strict") {
  1845. // A bit stricter than 'normal': global destructors must fully clean up
  1846. // after themselves if they are present.
  1847. FLAGS_heap_check_before_constructors = true; // from no profile (fast)
  1848. FLAGS_heap_check_after_destructors = true; // to after destructors
  1849. // (less data live)
  1850. FLAGS_heap_check_ignore_thread_live = true; // ignore all live
  1851. FLAGS_heap_check_ignore_global_live = true; // ignore all live
  1852. } else if (FLAGS_heap_check == "draconian") {
  1853. // Drop not very portable and not very exact live heap flooding.
  1854. FLAGS_heap_check_before_constructors = true; // from no profile (fast)
  1855. FLAGS_heap_check_after_destructors = true; // to after destructors
  1856. // (need them)
  1857. FLAGS_heap_check_ignore_thread_live = false; // no live flood (stricter)
  1858. FLAGS_heap_check_ignore_global_live = false; // no live flood (stricter)
  1859. } else if (FLAGS_heap_check == "as-is") {
  1860. // do nothing: use other flags as is
  1861. } else if (FLAGS_heap_check == "local") {
  1862. // do nothing
  1863. } else {
  1864. RAW_LOG(FATAL, "Unsupported heap_check flag: %s",
  1865. FLAGS_heap_check.c_str());
  1866. }
  1867. // FreeBSD doesn't seem to honor atexit execution order:
  1868. // http://code.google.com/p/gperftools/issues/detail?id=375
  1869. // Since heap-checking before destructors depends on atexit running
  1870. // at the right time, on FreeBSD we always check after, even in the
  1871. // less strict modes. This just means FreeBSD is always a bit
  1872. // stricter in its checking than other OSes.
  1873. // This now appears to be the case in other OSes as well;
  1874. // so always check afterwards.
  1875. FLAGS_heap_check_after_destructors = true;
  1876. { SpinLockHolder l(&heap_checker_lock);
  1877. RAW_DCHECK(heap_checker_pid == getpid(), "");
  1878. heap_checker_on = true;
  1879. RAW_DCHECK(heap_profile, "");
  1880. HeapLeakChecker::ProcMapsResult pm_result = HeapLeakChecker::UseProcMapsLocked(HeapLeakChecker::DISABLE_LIBRARY_ALLOCS);
  1881. // might neeed to do this more than once
  1882. // if one later dynamically loads libraries that we want disabled
  1883. if (pm_result != HeapLeakChecker::PROC_MAPS_USED) { // can't function
  1884. HeapLeakChecker::TurnItselfOffLocked();
  1885. return;
  1886. }
  1887. }
  1888. // make a good place and name for heap profile leak dumps
  1889. string* profile_prefix =
  1890. new string(FLAGS_heap_check_dump_directory + "/" + invocation_name());
  1891. // Finalize prefix for dumping leak checking profiles.
  1892. const int32 our_pid = getpid(); // safest to call getpid() outside lock
  1893. { SpinLockHolder l(&heap_checker_lock);
  1894. // main_thread_pid might still be 0 if this function is being called before
  1895. // global constructors. In that case, our pid *is* the main pid.
  1896. if (main_thread_pid == 0)
  1897. main_thread_pid = our_pid;
  1898. }
  1899. char pid_buf[15];
  1900. snprintf(pid_buf, sizeof(pid_buf), ".%d", main_thread_pid);
  1901. *profile_prefix += pid_buf;
  1902. { SpinLockHolder l(&heap_checker_lock);
  1903. RAW_DCHECK(profile_name_prefix == NULL, "");
  1904. profile_name_prefix = profile_prefix;
  1905. }
  1906. // Make sure new/delete hooks are installed properly
  1907. // and heap profiler is indeed able to keep track
  1908. // of the objects being allocated.
  1909. // We test this to make sure we are indeed checking for leaks.
  1910. char* test_str = new char[5];
  1911. size_t size;
  1912. { SpinLockHolder l(&heap_checker_lock);
  1913. RAW_CHECK(heap_profile->FindAlloc(test_str, &size),
  1914. "our own new/delete not linked?");
  1915. }
  1916. delete[] test_str;
  1917. { SpinLockHolder l(&heap_checker_lock);
  1918. // This check can fail when it should not if another thread allocates
  1919. // into this same spot right this moment,
  1920. // which is unlikely since this code runs in InitGoogle.
  1921. RAW_CHECK(!heap_profile->FindAlloc(test_str, &size),
  1922. "our own new/delete not linked?");
  1923. }
  1924. // If we crash in the above code, it probably means that
  1925. // "nm <this_binary> | grep new" will show that tcmalloc's new/delete
  1926. // implementation did not get linked-in into this binary
  1927. // (i.e. nm will list __builtin_new and __builtin_vec_new as undefined).
  1928. // If this happens, it is a BUILD bug to be fixed.
  1929. RAW_VLOG(heap_checker_info_level,
  1930. "WARNING: Perftools heap leak checker is active "
  1931. "-- Performance may suffer");
  1932. if (FLAGS_heap_check != "local") {
  1933. HeapLeakChecker* main_hc = new HeapLeakChecker();
  1934. SpinLockHolder l(&heap_checker_lock);
  1935. RAW_DCHECK(main_heap_checker == NULL,
  1936. "Repeated creation of main_heap_checker");
  1937. main_heap_checker = main_hc;
  1938. do_main_heap_check = true;
  1939. }
  1940. { SpinLockHolder l(&heap_checker_lock);
  1941. RAW_CHECK(heap_checker_on && constructor_heap_profiling,
  1942. "Leak checking is expected to be fully turned on now");
  1943. }
  1944. // For binaries built in debug mode, this will set release queue of
  1945. // debugallocation.cc to 100M to make it less likely for real leaks to
  1946. // be hidden due to reuse of heap memory object addresses.
  1947. // Running a test with --malloc_reclaim_memory=0 would help find leaks even
  1948. // better, but the test might run out of memory as a result.
  1949. // The scenario is that a heap object at address X is allocated and freed,
  1950. // but some other data-structure still retains a pointer to X.
  1951. // Then the same heap memory is used for another object, which is leaked,
  1952. // but the leak is not noticed due to the pointer to the original object at X.
  1953. // TODO(csilvers): support this in some manner.
  1954. #if 0
  1955. SetCommandLineOptionWithMode("max_free_queue_size", "104857600", // 100M
  1956. SET_FLAG_IF_DEFAULT);
  1957. #endif
  1958. }
  1959. // We want this to run early as well, but not so early as
  1960. // ::BeforeConstructors (we want flag assignments to have already
  1961. // happened, for instance). Initializer-registration does the trick.
  1962. REGISTER_MODULE_INITIALIZER(init_start, HeapLeakChecker_InternalInitStart());
  1963. REGISTER_MODULE_DESTRUCTOR(init_start, HeapLeakChecker_RunHeapCleanups());
  1964. // static
  1965. bool HeapLeakChecker::NoGlobalLeaksMaybeSymbolize(
  1966. ShouldSymbolize should_symbolize) {
  1967. // we never delete or change main_heap_checker once it's set:
  1968. HeapLeakChecker* main_hc = GlobalChecker();
  1969. if (main_hc) {
  1970. RAW_VLOG(10, "Checking for whole-program memory leaks");
  1971. return main_hc->DoNoLeaks(should_symbolize);
  1972. }
  1973. return true;
  1974. }
  1975. // static
  1976. bool HeapLeakChecker::DoMainHeapCheck() {
  1977. if (FLAGS_heap_check_delay_seconds > 0) {
  1978. sleep(FLAGS_heap_check_delay_seconds);
  1979. }
  1980. { SpinLockHolder l(&heap_checker_lock);
  1981. if (!do_main_heap_check) return false;
  1982. RAW_DCHECK(heap_checker_pid == getpid(), "");
  1983. do_main_heap_check = false; // will do it now; no need to do it more
  1984. }
  1985. // The program is over, so it's safe to symbolize addresses (which
  1986. // requires a fork) because no serious work is expected to be done
  1987. // after this. Symbolizing is really useful -- knowing what
  1988. // function has a leak is better than knowing just an address --
  1989. // and while we can only safely symbolize once in a program run,
  1990. // now is the time (after all, there's no "later" that would be better).
  1991. if (!NoGlobalLeaksMaybeSymbolize(SYMBOLIZE)) {
  1992. if (FLAGS_heap_check_identify_leaks) {
  1993. RAW_LOG(FATAL, "Whole-program memory leaks found.");
  1994. }
  1995. RAW_LOG(ERROR, "Exiting with error code (instead of crashing) "
  1996. "because of whole-program memory leaks");
  1997. _exit(1); // we don't want to call atexit() routines!
  1998. }
  1999. return true;
  2000. }
  2001. // static
  2002. HeapLeakChecker* HeapLeakChecker::GlobalChecker() {
  2003. SpinLockHolder l(&heap_checker_lock);
  2004. return main_heap_checker;
  2005. }
  2006. // static
  2007. bool HeapLeakChecker::NoGlobalLeaks() {
  2008. // symbolizing requires a fork, which isn't safe to do in general.
  2009. return NoGlobalLeaksMaybeSymbolize(DO_NOT_SYMBOLIZE);
  2010. }
  2011. // static
  2012. void HeapLeakChecker::CancelGlobalCheck() {
  2013. SpinLockHolder l(&heap_checker_lock);
  2014. if (do_main_heap_check) {
  2015. RAW_VLOG(heap_checker_info_level,
  2016. "Canceling the automatic at-exit whole-program memory leak check");
  2017. do_main_heap_check = false;
  2018. }
  2019. }
  2020. // static
  2021. void HeapLeakChecker::BeforeConstructorsLocked() {
  2022. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  2023. RAW_CHECK(!constructor_heap_profiling,
  2024. "BeforeConstructorsLocked called multiple times");
  2025. #ifdef ADDRESS_SANITIZER
  2026. // AddressSanitizer's custom malloc conflicts with HeapChecker.
  2027. return;
  2028. #endif
  2029. // Set hooks early to crash if 'new' gets called before we make heap_profile,
  2030. // and make sure no other hooks existed:
  2031. RAW_CHECK(MallocHook::AddNewHook(&NewHook), "");
  2032. RAW_CHECK(MallocHook::AddDeleteHook(&DeleteHook), "");
  2033. constructor_heap_profiling = true;
  2034. MemoryRegionMap::Init(1, /* use_buckets */ false);
  2035. // Set up MemoryRegionMap with (at least) one caller stack frame to record
  2036. // (important that it's done before HeapProfileTable creation below).
  2037. Allocator::Init();
  2038. RAW_CHECK(heap_profile == NULL, "");
  2039. heap_profile = new(Allocator::Allocate(sizeof(HeapProfileTable)))
  2040. HeapProfileTable(&Allocator::Allocate, &Allocator::Free,
  2041. /* profile_mmap */ false);
  2042. RAW_VLOG(10, "Starting tracking the heap");
  2043. heap_checker_on = true;
  2044. }
  2045. // static
  2046. void HeapLeakChecker::TurnItselfOffLocked() {
  2047. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  2048. // Set FLAGS_heap_check to "", for users who test for it
  2049. if (!FLAGS_heap_check.empty()) // be a noop in the common case
  2050. FLAGS_heap_check.clear(); // because clear() could allocate memory
  2051. if (constructor_heap_profiling) {
  2052. RAW_CHECK(heap_checker_on, "");
  2053. RAW_VLOG(heap_checker_info_level, "Turning perftools heap leak checking off");
  2054. heap_checker_on = false;
  2055. // Unset our hooks checking they were set:
  2056. RAW_CHECK(MallocHook::RemoveNewHook(&NewHook), "");
  2057. RAW_CHECK(MallocHook::RemoveDeleteHook(&DeleteHook), "");
  2058. Allocator::DeleteAndNull(&heap_profile);
  2059. // free our optional global data:
  2060. Allocator::DeleteAndNullIfNot(&ignored_objects);
  2061. Allocator::DeleteAndNullIfNot(&disabled_ranges);
  2062. Allocator::DeleteAndNullIfNot(&global_region_caller_ranges);
  2063. Allocator::Shutdown();
  2064. MemoryRegionMap::Shutdown();
  2065. }
  2066. RAW_CHECK(!heap_checker_on, "");
  2067. }
  2068. extern bool heap_leak_checker_bcad_variable; // in heap-checker-bcad.cc
  2069. static bool has_called_before_constructors = false;
  2070. // TODO(maxim): inline this function with
  2071. // MallocHook_InitAtFirstAllocation_HeapLeakChecker, and also rename
  2072. // HeapLeakChecker::BeforeConstructorsLocked.
  2073. void HeapLeakChecker_BeforeConstructors() {
  2074. SpinLockHolder l(&heap_checker_lock);
  2075. // We can be called from several places: the first mmap/sbrk/alloc call
  2076. // or the first global c-tor from heap-checker-bcad.cc:
  2077. // Do not re-execute initialization:
  2078. if (has_called_before_constructors) return;
  2079. has_called_before_constructors = true;
  2080. heap_checker_pid = getpid(); // set it always
  2081. heap_leak_checker_bcad_variable = true;
  2082. // just to reference it, so that heap-checker-bcad.o is linked in
  2083. // This function can be called *very* early, before the normal
  2084. // global-constructor that sets FLAGS_verbose. Set it manually now,
  2085. // so the RAW_LOG messages here are controllable.
  2086. const char* verbose_str = GetenvBeforeMain("PERFTOOLS_VERBOSE");
  2087. if (verbose_str && atoi(verbose_str)) { // different than the default of 0?
  2088. FLAGS_verbose = atoi(verbose_str);
  2089. }
  2090. bool need_heap_check = true;
  2091. // The user indicates a desire for heap-checking via the HEAPCHECK
  2092. // environment variable. If it's not set, there's no way to do
  2093. // heap-checking.
  2094. if (!GetenvBeforeMain("HEAPCHECK")) {
  2095. need_heap_check = false;
  2096. }
  2097. #ifdef HAVE_GETEUID
  2098. if (need_heap_check && getuid() != geteuid()) {
  2099. // heap-checker writes out files. Thus, for security reasons, we don't
  2100. // recognize the env. var. to turn on heap-checking if we're setuid.
  2101. RAW_LOG(WARNING, ("HeapChecker: ignoring HEAPCHECK because "
  2102. "program seems to be setuid\n"));
  2103. need_heap_check = false;
  2104. }
  2105. #endif
  2106. if (need_heap_check) {
  2107. HeapLeakChecker::BeforeConstructorsLocked();
  2108. }
  2109. }
  2110. // This function overrides the weak function defined in malloc_hook.cc and
  2111. // called by one of the initial malloc hooks (malloc_hook.cc) when the very
  2112. // first memory allocation or an mmap/sbrk happens. This ensures that
  2113. // HeapLeakChecker is initialized and installs all its hooks early enough to
  2114. // track absolutely all memory allocations and all memory region acquisitions
  2115. // via mmap and sbrk.
  2116. extern "C" void MallocHook_InitAtFirstAllocation_HeapLeakChecker() {
  2117. HeapLeakChecker_BeforeConstructors();
  2118. }
  2119. // This function is executed after all global object destructors run.
  2120. void HeapLeakChecker_AfterDestructors() {
  2121. { SpinLockHolder l(&heap_checker_lock);
  2122. // can get here (via forks?) with other pids
  2123. if (heap_checker_pid != getpid()) return;
  2124. }
  2125. if (FLAGS_heap_check_after_destructors) {
  2126. if (HeapLeakChecker::DoMainHeapCheck()) {
  2127. const struct timespec sleep_time = { 0, 500000000 }; // 500 ms
  2128. nanosleep(&sleep_time, NULL);
  2129. // Need this hack to wait for other pthreads to exit.
  2130. // Otherwise tcmalloc find errors
  2131. // on a free() call from pthreads.
  2132. }
  2133. }
  2134. SpinLockHolder l(&heap_checker_lock);
  2135. RAW_CHECK(!do_main_heap_check, "should have done it");
  2136. }
  2137. //----------------------------------------------------------------------
  2138. // HeapLeakChecker disabling helpers
  2139. //----------------------------------------------------------------------
  2140. // These functions are at the end of the file to prevent their inlining:
  2141. // static
  2142. void HeapLeakChecker::DisableChecksFromToLocked(const void* start_address,
  2143. const void* end_address,
  2144. int max_depth) {
  2145. RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  2146. RAW_DCHECK(start_address < end_address, "");
  2147. if (disabled_ranges == NULL) {
  2148. disabled_ranges = new(Allocator::Allocate(sizeof(DisabledRangeMap)))
  2149. DisabledRangeMap;
  2150. }
  2151. RangeValue value;
  2152. value.start_address = AsInt(start_address);
  2153. value.max_depth = max_depth;
  2154. if (disabled_ranges->insert(make_pair(AsInt(end_address), value)).second) {
  2155. RAW_VLOG(10, "Disabling leak checking in stack traces "
  2156. "under frame addresses between %p..%p",
  2157. start_address, end_address);
  2158. } else { // check that this is just a verbatim repetition
  2159. RangeValue const& val = disabled_ranges->find(AsInt(end_address))->second;
  2160. if (val.max_depth != value.max_depth ||
  2161. val.start_address != value.start_address) {
  2162. RAW_LOG(FATAL, "Two DisableChecksToHereFrom calls conflict: "
  2163. "(%p, %p, %d) vs. (%p, %p, %d)",
  2164. AsPtr(val.start_address), end_address, val.max_depth,
  2165. start_address, end_address, max_depth);
  2166. }
  2167. }
  2168. }
  2169. // static
  2170. inline bool HeapLeakChecker::HaveOnHeapLocked(const void** ptr,
  2171. size_t* object_size) {
  2172. // Commented-out because HaveOnHeapLocked is very performance-critical:
  2173. // RAW_DCHECK(heap_checker_lock.IsHeld(), "");
  2174. const uintptr_t addr = AsInt(*ptr);
  2175. if (heap_profile->FindInsideAlloc(
  2176. *ptr, max_heap_object_size, ptr, object_size)) {
  2177. RAW_VLOG(16, "Got pointer into %p at +%" PRIuPTR " offset",
  2178. *ptr, addr - AsInt(*ptr));
  2179. return true;
  2180. }
  2181. return false;
  2182. }
  2183. // static
  2184. const void* HeapLeakChecker::GetAllocCaller(void* ptr) {
  2185. // this is used only in the unittest, so the heavy checks are fine
  2186. HeapProfileTable::AllocInfo info;
  2187. { SpinLockHolder l(&heap_checker_lock);
  2188. RAW_CHECK(heap_profile->FindAllocDetails(ptr, &info), "");
  2189. }
  2190. RAW_CHECK(info.stack_depth >= 1, "");
  2191. return info.call_stack[0];
  2192. }