-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
heap-checker.cc
2404 lines (2197 loc) · 97.3 KB
/
heap-checker.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
// Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// All Rights Reserved.
//
// Author: Maxim Lifantsev
//
#include "config.h"
#ifndef __linux__
#error we only support non-ancient Linux-es with native TLS support
#endif
#include <errno.h>
#include <fcntl.h> // for O_RDONLY (we use syscall to do actual reads)
#include <pthread.h>
#include <stddef.h>
#include <string.h>
#include <sys/mman.h> // TODO: check if needed
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <time.h>
#include <unistd.h>
#include <sys/ptrace.h>
#include <sys/procfs.h>
#include <sys/user.h>
#include <elf.h> // NT_PRSTATUS
#include <algorithm>
#include <functional>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <gperftools/heap-checker.h>
#include <gperftools/malloc_extension.h>
#include <gperftools/malloc_hook.h>
#include <gperftools/stacktrace.h>
#include <gperftools/tcmalloc.h>
#include "base/basictypes.h"
#include "base/commandlineflags.h"
#include "base/googleinit.h"
#include "base/linuxthreads.h"
#include "base/logging.h"
#include "base/low_level_alloc.h"
#include "base/proc_maps_iterator.h"
#include "base/spinlock.h"
#include "base/stl_allocator.h"
#include "base/sysinfo.h"
#include "heap-profile-table.h"
#include "malloc_hook-inl.h"
#include "memory_region_map.h"
#include "safe_strerror.h"
// When dealing with ptrace-ed threads, we need to capture all thread
// registers (as potential live pointers), and we need to capture
// thread's stack pointer to scan stack. capture_regs function uses
// ptrace API to grab and scan registers and fetch stack pointer.
template <typename Body>
static std::pair<bool, uintptr_t> CaptureRegs(pid_t tid, const Body& body) {
uintptr_t sp_offset;
#if defined(__aarch64__)
sp_offset = offsetof(user_regs_struct, sp);
#elif defined(__arm__)
sp_offset = 13 * sizeof(uintptr_t); // reg 13 is sp on legacy arms
#elif defined(__x86_64__)
sp_offset = offsetof(user_regs_struct, rsp);
#elif defined(__i386__)
sp_offset = offsetof(user_regs_struct, esp);
#elif defined(__riscv)
sp_offset = 2 * sizeof(uintptr_t); // register #2 is SP on riscv-s
#elif defined(__PPC__)
sp_offset = 1 * sizeof(uintptr_t);
#elif defined(__mips__)
sp_offset = offsetof(struct user, regs[EF_REG29]);
#else
// unsupported HW architecture. Single-threaded programs don't run
// this code, so we still have chance to be useful on less supported
// architectures.
abort();
#endif
elf_gregset_t regs;
int rv;
// PTRACE_GETREGSET is better interface, but manpage says it is
// 2.6.34 or later. RHEL6's kernel is, sadly, older. Yet, I'd like
// us to still support rhel6, so we handle this case too.
#ifdef PTRACE_GETREGSET
iovec iov = {®s, sizeof(regs)};
rv = syscall(SYS_ptrace, PTRACE_GETREGSET, tid, NT_PRSTATUS, &iov);
if (rv == 0) {
if (iov.iov_len != sizeof(regs)) {
abort(); // bug?!
}
}
#else
errno = ENOSYS;
rv = -1;
#endif
// Some Linux architectures and glibc versions only have
// PTRACE_GETREGSET, some only PTRACE_GETREGS and some both.
//
// But glibc tends to define PTRACE_XYZ constants as enums. Some
// newer versions also do define, but older glibc (i.e. as shipped
// by rhel 6) only define PT_GETREGS (to enum value
// PTRACE_GETREGS). Bionic and musl do regular defines,
// thankfully. So there seem to be no absolutely perfect way to
// detect things.
//
// We do detect older interface detection by testing defines for
// both PTRACE_GETREGS and PT_GETREGS. Which seems to work for range
// of OS-es we try to support.
#if defined(PTRACE_GETREGS) || defined(PT_GETREGS)
if (rv < 0 && errno == ENOSYS) {
rv = syscall(SYS_ptrace, PTRACE_GETREGS, tid, nullptr, ®s);
}
#endif
if (rv < 0) {
return {false, 0};
}
uintptr_t sp = *reinterpret_cast<uintptr_t*>(reinterpret_cast<uintptr_t>(®s) + sp_offset);
for (void** p = reinterpret_cast<void**>(®s);
p < reinterpret_cast<void**>(®s + 1); ++p) {
body(*p);
}
return {true, sp};
}
using std::string;
using std::basic_string;
using std::pair;
using std::map;
using std::set;
using std::vector;
using std::swap;
using std::make_pair;
using std::min;
using std::max;
using std::less;
using std::char_traits;
// If current process is being ptrace()d, 'TracerPid' in /proc/self/status
// will be non-zero.
static bool IsDebuggerAttached(void) { // only works under linux, probably
char buf[256]; // TracerPid comes relatively earlier in status output
int fd = open("/proc/self/status", O_RDONLY);
if (fd == -1) {
return false; // Can't tell for sure.
}
const int len = read(fd, buf, sizeof(buf));
bool rc = false;
if (len > 0) {
const char *const kTracerPid = "TracerPid:\t";
buf[len - 1] = '\0';
const char *p = strstr(buf, kTracerPid);
if (p != NULL) {
rc = (strncmp(p + strlen(kTracerPid), "0\n", 2) != 0);
}
}
close(fd);
return rc;
}
// This is the default if you don't link in -lprofiler
extern "C" {
ATTRIBUTE_WEAK PERFTOOLS_DLL_DECL int ProfilingIsEnabledForAllThreads();
int ProfilingIsEnabledForAllThreads() { return false; }
}
//----------------------------------------------------------------------
// Flags that control heap-checking
//----------------------------------------------------------------------
DEFINE_string(heap_check,
EnvToString("HEAPCHECK", ""),
"The heap leak checking to be done over the whole executable: "
"\"minimal\", \"normal\", \"strict\", "
"\"draconian\", \"as-is\", and \"local\" "
" or the empty string are the supported choices. "
"(See HeapLeakChecker_InternalInitStart for details.)");
DEFINE_bool(heap_check_report, true, "Obsolete");
DEFINE_bool(heap_check_before_constructors,
true,
"deprecated; pretty much always true now");
DEFINE_bool(heap_check_after_destructors,
EnvToBool("HEAP_CHECK_AFTER_DESTRUCTORS", false),
"If overall heap check is to end after global destructors "
"or right after all REGISTER_HEAPCHECK_CLEANUP's");
DEFINE_bool(heap_check_strict_check, true, "Obsolete");
DEFINE_bool(heap_check_ignore_global_live,
EnvToBool("HEAP_CHECK_IGNORE_GLOBAL_LIVE", true),
"If overall heap check is to ignore heap objects reachable "
"from the global data");
DEFINE_bool(heap_check_identify_leaks,
EnvToBool("HEAP_CHECK_IDENTIFY_LEAKS", false),
"If heap check should generate the addresses of the leaked "
"objects in the memory leak profiles. This may be useful "
"in tracking down leaks where only a small fraction of "
"objects allocated at the same stack trace are leaked.");
DEFINE_bool(heap_check_ignore_thread_live,
EnvToBool("HEAP_CHECK_IGNORE_THREAD_LIVE", true),
"If set to true, objects reachable from thread stacks "
"and registers are not reported as leaks");
DEFINE_bool(heap_check_test_pointer_alignment,
EnvToBool("HEAP_CHECK_TEST_POINTER_ALIGNMENT", false),
"Set to true to check if the found leak can be due to "
"use of unaligned pointers");
// Alignment at which all pointers in memory are supposed to be located;
// use 1 if any alignment is ok.
// heap_check_test_pointer_alignment flag guides if we try the value of 1.
// The larger it can be, the lesser is the chance of missing real leaks.
static const size_t kPointerSourceAlignment = sizeof(void*);
DEFINE_int32(heap_check_pointer_source_alignment,
EnvToInt("HEAP_CHECK_POINTER_SOURCE_ALIGNMENT",
kPointerSourceAlignment),
"Alignment at which all pointers in memory are supposed to be "
"located. Use 1 if any alignment is ok.");
// A reasonable default to handle pointers inside of typical class objects:
// Too low and we won't be able to traverse pointers to normally-used
// nested objects and base parts of multiple-inherited objects.
// Too high and it will both slow down leak checking (FindInsideAlloc
// in HaveOnHeapLocked will get slower when there are large on-heap objects)
// and make it probabilistically more likely to miss leaks
// of large-sized objects.
static const int64_t kHeapCheckMaxPointerOffset = 1024;
DEFINE_int64(heap_check_max_pointer_offset,
EnvToInt("HEAP_CHECK_MAX_POINTER_OFFSET",
kHeapCheckMaxPointerOffset),
"Largest pointer offset for which we traverse "
"pointers going inside of heap allocated objects. "
"Set to -1 to use the actual largest heap object size.");
DEFINE_bool(heap_check_run_under_gdb,
EnvToBool("HEAP_CHECK_RUN_UNDER_GDB", false),
"If false, turns off heap-checking library when running under gdb "
"(normally, set to 'true' only when debugging the heap-checker)");
DEFINE_int32(heap_check_delay_seconds, 0,
"Number of seconds to delay on-exit heap checking."
" If you set this flag,"
" you may also want to set exit_timeout_seconds in order to"
" avoid exit timeouts.\n"
"NOTE: This flag is to be used only to help diagnose issues"
" where it is suspected that the heap checker is reporting"
" false leaks that will disappear if the heap checker delays"
" its checks. Report any such issues to the heap-checker"
" maintainer(s).");
//----------------------------------------------------------------------
DEFINE_string(heap_profile_pprof,
EnvToString("PPROF_PATH", "pprof"),
"OBSOLETE; not used");
DEFINE_string(heap_check_dump_directory,
EnvToString("HEAP_CHECK_DUMP_DIRECTORY", "/tmp"),
"Directory to put heap-checker leak dump information");
//----------------------------------------------------------------------
// HeapLeakChecker global data
//----------------------------------------------------------------------
// Global lock for all the global data of this module.
static SpinLock heap_checker_lock;
//----------------------------------------------------------------------
// Heap profile prefix for leak checking profiles.
// Gets assigned once when leak checking is turned on, then never modified.
static const string* profile_name_prefix = NULL;
// Whole-program heap leak checker.
// Gets assigned once when leak checking is turned on,
// then main_heap_checker is never deleted.
static HeapLeakChecker* main_heap_checker = NULL;
// Whether we will use main_heap_checker to do a check at program exit
// automatically. In any case user can ask for more checks on main_heap_checker
// via GlobalChecker().
static bool do_main_heap_check = false;
// The heap profile we use to collect info about the heap.
// This is created in HeapLeakChecker::BeforeConstructorsLocked
// together with setting heap_checker_on (below) to true
// and registering our new/delete malloc hooks;
// similarly all are unset in HeapLeakChecker::TurnItselfOffLocked.
static HeapProfileTable* heap_profile = NULL;
// If we are doing (or going to do) any kind of heap-checking.
static bool heap_checker_on = false;
// pid of the process that does whole-program heap leak checking
static pid_t heap_checker_pid = 0;
// If we did heap profiling during global constructors execution
static bool constructor_heap_profiling = false;
// RAW_VLOG level we dump key INFO messages at. If you want to turn
// off these messages, set the environment variable PERFTOOLS_VERBOSE=-1.
static const int heap_checker_info_level = 0;
//----------------------------------------------------------------------
// HeapLeakChecker's own memory allocator that is
// independent of the normal program allocator.
//----------------------------------------------------------------------
// Wrapper of LowLevelAlloc for STL_Allocator and direct use.
// We always access this class under held heap_checker_lock,
// this allows us to in particular protect the period when threads are stopped
// at random spots with TCMalloc_ListAllProcessThreads by heap_checker_lock,
// w/o worrying about the lock in LowLevelAlloc::Arena.
// We rely on the fact that we use an own arena with an own lock here.
class HeapLeakChecker::Allocator {
public:
static void Init() {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
RAW_DCHECK(arena_ == NULL, "");
arena_ = LowLevelAlloc::NewArena(nullptr);
}
static void Shutdown() {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
if (!LowLevelAlloc::DeleteArena(arena_) || alloc_count_ != 0) {
RAW_LOG(FATAL, "Internal heap checker leak of %d objects", alloc_count_);
}
}
static int alloc_count() {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
return alloc_count_;
}
static void* Allocate(size_t n) {
RAW_DCHECK(arena_ && heap_checker_lock.IsHeld(), "");
void* p = LowLevelAlloc::AllocWithArena(n, arena_);
if (p) alloc_count_ += 1;
return p;
}
static void Free(void* p) {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
if (p) alloc_count_ -= 1;
LowLevelAlloc::Free(p);
}
static void Free(void* p, size_t /* n */) {
Free(p);
}
// destruct, free, and make *p to be NULL
template<typename T> static void DeleteAndNull(T** p) {
(*p)->~T();
Free(*p);
*p = NULL;
}
template<typename T> static void DeleteAndNullIfNot(T** p) {
if (*p != NULL) DeleteAndNull(p);
}
private:
static LowLevelAlloc::Arena* arena_;
static int alloc_count_;
};
LowLevelAlloc::Arena* HeapLeakChecker::Allocator::arena_ = NULL;
int HeapLeakChecker::Allocator::alloc_count_ = 0;
//----------------------------------------------------------------------
// HeapLeakChecker live object tracking components
//----------------------------------------------------------------------
// Cases of live object placement we distinguish
enum ObjectPlacement {
MUST_BE_ON_HEAP, // Must point to a live object of the matching size in the
// heap_profile map of the heap when we get to it
IGNORED_ON_HEAP, // Is a live (ignored) object on heap
MAYBE_LIVE, // Is a piece of writable memory from /proc/self/maps
IN_GLOBAL_DATA, // Is part of global data region of the executable
THREAD_DATA, // Part of a thread stack and a thread descriptor with TLS
THREAD_REGISTERS, // Values in registers of some thread
};
// Information about an allocated object
struct AllocObject {
const void* ptr; // the object
uintptr_t size; // its size
ObjectPlacement place; // where ptr points to
AllocObject(const void* p, size_t s, ObjectPlacement l)
: ptr(p), size(s), place(l) { }
};
// All objects (memory ranges) ignored via HeapLeakChecker::IgnoreObject
// Key is the object's address; value is its size.
typedef map<uintptr_t, size_t, less<uintptr_t>,
STL_Allocator<pair<const uintptr_t, size_t>,
HeapLeakChecker::Allocator>
> IgnoredObjectsMap;
static IgnoredObjectsMap* ignored_objects = NULL;
// All objects (memory ranges) that we consider to be the sources of pointers
// to live (not leaked) objects.
// At different times this holds (what can be reached from) global data regions
// and the objects we've been told to ignore.
// For any AllocObject::ptr "live_objects" is supposed to contain at most one
// record at any time. We maintain this by checking with the heap_profile map
// of the heap and removing the live heap objects we've handled from it.
// This vector is maintained as a stack and the frontier of reachable
// live heap objects in our flood traversal of them.
typedef vector<AllocObject,
STL_Allocator<AllocObject, HeapLeakChecker::Allocator>
> LiveObjectsStack;
static LiveObjectsStack* live_objects = NULL;
// A special string type that uses my allocator
typedef basic_string<char, char_traits<char>,
STL_Allocator<char, HeapLeakChecker::Allocator>
> HCL_string;
// A placeholder to fill-in the starting values for live_objects
// for each library so we can keep the library-name association for logging.
typedef map<HCL_string, LiveObjectsStack, less<HCL_string>,
STL_Allocator<pair<const HCL_string, LiveObjectsStack>,
HeapLeakChecker::Allocator>
> LibraryLiveObjectsStacks;
static LibraryLiveObjectsStacks* library_live_objects = NULL;
// Value stored in the map of disabled address ranges;
// its key is the end of the address range.
// We'll ignore allocations with a return address in a disabled range
// if the address occurs at 'max_depth' or less in the stack trace.
struct HeapLeakChecker::RangeValue {
uintptr_t start_address; // the start of the range
int max_depth; // the maximal stack depth to disable at
};
typedef map<uintptr_t, HeapLeakChecker::RangeValue, less<uintptr_t>,
STL_Allocator<pair<const uintptr_t, HeapLeakChecker::RangeValue>,
HeapLeakChecker::Allocator>
> DisabledRangeMap;
// The disabled program counter address ranges for profile dumping
// that are registered with HeapLeakChecker::DisableChecksFromToLocked.
static DisabledRangeMap* disabled_ranges = NULL;
// Set of stack tops.
// These are used to consider live only appropriate chunks of the memory areas
// that are used for stacks (and maybe thread-specific data as well)
// so that we do not treat pointers from outdated stack frames as live.
typedef set<uintptr_t, less<uintptr_t>,
STL_Allocator<uintptr_t, HeapLeakChecker::Allocator>
> StackTopSet;
static StackTopSet* stack_tops = NULL;
// A map of ranges of code addresses for the system libraries
// that can mmap/mremap/sbrk-allocate memory regions for stacks
// and thread-local storage that we want to consider as live global data.
// Maps from the end address to the start address.
typedef map<uintptr_t, uintptr_t, less<uintptr_t>,
STL_Allocator<pair<const uintptr_t, uintptr_t>,
HeapLeakChecker::Allocator>
> GlobalRegionCallerRangeMap;
static GlobalRegionCallerRangeMap* global_region_caller_ranges = NULL;
// TODO(maxim): make our big data structs into own modules
// Disabler is implemented by keeping track of a per-thread count
// of active Disabler objects. Any objects allocated while the
// count > 0 are not reported.
static __thread int thread_disable_counter ATTR_INITIAL_EXEC;
inline int get_thread_disable_counter() {
return thread_disable_counter;
}
inline void set_thread_disable_counter(int value) {
thread_disable_counter = value;
}
HeapLeakChecker::Disabler::Disabler() {
// It is faster to unconditionally increment the thread-local
// counter than to check whether or not heap-checking is on
// in a thread-safe manner.
int counter = get_thread_disable_counter();
set_thread_disable_counter(counter + 1);
RAW_VLOG(10, "Increasing thread disable counter to %d", counter + 1);
}
HeapLeakChecker::Disabler::~Disabler() {
int counter = get_thread_disable_counter();
RAW_DCHECK(counter > 0, "");
if (counter > 0) {
set_thread_disable_counter(counter - 1);
RAW_VLOG(10, "Decreasing thread disable counter to %d", counter);
} else {
RAW_VLOG(0, "Thread disable counter underflow : %d", counter);
}
}
//----------------------------------------------------------------------
// The size of the largest heap object allocated so far.
static size_t max_heap_object_size = 0;
// The possible range of addresses that can point
// into one of the elements of heap_objects.
static uintptr_t min_heap_address = uintptr_t(-1LL);
static uintptr_t max_heap_address = 0;
//----------------------------------------------------------------------
// Simple casting helpers for uintptr_t and void*:
template<typename T>
inline static const void* AsPtr(T addr) {
return reinterpret_cast<void*>(addr);
}
inline static uintptr_t AsInt(const void* ptr) {
return reinterpret_cast<uintptr_t>(ptr);
}
//----------------------------------------------------------------------
// We've seen reports that strstr causes heap-checker crashes in some
// libc's (?):
// https://github.com/gperftools/gperftools/issues/265
// It's simple enough to use our own. This is not in time-critical code.
static const char* hc_strstr(const char* s1, const char* s2) {
const size_t len = strlen(s2);
RAW_CHECK(len > 0, "Unexpected empty string passed to strstr()");
for (const char* p = strchr(s1, *s2); p != NULL; p = strchr(p+1, *s2)) {
if (strncmp(p, s2, len) == 0) {
return p;
}
}
return NULL;
}
//----------------------------------------------------------------------
// Our hooks for MallocHook
static void NewHook(const void* ptr, size_t size) {
if (ptr != NULL) {
const int counter = get_thread_disable_counter();
const bool ignore = (counter > 0);
RAW_VLOG(16, "Recording Alloc: %p of %zu; %d", ptr, size,
int(counter));
// Fetch the caller's stack trace before acquiring heap_checker_lock.
void* stack[HeapProfileTable::kMaxStackDepth];
int depth = HeapProfileTable::GetCallerStackTrace(0, stack);
{ SpinLockHolder l(&heap_checker_lock);
if (size > max_heap_object_size) max_heap_object_size = size;
uintptr_t addr = AsInt(ptr);
if (addr < min_heap_address) min_heap_address = addr;
addr += size;
if (addr > max_heap_address) max_heap_address = addr;
if (heap_checker_on) {
heap_profile->RecordAlloc(ptr, size, depth, stack);
if (ignore) {
heap_profile->MarkAsIgnored(ptr);
}
}
}
RAW_VLOG(17, "Alloc Recorded: %p of %zu", ptr, size);
}
}
static void DeleteHook(const void* ptr) {
if (ptr != NULL) {
RAW_VLOG(16, "Recording Free %p", ptr);
{ SpinLockHolder l(&heap_checker_lock);
if (heap_checker_on) heap_profile->RecordFree(ptr);
}
RAW_VLOG(17, "Free Recorded: %p", ptr);
}
}
//----------------------------------------------------------------------
enum StackDirection {
GROWS_TOWARDS_HIGH_ADDRESSES,
GROWS_TOWARDS_LOW_ADDRESSES,
UNKNOWN_DIRECTION
};
// Determine which way the stack grows:
static StackDirection ATTRIBUTE_NOINLINE GetStackDirection(
const uintptr_t *const ptr) {
uintptr_t x;
if (&x < ptr)
return GROWS_TOWARDS_LOW_ADDRESSES;
if (ptr < &x)
return GROWS_TOWARDS_HIGH_ADDRESSES;
RAW_CHECK(0, ""); // Couldn't determine the stack direction.
return UNKNOWN_DIRECTION;
}
// Direction of stack growth (will initialize via GetStackDirection())
static StackDirection stack_direction = UNKNOWN_DIRECTION;
// This routine is called for every thread stack we know about to register it.
static void RegisterStackLocked(const void* top_ptr) {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
RAW_DCHECK(MemoryRegionMap::LockIsHeld(), "");
RAW_VLOG(10, "Thread stack at %p", top_ptr);
uintptr_t top = AsInt(top_ptr);
stack_tops->insert(top); // add for later use
// make sure stack_direction is initialized
if (stack_direction == UNKNOWN_DIRECTION) {
stack_direction = GetStackDirection(&top);
}
// Find memory region with this stack
MemoryRegionMap::Region region;
if (MemoryRegionMap::FindAndMarkStackRegion(top, ®ion)) {
// Make the proper portion of the stack live:
if (stack_direction == GROWS_TOWARDS_LOW_ADDRESSES) {
RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes",
top_ptr, region.end_addr - top);
live_objects->push_back(AllocObject(top_ptr, region.end_addr - top,
THREAD_DATA));
} else { // GROWS_TOWARDS_HIGH_ADDRESSES
RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes",
AsPtr(region.start_addr),
top - region.start_addr);
live_objects->push_back(AllocObject(AsPtr(region.start_addr),
top - region.start_addr,
THREAD_DATA));
}
// not in MemoryRegionMap, look in library_live_objects:
} else if (FLAGS_heap_check_ignore_global_live) {
for (LibraryLiveObjectsStacks::iterator lib = library_live_objects->begin();
lib != library_live_objects->end(); ++lib) {
for (LiveObjectsStack::iterator span = lib->second.begin();
span != lib->second.end(); ++span) {
uintptr_t start = AsInt(span->ptr);
uintptr_t end = start + span->size;
if (start <= top && top < end) {
RAW_VLOG(11, "Stack at %p is inside /proc/self/maps chunk %p..%p",
top_ptr, AsPtr(start), AsPtr(end));
// Shrink start..end region by chopping away the memory regions in
// MemoryRegionMap that land in it to undo merging of regions
// in /proc/self/maps, so that we correctly identify what portion
// of start..end is actually the stack region.
uintptr_t stack_start = start;
uintptr_t stack_end = end;
// can optimize-away this loop, but it does not run often
RAW_DCHECK(MemoryRegionMap::LockIsHeld(), "");
for (MemoryRegionMap::RegionIterator r =
MemoryRegionMap::BeginRegionLocked();
r != MemoryRegionMap::EndRegionLocked(); ++r) {
if (top < r->start_addr && r->start_addr < stack_end) {
stack_end = r->start_addr;
}
if (stack_start < r->end_addr && r->end_addr <= top) {
stack_start = r->end_addr;
}
}
if (stack_start != start || stack_end != end) {
RAW_VLOG(11, "Stack at %p is actually inside memory chunk %p..%p",
top_ptr, AsPtr(stack_start), AsPtr(stack_end));
}
// Make the proper portion of the stack live:
if (stack_direction == GROWS_TOWARDS_LOW_ADDRESSES) {
RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes",
top_ptr, stack_end - top);
live_objects->push_back(
AllocObject(top_ptr, stack_end - top, THREAD_DATA));
} else { // GROWS_TOWARDS_HIGH_ADDRESSES
RAW_VLOG(11, "Live stack at %p of %" PRIuPTR " bytes",
AsPtr(stack_start), top - stack_start);
live_objects->push_back(
AllocObject(AsPtr(stack_start), top - stack_start, THREAD_DATA));
}
lib->second.erase(span); // kill the rest of the region
// Put the non-stack part(s) of the region back:
if (stack_start != start) {
lib->second.push_back(AllocObject(AsPtr(start), stack_start - start,
MAYBE_LIVE));
}
if (stack_end != end) {
lib->second.push_back(AllocObject(AsPtr(stack_end), end - stack_end,
MAYBE_LIVE));
}
return;
}
}
}
RAW_LOG(ERROR, "Memory region for stack at %p not found. "
"Will likely report false leak positives.", top_ptr);
}
}
// Iterator for heap allocation map data to make ignored objects "live"
// (i.e., treated as roots for the mark-and-sweep phase)
static void MakeIgnoredObjectsLiveCallbackLocked(
const void* ptr, const HeapProfileTable::AllocInfo& info) {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
if (info.ignored) {
live_objects->push_back(AllocObject(ptr, info.object_size,
MUST_BE_ON_HEAP));
}
}
// Iterator for heap allocation map data to make objects allocated from
// disabled regions of code to be live.
static void MakeDisabledLiveCallbackLocked(
const void* ptr, const HeapProfileTable::AllocInfo& info) {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
bool stack_disable = false;
bool range_disable = false;
for (int depth = 0; depth < info.stack_depth; depth++) {
uintptr_t addr = AsInt(info.call_stack[depth]);
if (disabled_ranges) {
DisabledRangeMap::const_iterator iter
= disabled_ranges->upper_bound(addr);
if (iter != disabled_ranges->end()) {
RAW_DCHECK(iter->first > addr, "");
if (iter->second.start_address < addr &&
iter->second.max_depth > depth) {
range_disable = true; // in range; dropping
break;
}
}
}
}
if (stack_disable || range_disable) {
uintptr_t start_address = AsInt(ptr);
uintptr_t end_address = start_address + info.object_size;
StackTopSet::const_iterator iter
= stack_tops->lower_bound(start_address);
if (iter != stack_tops->end()) {
RAW_DCHECK(*iter >= start_address, "");
if (*iter < end_address) {
// We do not disable (treat as live) whole allocated regions
// if they are used to hold thread call stacks
// (i.e. when we find a stack inside).
// The reason is that we'll treat as live the currently used
// stack portions anyway (see RegisterStackLocked),
// and the rest of the region where the stack lives can well
// contain outdated stack variables which are not live anymore,
// hence should not be treated as such.
RAW_VLOG(11, "Not %s-disabling %zu bytes at %p"
": have stack inside: %p",
(stack_disable ? "stack" : "range"),
info.object_size, ptr, AsPtr(*iter));
return;
}
}
RAW_VLOG(11, "%s-disabling %zu bytes at %p",
(stack_disable ? "Stack" : "Range"), info.object_size, ptr);
live_objects->push_back(AllocObject(ptr, info.object_size,
MUST_BE_ON_HEAP));
}
}
static const char kUnnamedProcSelfMapEntry[] = "UNNAMED";
// This function takes some fields from a /proc/self/maps line:
//
// start_address start address of a memory region.
// end_address end address of a memory region
// permissions rwx + private/shared bit
// filename filename of the mapped file
//
// If the region is not writeable, then it cannot have any heap
// pointers in it, otherwise we record it as a candidate live region
// to get filtered later.
static void RecordGlobalDataLocked(uintptr_t start_address,
uintptr_t end_address,
const char* permissions,
const char* filename) {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
// Ignore non-writeable regions.
if (strchr(permissions, 'w') == NULL) return;
if (filename == NULL || *filename == '\0') {
filename = kUnnamedProcSelfMapEntry;
}
RAW_VLOG(11, "Looking into %s: 0x%" PRIxPTR "..0x%" PRIxPTR,
filename, start_address, end_address);
(*library_live_objects)[filename].
push_back(AllocObject(AsPtr(start_address),
end_address - start_address,
MAYBE_LIVE));
}
// See if 'library' from /proc/self/maps has base name 'library_base'
// i.e. contains it and has '.' or '-' after it.
static bool IsLibraryNamed(const char* library, const char* library_base) {
const char* p = hc_strstr(library, library_base);
size_t sz = strlen(library_base);
return p != NULL && (p[sz] == '.' || p[sz] == '-');
}
// static
void HeapLeakChecker::DisableLibraryAllocsLocked(const char* library,
uintptr_t start_address,
uintptr_t end_address) {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
int depth = 0;
// TODO(maxim): maybe this should be extended to also use objdump
// and pick the text portion of the library more precisely.
if (IsLibraryNamed(library, "/libpthread") ||
// libpthread has a lot of small "system" leaks we don't care about.
// In particular it allocates memory to store data supplied via
// tcmalloc::SetTlsValue (which can be the only pointer to a heap object).
IsLibraryNamed(library, "/libdl") ||
// library loaders leak some "system" heap that we don't care about
IsLibraryNamed(library, "/libcrypto") ||
// Sometimes libcrypto of OpenSSH is compiled with -fomit-frame-pointer
// (any library can be, of course, but this one often is because speed
// is so important for making crypto usable). We ignore all its
// allocations because we can't see the call stacks. We'd prefer
// to ignore allocations done in files/symbols that match
// "default_malloc_ex|default_realloc_ex"
// but that doesn't work when the end-result binary is stripped.
IsLibraryNamed(library, "/libjvm") ||
// JVM has a lot of leaks we don't care about.
IsLibraryNamed(library, "/libzip")
// The JVM leaks java.util.zip.Inflater after loading classes.
) {
depth = 1; // only disable allocation calls directly from the library code
} else if (IsLibraryNamed(library, "/ld")
// library loader leaks some "system" heap
// (e.g. thread-local storage) that we don't care about
) {
depth = 2; // disable allocation calls directly from the library code
// and at depth 2 from it.
// We need depth 2 here solely because of a libc bug that
// forces us to jump through __memalign_hook and MemalignOverride hoops
// in tcmalloc.cc.
// Those buggy __libc_memalign() calls are in ld-linux.so and happen for
// thread-local storage allocations that we want to ignore here.
// We go with the depth-2 hack as a workaround for this libc bug:
// otherwise we'd need to extend MallocHook interface
// so that correct stack depth adjustment can be propagated from
// the exceptional case of MemalignOverride.
// Using depth 2 here should not mask real leaks because ld-linux.so
// does not call user code.
}
if (depth) {
RAW_VLOG(10, "Disabling allocations from %s at depth %d:", library, depth);
DisableChecksFromToLocked(AsPtr(start_address), AsPtr(end_address), depth);
if (IsLibraryNamed(library, "/libpthread") ||
IsLibraryNamed(library, "/libdl") ||
IsLibraryNamed(library, "/ld")) {
RAW_VLOG(10, "Global memory regions made by %s will be live data",
library);
if (global_region_caller_ranges == NULL) {
global_region_caller_ranges =
new(Allocator::Allocate(sizeof(GlobalRegionCallerRangeMap)))
GlobalRegionCallerRangeMap;
}
global_region_caller_ranges
->insert(make_pair(end_address, start_address));
}
}
}
// static
HeapLeakChecker::ProcMapsResult HeapLeakChecker::UseProcMapsLocked(
ProcMapsTask proc_maps_task) {
RAW_DCHECK(heap_checker_lock.IsHeld(), "");
bool saw_shared_lib = false;
bool saw_nonzero_inode = false;
bool saw_shared_lib_with_nonzero_inode = false;
bool ok = tcmalloc::ForEachProcMapping([&] (const tcmalloc::ProcMapping& mapping) {
const uint64_t start_address = mapping.start, end_address = mapping.end;
const char *filename = mapping.filename;
if (start_address >= end_address) {
// Warn if a line we can be interested in is ill-formed:
if (mapping.inode != 0) {
RAW_LOG(ERROR, "Errors reading /proc/self/maps. "
"Some global memory regions will not "
"be handled correctly.");
}
// Silently skip other ill-formed lines: some are possible
// probably due to the interplay of how /proc/self/maps is updated
// while we read it in chunks in ProcMapsIterator and
// do things in this loop.
return;
}
// Determine if any shared libraries are present (this is the same
// list of extensions as is found in pprof). We want to ignore
// 'fake' libraries with inode 0 when determining. However, some
// systems don't share inodes via /proc, so we turn off this check
// if we don't see any evidence that we're getting inode info.
if (mapping.inode != 0) {
saw_nonzero_inode = true;
}
if ((hc_strstr(filename, "lib") && hc_strstr(filename, ".so")) ||
hc_strstr(filename, ".dll") ||
// not all .dylib filenames start with lib. .dylib is big enough
// that we are unlikely to get false matches just checking that.
hc_strstr(filename, ".dylib") || hc_strstr(filename, ".bundle")) {
saw_shared_lib = true;
if (mapping.inode != 0) {
saw_shared_lib_with_nonzero_inode = true;
}
}
switch (proc_maps_task) {
case DISABLE_LIBRARY_ALLOCS:
// All lines starting like
// "401dc000-4030f000 r??p 00132000 03:01 13991972 lib/bin"
// identify a data and code sections of a shared library or our binary
if (mapping.inode != 0 && strncmp(mapping.flags, "r-xp", 4) == 0) {
DisableLibraryAllocsLocked(filename, start_address, end_address);
}
break;
case RECORD_GLOBAL_DATA:
RecordGlobalDataLocked(start_address, end_address,
mapping.flags, filename);
break;
default:
RAW_CHECK(0, "");
}
});
if (!ok) {
int errsv = errno;
RAW_LOG(ERROR, "Could not open /proc/self/maps: errno=%d. "
"Libraries will not be handled correctly.", errsv);
return CANT_OPEN_PROC_MAPS;
}
// If /proc/self/maps is reporting inodes properly (we saw a
// non-zero inode), then we only say we saw a shared lib if we saw a
// 'real' one, with a non-zero inode.
if (saw_nonzero_inode) {
saw_shared_lib = saw_shared_lib_with_nonzero_inode;
}
if (!saw_shared_lib) {
RAW_LOG(ERROR, "No shared libs detected. Will likely report false leak "
"positives for statically linked executables.");
return NO_SHARED_LIBS_IN_PROC_MAPS;
}
return PROC_MAPS_USED;
}
// Total number and size of live objects dropped from the profile;
// (re)initialized in IgnoreAllLiveObjectsLocked.
static int64_t live_objects_total;
static int64_t live_bytes_total;
// pid of the thread that is doing the current leak check
// (protected by our lock; IgnoreAllLiveObjectsLocked sets it)
static pid_t self_thread_pid = 0;
// Status of our thread listing callback execution
// (protected by our lock; used from within IgnoreAllLiveObjectsLocked)