]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/lsan/lsan_common.cc
Import compiler-rt trunk r228651.
[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_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_stoptheworld.h"
25 #include "sanitizer_common/sanitizer_suppressions.h"
26 #include "sanitizer_common/sanitizer_report_decorator.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 THREADLOCAL int disable_counter;
36 bool DisabledInThisThread() { return disable_counter > 0; }
37
38 Flags lsan_flags;
39
40 void Flags::SetDefaults() {
41 #define LSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
42 #include "lsan_flags.inc"
43 #undef LSAN_FLAG
44 }
45
46 static void RegisterLsanFlags(FlagParser *parser, Flags *f) {
47 #define LSAN_FLAG(Type, Name, DefaultValue, Description) \
48   RegisterFlag(parser, #Name, Description, &f->Name);
49 #include "lsan_flags.inc"
50 #undef LSAN_FLAG
51 }
52
53 static void InitializeFlags(bool standalone) {
54   Flags *f = flags();
55   FlagParser parser;
56   RegisterLsanFlags(&parser, f);
57   RegisterCommonFlags(&parser);
58
59   f->SetDefaults();
60
61   // Set defaults for common flags (only in standalone mode) and parse
62   // them from LSAN_OPTIONS.
63   if (standalone) {
64     SetCommonFlagsDefaults();
65     CommonFlags cf;
66     cf.CopyFrom(*common_flags());
67     cf.external_symbolizer_path = GetEnv("LSAN_SYMBOLIZER_PATH");
68     cf.malloc_context_size = 30;
69     cf.detect_leaks = true;
70     OverrideCommonFlags(cf);
71   }
72
73   bool help_before = common_flags()->help;
74
75   const char *options = GetEnv("LSAN_OPTIONS");
76   parser.ParseString(options);
77
78   SetVerbosity(common_flags()->verbosity);
79
80   if (Verbosity()) ReportUnrecognizedFlags();
81
82   if (!help_before && common_flags()->help)
83     parser.PrintFlagDescriptions();
84 }
85
86 #define LOG_POINTERS(...)                           \
87   do {                                              \
88     if (flags()->log_pointers) Report(__VA_ARGS__); \
89   } while (0);
90
91 #define LOG_THREADS(...)                           \
92   do {                                             \
93     if (flags()->log_threads) Report(__VA_ARGS__); \
94   } while (0);
95
96 static bool suppressions_inited = false;
97
98 void InitializeSuppressions() {
99   CHECK(!suppressions_inited);
100   SuppressionContext::InitIfNecessary();
101   if (&__lsan_default_suppressions)
102     SuppressionContext::Get()->Parse(__lsan_default_suppressions());
103   suppressions_inited = true;
104 }
105
106 struct RootRegion {
107   const void *begin;
108   uptr size;
109 };
110
111 InternalMmapVector<RootRegion> *root_regions;
112
113 void InitializeRootRegions() {
114   CHECK(!root_regions);
115   ALIGNED(64) static char placeholder[sizeof(InternalMmapVector<RootRegion>)];
116   root_regions = new(placeholder) InternalMmapVector<RootRegion>(1);
117 }
118
119 void InitCommonLsan(bool standalone) {
120   InitializeFlags(standalone);
121   InitializeRootRegions();
122   if (common_flags()->detect_leaks) {
123     // Initialization which can fail or print warnings should only be done if
124     // LSan is actually enabled.
125     InitializeSuppressions();
126     InitializePlatformSpecificModules();
127   }
128 }
129
130 class Decorator: public __sanitizer::SanitizerCommonDecorator {
131  public:
132   Decorator() : SanitizerCommonDecorator() { }
133   const char *Error() { return Red(); }
134   const char *Leak() { return Blue(); }
135   const char *End() { return Default(); }
136 };
137
138 static inline bool CanBeAHeapPointer(uptr p) {
139   // Since our heap is located in mmap-ed memory, we can assume a sensible lower
140   // bound on heap addresses.
141   const uptr kMinAddress = 4 * 4096;
142   if (p < kMinAddress) return false;
143 #ifdef __x86_64__
144   // Accept only canonical form user-space addresses.
145   return ((p >> 47) == 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 or ignored
154 // chunks (|tag| = kReachable or kIgnored) 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   const uptr alignment = flags()->pointer_alignment();
161   LOG_POINTERS("Scanning %s range %p-%p.\n", region_type, begin, end);
162   uptr pp = begin;
163   if (pp % alignment)
164     pp = pp + alignment - pp % alignment;
165   for (; pp + sizeof(void *) <= end; pp += alignment) {  // NOLINT
166     void *p = *reinterpret_cast<void **>(pp);
167     if (!CanBeAHeapPointer(reinterpret_cast<uptr>(p))) continue;
168     uptr chunk = PointsIntoChunk(p);
169     if (!chunk) continue;
170     // Pointers to self don't count. This matters when tag == kIndirectlyLeaked.
171     if (chunk == begin) continue;
172     LsanMetadata m(chunk);
173     // Reachable beats ignored beats leaked.
174     if (m.tag() == kReachable) continue;
175     if (m.tag() == kIgnored && tag != kReachable) continue;
176
177     // Do this check relatively late so we can log only the interesting cases.
178     if (!flags()->use_poisoned && WordIsPoisoned(pp)) {
179       LOG_POINTERS(
180           "%p is poisoned: ignoring %p pointing into chunk %p-%p of size "
181           "%zu.\n",
182           pp, p, chunk, chunk + m.requested_size(), m.requested_size());
183       continue;
184     }
185
186     m.set_tag(tag);
187     LOG_POINTERS("%p: found %p pointing into chunk %p-%p of size %zu.\n", pp, p,
188                  chunk, chunk + m.requested_size(), m.requested_size());
189     if (frontier)
190       frontier->push_back(chunk);
191   }
192 }
193
194 void ForEachExtraStackRangeCb(uptr begin, uptr end, void* arg) {
195   Frontier *frontier = reinterpret_cast<Frontier *>(arg);
196   ScanRangeForPointers(begin, end, frontier, "FAKE STACK", kReachable);
197 }
198
199 // Scans thread data (stacks and TLS) for heap pointers.
200 static void ProcessThreads(SuspendedThreadsList const &suspended_threads,
201                            Frontier *frontier) {
202   InternalScopedBuffer<uptr> registers(SuspendedThreadsList::RegisterCount());
203   uptr registers_begin = reinterpret_cast<uptr>(registers.data());
204   uptr registers_end = registers_begin + registers.size();
205   for (uptr i = 0; i < suspended_threads.thread_count(); i++) {
206     uptr os_id = static_cast<uptr>(suspended_threads.GetThreadID(i));
207     LOG_THREADS("Processing thread %d.\n", os_id);
208     uptr stack_begin, stack_end, tls_begin, tls_end, cache_begin, cache_end;
209     bool thread_found = GetThreadRangesLocked(os_id, &stack_begin, &stack_end,
210                                               &tls_begin, &tls_end,
211                                               &cache_begin, &cache_end);
212     if (!thread_found) {
213       // If a thread can't be found in the thread registry, it's probably in the
214       // process of destruction. Log this event and move on.
215       LOG_THREADS("Thread %d not found in registry.\n", os_id);
216       continue;
217     }
218     uptr sp;
219     bool have_registers =
220         (suspended_threads.GetRegistersAndSP(i, registers.data(), &sp) == 0);
221     if (!have_registers) {
222       Report("Unable to get registers from thread %d.\n");
223       // If unable to get SP, consider the entire stack to be reachable.
224       sp = stack_begin;
225     }
226
227     if (flags()->use_registers && have_registers)
228       ScanRangeForPointers(registers_begin, registers_end, frontier,
229                            "REGISTERS", kReachable);
230
231     if (flags()->use_stacks) {
232       LOG_THREADS("Stack at %p-%p (SP = %p).\n", stack_begin, stack_end, sp);
233       if (sp < stack_begin || sp >= stack_end) {
234         // SP is outside the recorded stack range (e.g. the thread is running a
235         // signal handler on alternate stack). Again, consider the entire stack
236         // range to be reachable.
237         LOG_THREADS("WARNING: stack pointer not in stack range.\n");
238       } else {
239         // Shrink the stack range to ignore out-of-scope values.
240         stack_begin = sp;
241       }
242       ScanRangeForPointers(stack_begin, stack_end, frontier, "STACK",
243                            kReachable);
244       ForEachExtraStackRange(os_id, ForEachExtraStackRangeCb, frontier);
245     }
246
247     if (flags()->use_tls) {
248       LOG_THREADS("TLS at %p-%p.\n", tls_begin, tls_end);
249       if (cache_begin == cache_end) {
250         ScanRangeForPointers(tls_begin, tls_end, frontier, "TLS", kReachable);
251       } else {
252         // Because LSan should not be loaded with dlopen(), we can assume
253         // that allocator cache will be part of static TLS image.
254         CHECK_LE(tls_begin, cache_begin);
255         CHECK_GE(tls_end, cache_end);
256         if (tls_begin < cache_begin)
257           ScanRangeForPointers(tls_begin, cache_begin, frontier, "TLS",
258                                kReachable);
259         if (tls_end > cache_end)
260           ScanRangeForPointers(cache_end, tls_end, frontier, "TLS", kReachable);
261       }
262     }
263   }
264 }
265
266 static void ProcessRootRegion(Frontier *frontier, uptr root_begin,
267                               uptr root_end) {
268   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
269   uptr begin, end, prot;
270   while (proc_maps.Next(&begin, &end,
271                         /*offset*/ 0, /*filename*/ 0, /*filename_size*/ 0,
272                         &prot)) {
273     uptr intersection_begin = Max(root_begin, begin);
274     uptr intersection_end = Min(end, root_end);
275     if (intersection_begin >= intersection_end) continue;
276     bool is_readable = prot & MemoryMappingLayout::kProtectionRead;
277     LOG_POINTERS("Root region %p-%p intersects with mapped region %p-%p (%s)\n",
278                  root_begin, root_end, begin, end,
279                  is_readable ? "readable" : "unreadable");
280     if (is_readable)
281       ScanRangeForPointers(intersection_begin, intersection_end, frontier,
282                            "ROOT", kReachable);
283   }
284 }
285
286 // Scans root regions for heap pointers.
287 static void ProcessRootRegions(Frontier *frontier) {
288   if (!flags()->use_root_regions) return;
289   CHECK(root_regions);
290   for (uptr i = 0; i < root_regions->size(); i++) {
291     RootRegion region = (*root_regions)[i];
292     uptr begin_addr = reinterpret_cast<uptr>(region.begin);
293     ProcessRootRegion(frontier, begin_addr, begin_addr + region.size);
294   }
295 }
296
297 static void FloodFillTag(Frontier *frontier, ChunkTag tag) {
298   while (frontier->size()) {
299     uptr next_chunk = frontier->back();
300     frontier->pop_back();
301     LsanMetadata m(next_chunk);
302     ScanRangeForPointers(next_chunk, next_chunk + m.requested_size(), frontier,
303                          "HEAP", tag);
304   }
305 }
306
307 // ForEachChunk callback. If the chunk is marked as leaked, marks all chunks
308 // which are reachable from it as indirectly leaked.
309 static void MarkIndirectlyLeakedCb(uptr chunk, void *arg) {
310   chunk = GetUserBegin(chunk);
311   LsanMetadata m(chunk);
312   if (m.allocated() && m.tag() != kReachable) {
313     ScanRangeForPointers(chunk, chunk + m.requested_size(),
314                          /* frontier */ 0, "HEAP", kIndirectlyLeaked);
315   }
316 }
317
318 // ForEachChunk callback. If chunk is marked as ignored, adds its address to
319 // frontier.
320 static void CollectIgnoredCb(uptr chunk, void *arg) {
321   CHECK(arg);
322   chunk = GetUserBegin(chunk);
323   LsanMetadata m(chunk);
324   if (m.allocated() && m.tag() == kIgnored)
325     reinterpret_cast<Frontier *>(arg)->push_back(chunk);
326 }
327
328 // Sets the appropriate tag on each chunk.
329 static void ClassifyAllChunks(SuspendedThreadsList const &suspended_threads) {
330   // Holds the flood fill frontier.
331   Frontier frontier(1);
332
333   ProcessGlobalRegions(&frontier);
334   ProcessThreads(suspended_threads, &frontier);
335   ProcessRootRegions(&frontier);
336   FloodFillTag(&frontier, kReachable);
337   // The check here is relatively expensive, so we do this in a separate flood
338   // fill. That way we can skip the check for chunks that are reachable
339   // otherwise.
340   LOG_POINTERS("Processing platform-specific allocations.\n");
341   ProcessPlatformSpecificAllocations(&frontier);
342   FloodFillTag(&frontier, kReachable);
343
344   LOG_POINTERS("Scanning ignored chunks.\n");
345   CHECK_EQ(0, frontier.size());
346   ForEachChunk(CollectIgnoredCb, &frontier);
347   FloodFillTag(&frontier, kIgnored);
348
349   // Iterate over leaked chunks and mark those that are reachable from other
350   // leaked chunks.
351   LOG_POINTERS("Scanning leaked chunks.\n");
352   ForEachChunk(MarkIndirectlyLeakedCb, 0 /* arg */);
353 }
354
355 static void PrintStackTraceById(u32 stack_trace_id) {
356   CHECK(stack_trace_id);
357   StackDepotGet(stack_trace_id).Print();
358 }
359
360 // ForEachChunk callback. Aggregates information about unreachable chunks into
361 // a LeakReport.
362 static void CollectLeaksCb(uptr chunk, void *arg) {
363   CHECK(arg);
364   LeakReport *leak_report = reinterpret_cast<LeakReport *>(arg);
365   chunk = GetUserBegin(chunk);
366   LsanMetadata m(chunk);
367   if (!m.allocated()) return;
368   if (m.tag() == kDirectlyLeaked || m.tag() == kIndirectlyLeaked) {
369     u32 resolution = flags()->resolution;
370     u32 stack_trace_id = 0;
371     if (resolution > 0) {
372       StackTrace stack = StackDepotGet(m.stack_trace_id());
373       stack.size = Min(stack.size, resolution);
374       stack_trace_id = StackDepotPut(stack);
375     } else {
376       stack_trace_id = m.stack_trace_id();
377     }
378     leak_report->AddLeakedChunk(chunk, stack_trace_id, m.requested_size(),
379                                 m.tag());
380   }
381 }
382
383 static void PrintMatchedSuppressions() {
384   InternalMmapVector<Suppression *> matched(1);
385   SuppressionContext::Get()->GetMatched(&matched);
386   if (!matched.size())
387     return;
388   const char *line = "-----------------------------------------------------";
389   Printf("%s\n", line);
390   Printf("Suppressions used:\n");
391   Printf("  count      bytes template\n");
392   for (uptr i = 0; i < matched.size(); i++)
393     Printf("%7zu %10zu %s\n", static_cast<uptr>(matched[i]->hit_count),
394            matched[i]->weight, matched[i]->templ);
395   Printf("%s\n\n", line);
396 }
397
398 struct DoLeakCheckParam {
399   bool success;
400   LeakReport leak_report;
401 };
402
403 static void DoLeakCheckCallback(const SuspendedThreadsList &suspended_threads,
404                                 void *arg) {
405   DoLeakCheckParam *param = reinterpret_cast<DoLeakCheckParam *>(arg);
406   CHECK(param);
407   CHECK(!param->success);
408   ClassifyAllChunks(suspended_threads);
409   ForEachChunk(CollectLeaksCb, &param->leak_report);
410   param->success = true;
411 }
412
413 void DoLeakCheck() {
414   EnsureMainThreadIDIsCorrect();
415   BlockingMutexLock l(&global_mutex);
416   static bool already_done;
417   if (already_done) return;
418   already_done = true;
419   if (&__lsan_is_turned_off && __lsan_is_turned_off())
420       return;
421
422   DoLeakCheckParam param;
423   param.success = false;
424   LockThreadRegistry();
425   LockAllocator();
426   StopTheWorld(DoLeakCheckCallback, &param);
427   UnlockAllocator();
428   UnlockThreadRegistry();
429
430   if (!param.success) {
431     Report("LeakSanitizer has encountered a fatal error.\n");
432     Die();
433   }
434   param.leak_report.ApplySuppressions();
435   uptr unsuppressed_count = param.leak_report.UnsuppressedLeakCount();
436   if (unsuppressed_count > 0) {
437     Decorator d;
438     Printf("\n"
439            "================================================================="
440            "\n");
441     Printf("%s", d.Error());
442     Report("ERROR: LeakSanitizer: detected memory leaks\n");
443     Printf("%s", d.End());
444     param.leak_report.ReportTopLeaks(flags()->max_leaks);
445   }
446   if (common_flags()->print_suppressions)
447     PrintMatchedSuppressions();
448   if (unsuppressed_count > 0) {
449     param.leak_report.PrintSummary();
450     if (flags()->exitcode) {
451       if (common_flags()->coverage)
452         __sanitizer_cov_dump();
453       internal__exit(flags()->exitcode);
454     }
455   }
456 }
457
458 static Suppression *GetSuppressionForAddr(uptr addr) {
459   Suppression *s = nullptr;
460
461   // Suppress by module name.
462   const char *module_name;
463   uptr module_offset;
464   if (Symbolizer::GetOrInit()->GetModuleNameAndOffsetForPC(addr, &module_name,
465                                                            &module_offset) &&
466       SuppressionContext::Get()->Match(module_name, SuppressionLeak, &s))
467     return s;
468
469   // Suppress by file or function name.
470   SymbolizedStack *frames = Symbolizer::GetOrInit()->SymbolizePC(addr);
471   for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
472     if (SuppressionContext::Get()->Match(cur->info.function, SuppressionLeak,
473                                          &s) ||
474         SuppressionContext::Get()->Match(cur->info.file, SuppressionLeak, &s)) {
475       break;
476     }
477   }
478   frames->ClearAll();
479   return s;
480 }
481
482 static Suppression *GetSuppressionForStack(u32 stack_trace_id) {
483   StackTrace stack = StackDepotGet(stack_trace_id);
484   for (uptr i = 0; i < stack.size; i++) {
485     Suppression *s = GetSuppressionForAddr(
486         StackTrace::GetPreviousInstructionPc(stack.trace[i]));
487     if (s) return s;
488   }
489   return 0;
490 }
491
492 ///// LeakReport implementation. /////
493
494 // A hard limit on the number of distinct leaks, to avoid quadratic complexity
495 // in LeakReport::AddLeakedChunk(). We don't expect to ever see this many leaks
496 // in real-world applications.
497 // FIXME: Get rid of this limit by changing the implementation of LeakReport to
498 // use a hash table.
499 const uptr kMaxLeaksConsidered = 5000;
500
501 void LeakReport::AddLeakedChunk(uptr chunk, u32 stack_trace_id,
502                                 uptr leaked_size, ChunkTag tag) {
503   CHECK(tag == kDirectlyLeaked || tag == kIndirectlyLeaked);
504   bool is_directly_leaked = (tag == kDirectlyLeaked);
505   uptr i;
506   for (i = 0; i < leaks_.size(); i++) {
507     if (leaks_[i].stack_trace_id == stack_trace_id &&
508         leaks_[i].is_directly_leaked == is_directly_leaked) {
509       leaks_[i].hit_count++;
510       leaks_[i].total_size += leaked_size;
511       break;
512     }
513   }
514   if (i == leaks_.size()) {
515     if (leaks_.size() == kMaxLeaksConsidered) return;
516     Leak leak = { next_id_++, /* hit_count */ 1, leaked_size, stack_trace_id,
517                   is_directly_leaked, /* is_suppressed */ false };
518     leaks_.push_back(leak);
519   }
520   if (flags()->report_objects) {
521     LeakedObject obj = {leaks_[i].id, chunk, leaked_size};
522     leaked_objects_.push_back(obj);
523   }
524 }
525
526 static bool LeakComparator(const Leak &leak1, const Leak &leak2) {
527   if (leak1.is_directly_leaked == leak2.is_directly_leaked)
528     return leak1.total_size > leak2.total_size;
529   else
530     return leak1.is_directly_leaked;
531 }
532
533 void LeakReport::ReportTopLeaks(uptr num_leaks_to_report) {
534   CHECK(leaks_.size() <= kMaxLeaksConsidered);
535   Printf("\n");
536   if (leaks_.size() == kMaxLeaksConsidered)
537     Printf("Too many leaks! Only the first %zu leaks encountered will be "
538            "reported.\n",
539            kMaxLeaksConsidered);
540
541   uptr unsuppressed_count = UnsuppressedLeakCount();
542   if (num_leaks_to_report > 0 && num_leaks_to_report < unsuppressed_count)
543     Printf("The %zu top leak(s):\n", num_leaks_to_report);
544   InternalSort(&leaks_, leaks_.size(), LeakComparator);
545   uptr leaks_reported = 0;
546   for (uptr i = 0; i < leaks_.size(); i++) {
547     if (leaks_[i].is_suppressed) continue;
548     PrintReportForLeak(i);
549     leaks_reported++;
550     if (leaks_reported == num_leaks_to_report) break;
551   }
552   if (leaks_reported < unsuppressed_count) {
553     uptr remaining = unsuppressed_count - leaks_reported;
554     Printf("Omitting %zu more leak(s).\n", remaining);
555   }
556 }
557
558 void LeakReport::PrintReportForLeak(uptr index) {
559   Decorator d;
560   Printf("%s", d.Leak());
561   Printf("%s leak of %zu byte(s) in %zu object(s) allocated from:\n",
562          leaks_[index].is_directly_leaked ? "Direct" : "Indirect",
563          leaks_[index].total_size, leaks_[index].hit_count);
564   Printf("%s", d.End());
565
566   PrintStackTraceById(leaks_[index].stack_trace_id);
567
568   if (flags()->report_objects) {
569     Printf("Objects leaked above:\n");
570     PrintLeakedObjectsForLeak(index);
571     Printf("\n");
572   }
573 }
574
575 void LeakReport::PrintLeakedObjectsForLeak(uptr index) {
576   u32 leak_id = leaks_[index].id;
577   for (uptr j = 0; j < leaked_objects_.size(); j++) {
578     if (leaked_objects_[j].leak_id == leak_id)
579       Printf("%p (%zu bytes)\n", leaked_objects_[j].addr,
580              leaked_objects_[j].size);
581   }
582 }
583
584 void LeakReport::PrintSummary() {
585   CHECK(leaks_.size() <= kMaxLeaksConsidered);
586   uptr bytes = 0, allocations = 0;
587   for (uptr i = 0; i < leaks_.size(); i++) {
588       if (leaks_[i].is_suppressed) continue;
589       bytes += leaks_[i].total_size;
590       allocations += leaks_[i].hit_count;
591   }
592   InternalScopedString summary(kMaxSummaryLength);
593   summary.append("%zu byte(s) leaked in %zu allocation(s).", bytes,
594                  allocations);
595   ReportErrorSummary(summary.data());
596 }
597
598 void LeakReport::ApplySuppressions() {
599   for (uptr i = 0; i < leaks_.size(); i++) {
600     Suppression *s = GetSuppressionForStack(leaks_[i].stack_trace_id);
601     if (s) {
602       s->weight += leaks_[i].total_size;
603       s->hit_count += leaks_[i].hit_count;
604       leaks_[i].is_suppressed = true;
605     }
606   }
607 }
608
609 uptr LeakReport::UnsuppressedLeakCount() {
610   uptr result = 0;
611   for (uptr i = 0; i < leaks_.size(); i++)
612     if (!leaks_[i].is_suppressed) result++;
613   return result;
614 }
615
616 }  // namespace __lsan
617 #endif  // CAN_SANITIZE_LEAKS
618
619 using namespace __lsan;  // NOLINT
620
621 extern "C" {
622 SANITIZER_INTERFACE_ATTRIBUTE
623 void __lsan_ignore_object(const void *p) {
624 #if CAN_SANITIZE_LEAKS
625   if (!common_flags()->detect_leaks)
626     return;
627   // Cannot use PointsIntoChunk or LsanMetadata here, since the allocator is not
628   // locked.
629   BlockingMutexLock l(&global_mutex);
630   IgnoreObjectResult res = IgnoreObjectLocked(p);
631   if (res == kIgnoreObjectInvalid)
632     VReport(1, "__lsan_ignore_object(): no heap object found at %p", p);
633   if (res == kIgnoreObjectAlreadyIgnored)
634     VReport(1, "__lsan_ignore_object(): "
635            "heap object at %p is already being ignored\n", p);
636   if (res == kIgnoreObjectSuccess)
637     VReport(1, "__lsan_ignore_object(): ignoring heap object at %p\n", p);
638 #endif  // CAN_SANITIZE_LEAKS
639 }
640
641 SANITIZER_INTERFACE_ATTRIBUTE
642 void __lsan_register_root_region(const void *begin, uptr size) {
643 #if CAN_SANITIZE_LEAKS
644   BlockingMutexLock l(&global_mutex);
645   CHECK(root_regions);
646   RootRegion region = {begin, size};
647   root_regions->push_back(region);
648   VReport(1, "Registered root region at %p of size %llu\n", begin, size);
649 #endif  // CAN_SANITIZE_LEAKS
650 }
651
652 SANITIZER_INTERFACE_ATTRIBUTE
653 void __lsan_unregister_root_region(const void *begin, uptr size) {
654 #if CAN_SANITIZE_LEAKS
655   BlockingMutexLock l(&global_mutex);
656   CHECK(root_regions);
657   bool removed = false;
658   for (uptr i = 0; i < root_regions->size(); i++) {
659     RootRegion region = (*root_regions)[i];
660     if (region.begin == begin && region.size == size) {
661       removed = true;
662       uptr last_index = root_regions->size() - 1;
663       (*root_regions)[i] = (*root_regions)[last_index];
664       root_regions->pop_back();
665       VReport(1, "Unregistered root region at %p of size %llu\n", begin, size);
666       break;
667     }
668   }
669   if (!removed) {
670     Report(
671         "__lsan_unregister_root_region(): region at %p of size %llu has not "
672         "been registered.\n",
673         begin, size);
674     Die();
675   }
676 #endif  // CAN_SANITIZE_LEAKS
677 }
678
679 SANITIZER_INTERFACE_ATTRIBUTE
680 void __lsan_disable() {
681 #if CAN_SANITIZE_LEAKS
682   __lsan::disable_counter++;
683 #endif
684 }
685
686 SANITIZER_INTERFACE_ATTRIBUTE
687 void __lsan_enable() {
688 #if CAN_SANITIZE_LEAKS
689   if (!__lsan::disable_counter && common_flags()->detect_leaks) {
690     Report("Unmatched call to __lsan_enable().\n");
691     Die();
692   }
693   __lsan::disable_counter--;
694 #endif
695 }
696
697 SANITIZER_INTERFACE_ATTRIBUTE
698 void __lsan_do_leak_check() {
699 #if CAN_SANITIZE_LEAKS
700   if (common_flags()->detect_leaks)
701     __lsan::DoLeakCheck();
702 #endif  // CAN_SANITIZE_LEAKS
703 }
704
705 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
706 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
707 int __lsan_is_turned_off() {
708   return 0;
709 }
710 #endif
711 }  // extern "C"