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