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