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