Bug Summary

File:projects/compiler-rt/lib/lsan/lsan_common.cc
Warning:line 657, column 3
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name lsan_common.cc -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/projects/compiler-rt/lib/lsan -I /build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -I /build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/.. -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -Wno-unused-parameter -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -Wno-unused-parameter -Wno-variadic-macros -Wno-non-virtual-dtor -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/projects/compiler-rt/lib/lsan -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fvisibility-inlines-hidden -fno-builtin -fno-rtti -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc -faddrsig
1//=-- lsan_common.cc ------------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of LeakSanitizer.
11// Implementation of common leak checking functionality.
12//
13//===----------------------------------------------------------------------===//
14
15#include "lsan_common.h"
16
17#include "sanitizer_common/sanitizer_common.h"
18#include "sanitizer_common/sanitizer_flag_parser.h"
19#include "sanitizer_common/sanitizer_flags.h"
20#include "sanitizer_common/sanitizer_placement_new.h"
21#include "sanitizer_common/sanitizer_procmaps.h"
22#include "sanitizer_common/sanitizer_report_decorator.h"
23#include "sanitizer_common/sanitizer_stackdepot.h"
24#include "sanitizer_common/sanitizer_stacktrace.h"
25#include "sanitizer_common/sanitizer_suppressions.h"
26#include "sanitizer_common/sanitizer_thread_registry.h"
27#include "sanitizer_common/sanitizer_tls_get_addr.h"
28
29#if CAN_SANITIZE_LEAKS1
30namespace __lsan {
31
32// This mutex is used to prevent races between DoLeakCheck and IgnoreObject, and
33// also to protect the global list of root regions.
34BlockingMutex global_mutex(LINKER_INITIALIZED);
35
36Flags lsan_flags;
37
38void DisableCounterUnderflow() {
39 if (common_flags()->detect_leaks) {
40 Report("Unmatched call to __lsan_enable().\n");
41 Die();
42 }
43}
44
45void Flags::SetDefaults() {
46#define LSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
47#include "lsan_flags.inc"
48#undef LSAN_FLAG
49}
50
51void RegisterLsanFlags(FlagParser *parser, Flags *f) {
52#define LSAN_FLAG(Type, Name, DefaultValue, Description) \
53 RegisterFlag(parser, #Name, Description, &f->Name);
54#include "lsan_flags.inc"
55#undef LSAN_FLAG
56}
57
58#define LOG_POINTERS(...)do { if (flags()->log_pointers) Report(...); } while (0) \
59 do { \
60 if (flags()->log_pointers) Report(__VA_ARGS__); \
61 } while (0)
62
63#define LOG_THREADS(...)do { if (flags()->log_threads) Report(...); } while (0) \
64 do { \
65 if (flags()->log_threads) Report(__VA_ARGS__); \
66 } while (0)
67
68ALIGNED(64)__attribute__((aligned(64))) static char suppression_placeholder[sizeof(SuppressionContext)];
69static SuppressionContext *suppression_ctx = nullptr;
70static const char kSuppressionLeak[] = "leak";
71static const char *kSuppressionTypes[] = { kSuppressionLeak };
72static const char kStdSuppressions[] =
73#if SANITIZER_SUPPRESS_LEAK_ON_PTHREAD_EXIT0
74 // For more details refer to the SANITIZER_SUPPRESS_LEAK_ON_PTHREAD_EXIT
75 // definition.
76 "leak:*pthread_exit*\n"
77#endif // SANITIZER_SUPPRESS_LEAK_ON_PTHREAD_EXIT
78#if SANITIZER_MAC0
79 // For Darwin and os_log/os_trace: https://reviews.llvm.org/D35173
80 "leak:*_os_trace*\n"
81#endif
82 // TLS leak in some glibc versions, described in
83 // https://sourceware.org/bugzilla/show_bug.cgi?id=12650.
84 "leak:*tls_get_addr*\n";
85
86void InitializeSuppressions() {
87 CHECK_EQ(nullptr, suppression_ctx)do { __sanitizer::u64 v1 = (__sanitizer::u64)((nullptr)); __sanitizer
::u64 v2 = (__sanitizer::u64)((suppression_ctx)); if (__builtin_expect
(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 87, "(" "(nullptr)" ") " "==" " (" "(suppression_ctx)" ")",
v1, v2); } while (false)
;
88 suppression_ctx = new (suppression_placeholder) // NOLINT
89 SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes)(sizeof(kSuppressionTypes)/sizeof((kSuppressionTypes)[0])));
90 suppression_ctx->ParseFromFile(flags()->suppressions);
91 if (&__lsan_default_suppressions)
92 suppression_ctx->Parse(__lsan_default_suppressions());
93 suppression_ctx->Parse(kStdSuppressions);
94}
95
96static SuppressionContext *GetSuppressionContext() {
97 CHECK(suppression_ctx)do { __sanitizer::u64 v1 = (__sanitizer::u64)((suppression_ctx
)); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 97, "(" "(suppression_ctx)" ") " "!=" " (" "0" ")", v1, v2)
; } while (false)
;
98 return suppression_ctx;
99}
100
101static InternalMmapVector<RootRegion> *root_regions;
102
103static uptr initialized_for_pid;
104
105InternalMmapVector<RootRegion> const *GetRootRegions() { return root_regions; }
106
107void InitializeRootRegions() {
108 CHECK(!root_regions)do { __sanitizer::u64 v1 = (__sanitizer::u64)((!root_regions)
); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 108, "(" "(!root_regions)" ") " "!=" " (" "0" ")", v1, v2);
} while (false)
;
109 ALIGNED(64)__attribute__((aligned(64))) static char placeholder[sizeof(InternalMmapVector<RootRegion>)];
110 root_regions = new (placeholder) InternalMmapVector<RootRegion>(); // NOLINT
111}
112
113const char *MaybeCallLsanDefaultOptions() {
114 return (&__lsan_default_options) ? __lsan_default_options() : "";
115}
116
117void InitCommonLsan() {
118 initialized_for_pid = internal_getpid();
119 InitializeRootRegions();
120 if (common_flags()->detect_leaks) {
121 // Initialization which can fail or print warnings should only be done if
122 // LSan is actually enabled.
123 InitializeSuppressions();
124 InitializePlatformSpecificModules();
125 }
126}
127
128class Decorator: public __sanitizer::SanitizerCommonDecorator {
129 public:
130 Decorator() : SanitizerCommonDecorator() { }
131 const char *Error() { return Red(); }
132 const char *Leak() { return Blue(); }
133};
134
135static inline bool CanBeAHeapPointer(uptr p) {
136 // Since our heap is located in mmap-ed memory, we can assume a sensible lower
137 // bound on heap addresses.
138 const uptr kMinAddress = 4 * 4096;
139 if (p < kMinAddress) return false;
140#if defined(__x86_64__1)
141 // Accept only canonical form user-space addresses.
142 return ((p >> 47) == 0);
143#elif defined(__mips64)
144 return ((p >> 40) == 0);
145#elif defined(__aarch64__)
146 unsigned runtimeVMA =
147 (MostSignificantSetBitIndex(GET_CURRENT_FRAME()(__sanitizer::uptr) __builtin_frame_address(0)) + 1);
148 return ((p >> runtimeVMA) == 0);
149#else
150 return true;
151#endif
152}
153
154// Scans the memory range, looking for byte patterns that point into allocator
155// chunks. Marks those chunks with |tag| and adds them to |frontier|.
156// There are two usage modes for this function: finding reachable chunks
157// (|tag| = kReachable) and finding indirectly leaked chunks
158// (|tag| = kIndirectlyLeaked). In the second case, there's no flood fill,
159// so |frontier| = 0.
160void ScanRangeForPointers(uptr begin, uptr end,
161 Frontier *frontier,
162 const char *region_type, ChunkTag tag) {
163 CHECK(tag == kReachable || tag == kIndirectlyLeaked)do { __sanitizer::u64 v1 = (__sanitizer::u64)((tag == kReachable
|| tag == kIndirectlyLeaked)); __sanitizer::u64 v2 = (__sanitizer
::u64)(0); if (__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer
::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 163, "(" "(tag == kReachable || tag == kIndirectlyLeaked)" ") "
"!=" " (" "0" ")", v1, v2); } while (false)
;
164 const uptr alignment = flags()->pointer_alignment();
165 LOG_POINTERS("Scanning %s range %p-%p.\n", region_type, begin, end)do { if (flags()->log_pointers) Report("Scanning %s range %p-%p.\n"
, region_type, begin, end); } while (0)
;
166 uptr pp = begin;
167 if (pp % alignment)
168 pp = pp + alignment - pp % alignment;
169 for (; pp + sizeof(void *) <= end; pp += alignment) { // NOLINT
170 void *p = *reinterpret_cast<void **>(pp);
171 if (!CanBeAHeapPointer(reinterpret_cast<uptr>(p))) continue;
172 uptr chunk = PointsIntoChunk(p);
173 if (!chunk) continue;
174 // Pointers to self don't count. This matters when tag == kIndirectlyLeaked.
175 if (chunk == begin) continue;
176 LsanMetadata m(chunk);
177 if (m.tag() == kReachable || m.tag() == kIgnored) continue;
178
179 // Do this check relatively late so we can log only the interesting cases.
180 if (!flags()->use_poisoned && WordIsPoisoned(pp)) {
181 LOG_POINTERS(do { if (flags()->log_pointers) Report("%p is poisoned: ignoring %p pointing into chunk %p-%p of size "
"%zu.\n", pp, p, chunk, chunk + m.requested_size(), m.requested_size
()); } while (0)
182 "%p is poisoned: ignoring %p pointing into chunk %p-%p of size "do { if (flags()->log_pointers) Report("%p is poisoned: ignoring %p pointing into chunk %p-%p of size "
"%zu.\n", pp, p, chunk, chunk + m.requested_size(), m.requested_size
()); } while (0)
183 "%zu.\n",do { if (flags()->log_pointers) Report("%p is poisoned: ignoring %p pointing into chunk %p-%p of size "
"%zu.\n", pp, p, chunk, chunk + m.requested_size(), m.requested_size
()); } while (0)
184 pp, p, chunk, chunk + m.requested_size(), m.requested_size())do { if (flags()->log_pointers) Report("%p is poisoned: ignoring %p pointing into chunk %p-%p of size "
"%zu.\n", pp, p, chunk, chunk + m.requested_size(), m.requested_size
()); } while (0)
;
185 continue;
186 }
187
188 m.set_tag(tag);
189 LOG_POINTERS("%p: found %p pointing into chunk %p-%p of size %zu.\n", pp, p,do { if (flags()->log_pointers) Report("%p: found %p pointing into chunk %p-%p of size %zu.\n"
, pp, p, chunk, chunk + m.requested_size(), m.requested_size(
)); } while (0)
190 chunk, chunk + m.requested_size(), m.requested_size())do { if (flags()->log_pointers) Report("%p: found %p pointing into chunk %p-%p of size %zu.\n"
, pp, p, chunk, chunk + m.requested_size(), m.requested_size(
)); } while (0)
;
191 if (frontier)
192 frontier->push_back(chunk);
193 }
194}
195
196// Scans a global range for pointers
197void ScanGlobalRange(uptr begin, uptr end, Frontier *frontier) {
198 uptr allocator_begin = 0, allocator_end = 0;
199 GetAllocatorGlobalRange(&allocator_begin, &allocator_end);
200 if (begin <= allocator_begin && allocator_begin < end) {
201 CHECK_LE(allocator_begin, allocator_end)do { __sanitizer::u64 v1 = (__sanitizer::u64)((allocator_begin
)); __sanitizer::u64 v2 = (__sanitizer::u64)((allocator_end))
; if (__builtin_expect(!!(!(v1 <= v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 201, "(" "(allocator_begin)" ") " "<=" " (" "(allocator_end)"
")", v1, v2); } while (false)
;
202 CHECK_LE(allocator_end, end)do { __sanitizer::u64 v1 = (__sanitizer::u64)((allocator_end)
); __sanitizer::u64 v2 = (__sanitizer::u64)((end)); if (__builtin_expect
(!!(!(v1 <= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 202, "(" "(allocator_end)" ") " "<=" " (" "(end)" ")", v1
, v2); } while (false)
;
203 if (begin < allocator_begin)
204 ScanRangeForPointers(begin, allocator_begin, frontier, "GLOBAL",
205 kReachable);
206 if (allocator_end < end)
207 ScanRangeForPointers(allocator_end, end, frontier, "GLOBAL", kReachable);
208 } else {
209 ScanRangeForPointers(begin, end, frontier, "GLOBAL", kReachable);
210 }
211}
212
213void ForEachExtraStackRangeCb(uptr begin, uptr end, void* arg) {
214 Frontier *frontier = reinterpret_cast<Frontier *>(arg);
215 ScanRangeForPointers(begin, end, frontier, "FAKE STACK", kReachable);
216}
217
218// Scans thread data (stacks and TLS) for heap pointers.
219static void ProcessThreads(SuspendedThreadsList const &suspended_threads,
220 Frontier *frontier) {
221 InternalMmapVector<uptr> registers(suspended_threads.RegisterCount());
222 uptr registers_begin = reinterpret_cast<uptr>(registers.data());
223 uptr registers_end =
224 reinterpret_cast<uptr>(registers.data() + registers.size());
225 for (uptr i = 0; i < suspended_threads.ThreadCount(); i++) {
226 tid_t os_id = static_cast<tid_t>(suspended_threads.GetThreadID(i));
227 LOG_THREADS("Processing thread %d.\n", os_id)do { if (flags()->log_threads) Report("Processing thread %d.\n"
, os_id); } while (0)
;
228 uptr stack_begin, stack_end, tls_begin, tls_end, cache_begin, cache_end;
229 DTLS *dtls;
230 bool thread_found = GetThreadRangesLocked(os_id, &stack_begin, &stack_end,
231 &tls_begin, &tls_end,
232 &cache_begin, &cache_end, &dtls);
233 if (!thread_found) {
234 // If a thread can't be found in the thread registry, it's probably in the
235 // process of destruction. Log this event and move on.
236 LOG_THREADS("Thread %d not found in registry.\n", os_id)do { if (flags()->log_threads) Report("Thread %d not found in registry.\n"
, os_id); } while (0)
;
237 continue;
238 }
239 uptr sp;
240 PtraceRegistersStatus have_registers =
241 suspended_threads.GetRegistersAndSP(i, registers.data(), &sp);
242 if (have_registers != REGISTERS_AVAILABLE) {
243 Report("Unable to get registers from thread %d.\n", os_id);
244 // If unable to get SP, consider the entire stack to be reachable unless
245 // GetRegistersAndSP failed with ESRCH.
246 if (have_registers == REGISTERS_UNAVAILABLE_FATAL) continue;
247 sp = stack_begin;
248 }
249
250 if (flags()->use_registers && have_registers)
251 ScanRangeForPointers(registers_begin, registers_end, frontier,
252 "REGISTERS", kReachable);
253
254 if (flags()->use_stacks) {
255 LOG_THREADS("Stack at %p-%p (SP = %p).\n", stack_begin, stack_end, sp)do { if (flags()->log_threads) Report("Stack at %p-%p (SP = %p).\n"
, stack_begin, stack_end, sp); } while (0)
;
256 if (sp < stack_begin || sp >= stack_end) {
257 // SP is outside the recorded stack range (e.g. the thread is running a
258 // signal handler on alternate stack, or swapcontext was used).
259 // Again, consider the entire stack range to be reachable.
260 LOG_THREADS("WARNING: stack pointer not in stack range.\n")do { if (flags()->log_threads) Report("WARNING: stack pointer not in stack range.\n"
); } while (0)
;
261 uptr page_size = GetPageSizeCached();
262 int skipped = 0;
263 while (stack_begin < stack_end &&
264 !IsAccessibleMemoryRange(stack_begin, 1)) {
265 skipped++;
266 stack_begin += page_size;
267 }
268 LOG_THREADS("Skipped %d guard page(s) to obtain stack %p-%p.\n",do { if (flags()->log_threads) Report("Skipped %d guard page(s) to obtain stack %p-%p.\n"
, skipped, stack_begin, stack_end); } while (0)
269 skipped, stack_begin, stack_end)do { if (flags()->log_threads) Report("Skipped %d guard page(s) to obtain stack %p-%p.\n"
, skipped, stack_begin, stack_end); } while (0)
;
270 } else {
271 // Shrink the stack range to ignore out-of-scope values.
272 stack_begin = sp;
273 }
274 ScanRangeForPointers(stack_begin, stack_end, frontier, "STACK",
275 kReachable);
276 ForEachExtraStackRange(os_id, ForEachExtraStackRangeCb, frontier);
277 }
278
279 if (flags()->use_tls) {
280 if (tls_begin) {
281 LOG_THREADS("TLS at %p-%p.\n", tls_begin, tls_end)do { if (flags()->log_threads) Report("TLS at %p-%p.\n", tls_begin
, tls_end); } while (0)
;
282 // If the tls and cache ranges don't overlap, scan full tls range,
283 // otherwise, only scan the non-overlapping portions
284 if (cache_begin == cache_end || tls_end < cache_begin ||
285 tls_begin > cache_end) {
286 ScanRangeForPointers(tls_begin, tls_end, frontier, "TLS", kReachable);
287 } else {
288 if (tls_begin < cache_begin)
289 ScanRangeForPointers(tls_begin, cache_begin, frontier, "TLS",
290 kReachable);
291 if (tls_end > cache_end)
292 ScanRangeForPointers(cache_end, tls_end, frontier, "TLS",
293 kReachable);
294 }
295 }
296 if (dtls && !DTLSInDestruction(dtls)) {
297 for (uptr j = 0; j < dtls->dtv_size; ++j) {
298 uptr dtls_beg = dtls->dtv[j].beg;
299 uptr dtls_end = dtls_beg + dtls->dtv[j].size;
300 if (dtls_beg < dtls_end) {
301 LOG_THREADS("DTLS %zu at %p-%p.\n", j, dtls_beg, dtls_end)do { if (flags()->log_threads) Report("DTLS %zu at %p-%p.\n"
, j, dtls_beg, dtls_end); } while (0)
;
302 ScanRangeForPointers(dtls_beg, dtls_end, frontier, "DTLS",
303 kReachable);
304 }
305 }
306 } else {
307 // We are handling a thread with DTLS under destruction. Log about
308 // this and continue.
309 LOG_THREADS("Thread %d has DTLS under destruction.\n", os_id)do { if (flags()->log_threads) Report("Thread %d has DTLS under destruction.\n"
, os_id); } while (0)
;
310 }
311 }
312 }
313}
314
315void ScanRootRegion(Frontier *frontier, const RootRegion &root_region,
316 uptr region_begin, uptr region_end, bool is_readable) {
317 uptr intersection_begin = Max(root_region.begin, region_begin);
318 uptr intersection_end = Min(region_end, root_region.begin + root_region.size);
319 if (intersection_begin >= intersection_end) return;
320 LOG_POINTERS("Root region %p-%p intersects with mapped region %p-%p (%s)\n",do { if (flags()->log_pointers) Report("Root region %p-%p intersects with mapped region %p-%p (%s)\n"
, root_region.begin, root_region.begin + root_region.size, region_begin
, region_end, is_readable ? "readable" : "unreadable"); } while
(0)
321 root_region.begin, root_region.begin + root_region.size,do { if (flags()->log_pointers) Report("Root region %p-%p intersects with mapped region %p-%p (%s)\n"
, root_region.begin, root_region.begin + root_region.size, region_begin
, region_end, is_readable ? "readable" : "unreadable"); } while
(0)
322 region_begin, region_end,do { if (flags()->log_pointers) Report("Root region %p-%p intersects with mapped region %p-%p (%s)\n"
, root_region.begin, root_region.begin + root_region.size, region_begin
, region_end, is_readable ? "readable" : "unreadable"); } while
(0)
323 is_readable ? "readable" : "unreadable")do { if (flags()->log_pointers) Report("Root region %p-%p intersects with mapped region %p-%p (%s)\n"
, root_region.begin, root_region.begin + root_region.size, region_begin
, region_end, is_readable ? "readable" : "unreadable"); } while
(0)
;
324 if (is_readable)
325 ScanRangeForPointers(intersection_begin, intersection_end, frontier, "ROOT",
326 kReachable);
327}
328
329static void ProcessRootRegion(Frontier *frontier,
330 const RootRegion &root_region) {
331 MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
332 MemoryMappedSegment segment;
333 while (proc_maps.Next(&segment)) {
334 ScanRootRegion(frontier, root_region, segment.start, segment.end,
335 segment.IsReadable());
336 }
337}
338
339// Scans root regions for heap pointers.
340static void ProcessRootRegions(Frontier *frontier) {
341 if (!flags()->use_root_regions) return;
342 CHECK(root_regions)do { __sanitizer::u64 v1 = (__sanitizer::u64)((root_regions))
; __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 342, "(" "(root_regions)" ") " "!=" " (" "0" ")", v1, v2); }
while (false)
;
343 for (uptr i = 0; i < root_regions->size(); i++) {
344 ProcessRootRegion(frontier, (*root_regions)[i]);
345 }
346}
347
348static void FloodFillTag(Frontier *frontier, ChunkTag tag) {
349 while (frontier->size()) {
350 uptr next_chunk = frontier->back();
351 frontier->pop_back();
352 LsanMetadata m(next_chunk);
353 ScanRangeForPointers(next_chunk, next_chunk + m.requested_size(), frontier,
354 "HEAP", tag);
355 }
356}
357
358// ForEachChunk callback. If the chunk is marked as leaked, marks all chunks
359// which are reachable from it as indirectly leaked.
360static void MarkIndirectlyLeakedCb(uptr chunk, void *arg) {
361 chunk = GetUserBegin(chunk);
362 LsanMetadata m(chunk);
363 if (m.allocated() && m.tag() != kReachable) {
364 ScanRangeForPointers(chunk, chunk + m.requested_size(),
365 /* frontier */ nullptr, "HEAP", kIndirectlyLeaked);
366 }
367}
368
369// ForEachChunk callback. If chunk is marked as ignored, adds its address to
370// frontier.
371static void CollectIgnoredCb(uptr chunk, void *arg) {
372 CHECK(arg)do { __sanitizer::u64 v1 = (__sanitizer::u64)((arg)); __sanitizer
::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect(!!(!(v1
!= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 372, "(" "(arg)" ") " "!=" " (" "0" ")", v1, v2); } while (
false)
;
373 chunk = GetUserBegin(chunk);
374 LsanMetadata m(chunk);
375 if (m.allocated() && m.tag() == kIgnored) {
376 LOG_POINTERS("Ignored: chunk %p-%p of size %zu.\n",do { if (flags()->log_pointers) Report("Ignored: chunk %p-%p of size %zu.\n"
, chunk, chunk + m.requested_size(), m.requested_size()); } while
(0)
377 chunk, chunk + m.requested_size(), m.requested_size())do { if (flags()->log_pointers) Report("Ignored: chunk %p-%p of size %zu.\n"
, chunk, chunk + m.requested_size(), m.requested_size()); } while
(0)
;
378 reinterpret_cast<Frontier *>(arg)->push_back(chunk);
379 }
380}
381
382static uptr GetCallerPC(u32 stack_id, StackDepotReverseMap *map) {
383 CHECK(stack_id)do { __sanitizer::u64 v1 = (__sanitizer::u64)((stack_id)); __sanitizer
::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect(!!(!(v1
!= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 383, "(" "(stack_id)" ") " "!=" " (" "0" ")", v1, v2); } while
(false)
;
384 StackTrace stack = map->Get(stack_id);
385 // The top frame is our malloc/calloc/etc. The next frame is the caller.
386 if (stack.size >= 2)
387 return stack.trace[1];
388 return 0;
389}
390
391struct InvalidPCParam {
392 Frontier *frontier;
393 StackDepotReverseMap *stack_depot_reverse_map;
394 bool skip_linker_allocations;
395};
396
397// ForEachChunk callback. If the caller pc is invalid or is within the linker,
398// mark as reachable. Called by ProcessPlatformSpecificAllocations.
399static void MarkInvalidPCCb(uptr chunk, void *arg) {
400 CHECK(arg)do { __sanitizer::u64 v1 = (__sanitizer::u64)((arg)); __sanitizer
::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect(!!(!(v1
!= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 400, "(" "(arg)" ") " "!=" " (" "0" ")", v1, v2); } while (
false)
;
401 InvalidPCParam *param = reinterpret_cast<InvalidPCParam *>(arg);
402 chunk = GetUserBegin(chunk);
403 LsanMetadata m(chunk);
404 if (m.allocated() && m.tag() != kReachable && m.tag() != kIgnored) {
405 u32 stack_id = m.stack_trace_id();
406 uptr caller_pc = 0;
407 if (stack_id > 0)
408 caller_pc = GetCallerPC(stack_id, param->stack_depot_reverse_map);
409 // If caller_pc is unknown, this chunk may be allocated in a coroutine. Mark
410 // it as reachable, as we can't properly report its allocation stack anyway.
411 if (caller_pc == 0 || (param->skip_linker_allocations &&
412 GetLinker()->containsAddress(caller_pc))) {
413 m.set_tag(kReachable);
414 param->frontier->push_back(chunk);
415 }
416 }
417}
418
419// On Linux, treats all chunks allocated from ld-linux.so as reachable, which
420// covers dynamically allocated TLS blocks, internal dynamic loader's loaded
421// modules accounting etc.
422// Dynamic TLS blocks contain the TLS variables of dynamically loaded modules.
423// They are allocated with a __libc_memalign() call in allocate_and_init()
424// (elf/dl-tls.c). Glibc won't tell us the address ranges occupied by those
425// blocks, but we can make sure they come from our own allocator by intercepting
426// __libc_memalign(). On top of that, there is no easy way to reach them. Their
427// addresses are stored in a dynamically allocated array (the DTV) which is
428// referenced from the static TLS. Unfortunately, we can't just rely on the DTV
429// being reachable from the static TLS, and the dynamic TLS being reachable from
430// the DTV. This is because the initial DTV is allocated before our interception
431// mechanism kicks in, and thus we don't recognize it as allocated memory. We
432// can't special-case it either, since we don't know its size.
433// Our solution is to include in the root set all allocations made from
434// ld-linux.so (which is where allocate_and_init() is implemented). This is
435// guaranteed to include all dynamic TLS blocks (and possibly other allocations
436// which we don't care about).
437// On all other platforms, this simply checks to ensure that the caller pc is
438// valid before reporting chunks as leaked.
439void ProcessPC(Frontier *frontier) {
440 StackDepotReverseMap stack_depot_reverse_map;
441 InvalidPCParam arg;
442 arg.frontier = frontier;
443 arg.stack_depot_reverse_map = &stack_depot_reverse_map;
444 arg.skip_linker_allocations =
445 flags()->use_tls && flags()->use_ld_allocations && GetLinker() != nullptr;
446 ForEachChunk(MarkInvalidPCCb, &arg);
447}
448
449// Sets the appropriate tag on each chunk.
450static void ClassifyAllChunks(SuspendedThreadsList const &suspended_threads) {
451 // Holds the flood fill frontier.
452 Frontier frontier;
453
454 ForEachChunk(CollectIgnoredCb, &frontier);
455 ProcessGlobalRegions(&frontier);
456 ProcessThreads(suspended_threads, &frontier);
457 ProcessRootRegions(&frontier);
458 FloodFillTag(&frontier, kReachable);
459
460 CHECK_EQ(0, frontier.size())do { __sanitizer::u64 v1 = (__sanitizer::u64)((0)); __sanitizer
::u64 v2 = (__sanitizer::u64)((frontier.size())); if (__builtin_expect
(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 460, "(" "(0)" ") " "==" " (" "(frontier.size())" ")", v1, v2
); } while (false)
;
461 ProcessPC(&frontier);
462
463 // The check here is relatively expensive, so we do this in a separate flood
464 // fill. That way we can skip the check for chunks that are reachable
465 // otherwise.
466 LOG_POINTERS("Processing platform-specific allocations.\n")do { if (flags()->log_pointers) Report("Processing platform-specific allocations.\n"
); } while (0)
;
467 ProcessPlatformSpecificAllocations(&frontier);
468 FloodFillTag(&frontier, kReachable);
469
470 // Iterate over leaked chunks and mark those that are reachable from other
471 // leaked chunks.
472 LOG_POINTERS("Scanning leaked chunks.\n")do { if (flags()->log_pointers) Report("Scanning leaked chunks.\n"
); } while (0)
;
473 ForEachChunk(MarkIndirectlyLeakedCb, nullptr);
474}
475
476// ForEachChunk callback. Resets the tags to pre-leak-check state.
477static void ResetTagsCb(uptr chunk, void *arg) {
478 (void)arg;
479 chunk = GetUserBegin(chunk);
480 LsanMetadata m(chunk);
481 if (m.allocated() && m.tag() != kIgnored)
482 m.set_tag(kDirectlyLeaked);
483}
484
485static void PrintStackTraceById(u32 stack_trace_id) {
486 CHECK(stack_trace_id)do { __sanitizer::u64 v1 = (__sanitizer::u64)((stack_trace_id
)); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 486, "(" "(stack_trace_id)" ") " "!=" " (" "0" ")", v1, v2)
; } while (false)
;
487 StackDepotGet(stack_trace_id).Print();
488}
489
490// ForEachChunk callback. Aggregates information about unreachable chunks into
491// a LeakReport.
492static void CollectLeaksCb(uptr chunk, void *arg) {
493 CHECK(arg)do { __sanitizer::u64 v1 = (__sanitizer::u64)((arg)); __sanitizer
::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect(!!(!(v1
!= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 493, "(" "(arg)" ") " "!=" " (" "0" ")", v1, v2); } while (
false)
;
494 LeakReport *leak_report = reinterpret_cast<LeakReport *>(arg);
495 chunk = GetUserBegin(chunk);
496 LsanMetadata m(chunk);
497 if (!m.allocated()) return;
498 if (m.tag() == kDirectlyLeaked || m.tag() == kIndirectlyLeaked) {
499 u32 resolution = flags()->resolution;
500 u32 stack_trace_id = 0;
501 if (resolution > 0) {
502 StackTrace stack = StackDepotGet(m.stack_trace_id());
503 stack.size = Min(stack.size, resolution);
504 stack_trace_id = StackDepotPut(stack);
505 } else {
506 stack_trace_id = m.stack_trace_id();
507 }
508 leak_report->AddLeakedChunk(chunk, stack_trace_id, m.requested_size(),
509 m.tag());
510 }
511}
512
513static void PrintMatchedSuppressions() {
514 InternalMmapVector<Suppression *> matched;
515 GetSuppressionContext()->GetMatched(&matched);
516 if (!matched.size())
517 return;
518 const char *line = "-----------------------------------------------------";
519 Printf("%s\n", line);
520 Printf("Suppressions used:\n");
521 Printf(" count bytes template\n");
522 for (uptr i = 0; i < matched.size(); i++)
523 Printf("%7zu %10zu %s\n", static_cast<uptr>(atomic_load_relaxed(
524 &matched[i]->hit_count)), matched[i]->weight, matched[i]->templ);
525 Printf("%s\n\n", line);
526}
527
528struct CheckForLeaksParam {
529 bool success;
530 LeakReport leak_report;
531};
532
533static void ReportIfNotSuspended(ThreadContextBase *tctx, void *arg) {
534 const InternalMmapVector<tid_t> &suspended_threads =
535 *(const InternalMmapVector<tid_t> *)arg;
536 if (tctx->status == ThreadStatusRunning) {
537 uptr i = InternalLowerBound(suspended_threads, 0, suspended_threads.size(),
538 tctx->os_id, CompareLess<int>());
539 if (i >= suspended_threads.size() || suspended_threads[i] != tctx->os_id)
540 Report("Running thread %d was not suspended. False leaks are possible.\n",
541 tctx->os_id);
542 };
543}
544
545static void ReportUnsuspendedThreads(
546 const SuspendedThreadsList &suspended_threads) {
547 InternalMmapVector<tid_t> threads(suspended_threads.ThreadCount());
548 for (uptr i = 0; i < suspended_threads.ThreadCount(); ++i)
549 threads[i] = suspended_threads.GetThreadID(i);
550
551 Sort(threads.data(), threads.size());
552
553 GetThreadRegistryLocked()->RunCallbackForEachThreadLocked(
554 &ReportIfNotSuspended, &threads);
555}
556
557static void CheckForLeaksCallback(const SuspendedThreadsList &suspended_threads,
558 void *arg) {
559 CheckForLeaksParam *param = reinterpret_cast<CheckForLeaksParam *>(arg);
560 CHECK(param)do { __sanitizer::u64 v1 = (__sanitizer::u64)((param)); __sanitizer
::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect(!!(!(v1
!= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 560, "(" "(param)" ") " "!=" " (" "0" ")", v1, v2); } while
(false)
;
561 CHECK(!param->success)do { __sanitizer::u64 v1 = (__sanitizer::u64)((!param->success
)); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 561, "(" "(!param->success)" ") " "!=" " (" "0" ")", v1,
v2); } while (false)
;
562 ReportUnsuspendedThreads(suspended_threads);
563 ClassifyAllChunks(suspended_threads);
564 ForEachChunk(CollectLeaksCb, &param->leak_report);
565 // Clean up for subsequent leak checks. This assumes we did not overwrite any
566 // kIgnored tags.
567 ForEachChunk(ResetTagsCb, nullptr);
568 param->success = true;
569}
570
571static bool CheckForLeaks() {
572 if (&__lsan_is_turned_off && __lsan_is_turned_off())
573 return false;
574 if (initialized_for_pid != internal_getpid()) {
575 // If process was forked and it had threads we fail to detect references
576 // from other threads.
577 Report("WARNING: LeakSanitizer is disabled in forked process.\n");
578 return false;
579 }
580 EnsureMainThreadIDIsCorrect();
581 CheckForLeaksParam param;
582 param.success = false;
583 LockThreadRegistry();
584 LockAllocator();
585 DoStopTheWorld(CheckForLeaksCallback, &param);
586 UnlockAllocator();
587 UnlockThreadRegistry();
588
589 if (!param.success) {
590 Report("LeakSanitizer has encountered a fatal error.\n");
591 Report(
592 "HINT: For debugging, try setting environment variable "
593 "LSAN_OPTIONS=verbosity=1:log_threads=1\n");
594 Report(
595 "HINT: LeakSanitizer does not work under ptrace (strace, gdb, etc)\n");
596 Die();
597 }
598 param.leak_report.ApplySuppressions();
599 uptr unsuppressed_count = param.leak_report.UnsuppressedLeakCount();
600 if (unsuppressed_count > 0) {
601 Decorator d;
602 Printf("\n"
603 "================================================================="
604 "\n");
605 Printf("%s", d.Error());
606 Report("ERROR: LeakSanitizer: detected memory leaks\n");
607 Printf("%s", d.Default());
608 param.leak_report.ReportTopLeaks(flags()->max_leaks);
609 }
610 if (common_flags()->print_suppressions)
611 PrintMatchedSuppressions();
612 if (unsuppressed_count > 0) {
613 param.leak_report.PrintSummary();
614 return true;
615 }
616 return false;
617}
618
619static bool has_reported_leaks = false;
620bool HasReportedLeaks() { return has_reported_leaks; }
621
622void DoLeakCheck() {
623 BlockingMutexLock l(&global_mutex);
624 static bool already_done;
625 if (already_done) return;
626 already_done = true;
627 has_reported_leaks = CheckForLeaks();
628 if (has_reported_leaks) HandleLeaks();
629}
630
631static int DoRecoverableLeakCheck() {
632 BlockingMutexLock l(&global_mutex);
633 bool have_leaks = CheckForLeaks();
634 return have_leaks ? 1 : 0;
635}
636
637void DoRecoverableLeakCheckVoid() { DoRecoverableLeakCheck(); }
638
639static Suppression *GetSuppressionForAddr(uptr addr) {
640 Suppression *s = nullptr;
641
642 // Suppress by module name.
643 SuppressionContext *suppressions = GetSuppressionContext();
644 if (const char *module_name =
1
Taking false branch
645 Symbolizer::GetOrInit()->GetModuleNameForPc(addr))
646 if (suppressions->Match(module_name, kSuppressionLeak, &s))
647 return s;
648
649 // Suppress by file or function name.
650 SymbolizedStack *frames = Symbolizer::GetOrInit()->SymbolizePC(addr);
2
'frames' initialized here
651 for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
3
Assuming pointer value is null
4
Loop condition is false. Execution continues on line 657
652 if (suppressions->Match(cur->info.function, kSuppressionLeak, &s) ||
653 suppressions->Match(cur->info.file, kSuppressionLeak, &s)) {
654 break;
655 }
656 }
657 frames->ClearAll();
5
Called C++ object pointer is null
658 return s;
659}
660
661static Suppression *GetSuppressionForStack(u32 stack_trace_id) {
662 StackTrace stack = StackDepotGet(stack_trace_id);
663 for (uptr i = 0; i < stack.size; i++) {
664 Suppression *s = GetSuppressionForAddr(
665 StackTrace::GetPreviousInstructionPc(stack.trace[i]));
666 if (s) return s;
667 }
668 return nullptr;
669}
670
671///// LeakReport implementation. /////
672
673// A hard limit on the number of distinct leaks, to avoid quadratic complexity
674// in LeakReport::AddLeakedChunk(). We don't expect to ever see this many leaks
675// in real-world applications.
676// FIXME: Get rid of this limit by changing the implementation of LeakReport to
677// use a hash table.
678const uptr kMaxLeaksConsidered = 5000;
679
680void LeakReport::AddLeakedChunk(uptr chunk, u32 stack_trace_id,
681 uptr leaked_size, ChunkTag tag) {
682 CHECK(tag == kDirectlyLeaked || tag == kIndirectlyLeaked)do { __sanitizer::u64 v1 = (__sanitizer::u64)((tag == kDirectlyLeaked
|| tag == kIndirectlyLeaked)); __sanitizer::u64 v2 = (__sanitizer
::u64)(0); if (__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer
::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 682, "(" "(tag == kDirectlyLeaked || tag == kIndirectlyLeaked)"
") " "!=" " (" "0" ")", v1, v2); } while (false)
;
683 bool is_directly_leaked = (tag == kDirectlyLeaked);
684 uptr i;
685 for (i = 0; i < leaks_.size(); i++) {
686 if (leaks_[i].stack_trace_id == stack_trace_id &&
687 leaks_[i].is_directly_leaked == is_directly_leaked) {
688 leaks_[i].hit_count++;
689 leaks_[i].total_size += leaked_size;
690 break;
691 }
692 }
693 if (i == leaks_.size()) {
694 if (leaks_.size() == kMaxLeaksConsidered) return;
695 Leak leak = { next_id_++, /* hit_count */ 1, leaked_size, stack_trace_id,
696 is_directly_leaked, /* is_suppressed */ false };
697 leaks_.push_back(leak);
698 }
699 if (flags()->report_objects) {
700 LeakedObject obj = {leaks_[i].id, chunk, leaked_size};
701 leaked_objects_.push_back(obj);
702 }
703}
704
705static bool LeakComparator(const Leak &leak1, const Leak &leak2) {
706 if (leak1.is_directly_leaked == leak2.is_directly_leaked)
707 return leak1.total_size > leak2.total_size;
708 else
709 return leak1.is_directly_leaked;
710}
711
712void LeakReport::ReportTopLeaks(uptr num_leaks_to_report) {
713 CHECK(leaks_.size() <= kMaxLeaksConsidered)do { __sanitizer::u64 v1 = (__sanitizer::u64)((leaks_.size() <=
kMaxLeaksConsidered)); __sanitizer::u64 v2 = (__sanitizer::u64
)(0); if (__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer::
CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 713, "(" "(leaks_.size() <= kMaxLeaksConsidered)" ") " "!="
" (" "0" ")", v1, v2); } while (false)
;
714 Printf("\n");
715 if (leaks_.size() == kMaxLeaksConsidered)
716 Printf("Too many leaks! Only the first %zu leaks encountered will be "
717 "reported.\n",
718 kMaxLeaksConsidered);
719
720 uptr unsuppressed_count = UnsuppressedLeakCount();
721 if (num_leaks_to_report > 0 && num_leaks_to_report < unsuppressed_count)
722 Printf("The %zu top leak(s):\n", num_leaks_to_report);
723 Sort(leaks_.data(), leaks_.size(), &LeakComparator);
724 uptr leaks_reported = 0;
725 for (uptr i = 0; i < leaks_.size(); i++) {
726 if (leaks_[i].is_suppressed) continue;
727 PrintReportForLeak(i);
728 leaks_reported++;
729 if (leaks_reported == num_leaks_to_report) break;
730 }
731 if (leaks_reported < unsuppressed_count) {
732 uptr remaining = unsuppressed_count - leaks_reported;
733 Printf("Omitting %zu more leak(s).\n", remaining);
734 }
735}
736
737void LeakReport::PrintReportForLeak(uptr index) {
738 Decorator d;
739 Printf("%s", d.Leak());
740 Printf("%s leak of %zu byte(s) in %zu object(s) allocated from:\n",
741 leaks_[index].is_directly_leaked ? "Direct" : "Indirect",
742 leaks_[index].total_size, leaks_[index].hit_count);
743 Printf("%s", d.Default());
744
745 PrintStackTraceById(leaks_[index].stack_trace_id);
746
747 if (flags()->report_objects) {
748 Printf("Objects leaked above:\n");
749 PrintLeakedObjectsForLeak(index);
750 Printf("\n");
751 }
752}
753
754void LeakReport::PrintLeakedObjectsForLeak(uptr index) {
755 u32 leak_id = leaks_[index].id;
756 for (uptr j = 0; j < leaked_objects_.size(); j++) {
757 if (leaked_objects_[j].leak_id == leak_id)
758 Printf("%p (%zu bytes)\n", leaked_objects_[j].addr,
759 leaked_objects_[j].size);
760 }
761}
762
763void LeakReport::PrintSummary() {
764 CHECK(leaks_.size() <= kMaxLeaksConsidered)do { __sanitizer::u64 v1 = (__sanitizer::u64)((leaks_.size() <=
kMaxLeaksConsidered)); __sanitizer::u64 v2 = (__sanitizer::u64
)(0); if (__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer::
CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 764, "(" "(leaks_.size() <= kMaxLeaksConsidered)" ") " "!="
" (" "0" ")", v1, v2); } while (false)
;
765 uptr bytes = 0, allocations = 0;
766 for (uptr i = 0; i < leaks_.size(); i++) {
767 if (leaks_[i].is_suppressed) continue;
768 bytes += leaks_[i].total_size;
769 allocations += leaks_[i].hit_count;
770 }
771 InternalScopedString summary(kMaxSummaryLength);
772 summary.append("%zu byte(s) leaked in %zu allocation(s).", bytes,
773 allocations);
774 ReportErrorSummary(summary.data());
775}
776
777void LeakReport::ApplySuppressions() {
778 for (uptr i = 0; i < leaks_.size(); i++) {
779 Suppression *s = GetSuppressionForStack(leaks_[i].stack_trace_id);
780 if (s) {
781 s->weight += leaks_[i].total_size;
782 atomic_store_relaxed(&s->hit_count, atomic_load_relaxed(&s->hit_count) +
783 leaks_[i].hit_count);
784 leaks_[i].is_suppressed = true;
785 }
786 }
787}
788
789uptr LeakReport::UnsuppressedLeakCount() {
790 uptr result = 0;
791 for (uptr i = 0; i < leaks_.size(); i++)
792 if (!leaks_[i].is_suppressed) result++;
793 return result;
794}
795
796} // namespace __lsan
797#else // CAN_SANITIZE_LEAKS
798namespace __lsan {
799void InitCommonLsan() { }
800void DoLeakCheck() { }
801void DoRecoverableLeakCheckVoid() { }
802void DisableInThisThread() { }
803void EnableInThisThread() { }
804}
805#endif // CAN_SANITIZE_LEAKS
806
807using namespace __lsan; // NOLINT
808
809extern "C" {
810SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default")))
811void __lsan_ignore_object(const void *p) {
812#if CAN_SANITIZE_LEAKS1
813 if (!common_flags()->detect_leaks)
814 return;
815 // Cannot use PointsIntoChunk or LsanMetadata here, since the allocator is not
816 // locked.
817 BlockingMutexLock l(&global_mutex);
818 IgnoreObjectResult res = IgnoreObjectLocked(p);
819 if (res == kIgnoreObjectInvalid)
820 VReport(1, "__lsan_ignore_object(): no heap object found at %p", p)do { if ((uptr)Verbosity() >= (1)) Report("__lsan_ignore_object(): no heap object found at %p"
, p); } while (0)
;
821 if (res == kIgnoreObjectAlreadyIgnored)
822 VReport(1, "__lsan_ignore_object(): "do { if ((uptr)Verbosity() >= (1)) Report("__lsan_ignore_object(): "
"heap object at %p is already being ignored\n", p); } while (
0)
823 "heap object at %p is already being ignored\n", p)do { if ((uptr)Verbosity() >= (1)) Report("__lsan_ignore_object(): "
"heap object at %p is already being ignored\n", p); } while (
0)
;
824 if (res == kIgnoreObjectSuccess)
825 VReport(1, "__lsan_ignore_object(): ignoring heap object at %p\n", p)do { if ((uptr)Verbosity() >= (1)) Report("__lsan_ignore_object(): ignoring heap object at %p\n"
, p); } while (0)
;
826#endif // CAN_SANITIZE_LEAKS
827}
828
829SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default")))
830void __lsan_register_root_region(const void *begin, uptr size) {
831#if CAN_SANITIZE_LEAKS1
832 BlockingMutexLock l(&global_mutex);
833 CHECK(root_regions)do { __sanitizer::u64 v1 = (__sanitizer::u64)((root_regions))
; __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 833, "(" "(root_regions)" ") " "!=" " (" "0" ")", v1, v2); }
while (false)
;
834 RootRegion region = {reinterpret_cast<uptr>(begin), size};
835 root_regions->push_back(region);
836 VReport(1, "Registered root region at %p of size %llu\n", begin, size)do { if ((uptr)Verbosity() >= (1)) Report("Registered root region at %p of size %llu\n"
, begin, size); } while (0)
;
837#endif // CAN_SANITIZE_LEAKS
838}
839
840SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default")))
841void __lsan_unregister_root_region(const void *begin, uptr size) {
842#if CAN_SANITIZE_LEAKS1
843 BlockingMutexLock l(&global_mutex);
844 CHECK(root_regions)do { __sanitizer::u64 v1 = (__sanitizer::u64)((root_regions))
; __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-7~svn338205/projects/compiler-rt/lib/lsan/lsan_common.cc"
, 844, "(" "(root_regions)" ") " "!=" " (" "0" ")", v1, v2); }
while (false)
;
845 bool removed = false;
846 for (uptr i = 0; i < root_regions->size(); i++) {
847 RootRegion region = (*root_regions)[i];
848 if (region.begin == reinterpret_cast<uptr>(begin) && region.size == size) {
849 removed = true;
850 uptr last_index = root_regions->size() - 1;
851 (*root_regions)[i] = (*root_regions)[last_index];
852 root_regions->pop_back();
853 VReport(1, "Unregistered root region at %p of size %llu\n", begin, size)do { if ((uptr)Verbosity() >= (1)) Report("Unregistered root region at %p of size %llu\n"
, begin, size); } while (0)
;
854 break;
855 }
856 }
857 if (!removed) {
858 Report(
859 "__lsan_unregister_root_region(): region at %p of size %llu has not "
860 "been registered.\n",
861 begin, size);
862 Die();
863 }
864#endif // CAN_SANITIZE_LEAKS
865}
866
867SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default")))
868void __lsan_disable() {
869#if CAN_SANITIZE_LEAKS1
870 __lsan::DisableInThisThread();
871#endif
872}
873
874SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default")))
875void __lsan_enable() {
876#if CAN_SANITIZE_LEAKS1
877 __lsan::EnableInThisThread();
878#endif
879}
880
881SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default")))
882void __lsan_do_leak_check() {
883#if CAN_SANITIZE_LEAKS1
884 if (common_flags()->detect_leaks)
885 __lsan::DoLeakCheck();
886#endif // CAN_SANITIZE_LEAKS
887}
888
889SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default")))
890int __lsan_do_recoverable_leak_check() {
891#if CAN_SANITIZE_LEAKS1
892 if (common_flags()->detect_leaks)
893 return __lsan::DoRecoverableLeakCheck();
894#endif // CAN_SANITIZE_LEAKS
895 return 0;
896}
897
898#if !SANITIZER_SUPPORTS_WEAK_HOOKS1
899SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default"))) SANITIZER_WEAK_ATTRIBUTE__attribute__((weak))
900const char * __lsan_default_options() {
901 return "";
902}
903
904SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default"))) SANITIZER_WEAK_ATTRIBUTE__attribute__((weak))
905int __lsan_is_turned_off() {
906 return 0;
907}
908
909SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default"))) SANITIZER_WEAK_ATTRIBUTE__attribute__((weak))
910const char *__lsan_default_suppressions() {
911 return "";
912}
913#endif
914} // extern "C"