xref: /freebsd-src/contrib/llvm-project/compiler-rt/lib/lsan/lsan_common.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
168d75effSDimitry Andric //=-- lsan_common.cpp -----------------------------------------------------===//
268d75effSDimitry Andric //
368d75effSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
468d75effSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
568d75effSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
668d75effSDimitry Andric //
768d75effSDimitry Andric //===----------------------------------------------------------------------===//
868d75effSDimitry Andric //
968d75effSDimitry Andric // This file is a part of LeakSanitizer.
1068d75effSDimitry Andric // Implementation of common leak checking functionality.
1168d75effSDimitry Andric //
1268d75effSDimitry Andric //===----------------------------------------------------------------------===//
1368d75effSDimitry Andric 
1468d75effSDimitry Andric #include "lsan_common.h"
1568d75effSDimitry Andric 
1668d75effSDimitry Andric #include "sanitizer_common/sanitizer_common.h"
1768d75effSDimitry Andric #include "sanitizer_common/sanitizer_flag_parser.h"
1868d75effSDimitry Andric #include "sanitizer_common/sanitizer_flags.h"
1968d75effSDimitry Andric #include "sanitizer_common/sanitizer_placement_new.h"
2068d75effSDimitry Andric #include "sanitizer_common/sanitizer_procmaps.h"
2168d75effSDimitry Andric #include "sanitizer_common/sanitizer_report_decorator.h"
2268d75effSDimitry Andric #include "sanitizer_common/sanitizer_stackdepot.h"
2368d75effSDimitry Andric #include "sanitizer_common/sanitizer_stacktrace.h"
2468d75effSDimitry Andric #include "sanitizer_common/sanitizer_suppressions.h"
2568d75effSDimitry Andric #include "sanitizer_common/sanitizer_thread_registry.h"
2668d75effSDimitry Andric #include "sanitizer_common/sanitizer_tls_get_addr.h"
2768d75effSDimitry Andric 
2868d75effSDimitry Andric #if CAN_SANITIZE_LEAKS
29bdd1243dSDimitry Andric 
30bdd1243dSDimitry Andric #  if SANITIZER_APPLE
31bdd1243dSDimitry Andric // https://github.com/apple-oss-distributions/objc4/blob/8701d5672d3fd3cd817aeb84db1077aafe1a1604/runtime/objc-runtime-new.h#L127
32bdd1243dSDimitry Andric #    if SANITIZER_IOS && !SANITIZER_IOSSIM
33bdd1243dSDimitry Andric #      define OBJC_DATA_MASK 0x0000007ffffffff8UL
34bdd1243dSDimitry Andric #    else
35bdd1243dSDimitry Andric #      define OBJC_DATA_MASK 0x00007ffffffffff8UL
36bdd1243dSDimitry Andric #    endif
37bdd1243dSDimitry Andric #  endif
38bdd1243dSDimitry Andric 
3968d75effSDimitry Andric namespace __lsan {
4068d75effSDimitry Andric 
4168d75effSDimitry Andric // This mutex is used to prevent races between DoLeakCheck and IgnoreObject, and
4268d75effSDimitry Andric // also to protect the global list of root regions.
43*06c3fb27SDimitry Andric static Mutex global_mutex;
4468d75effSDimitry Andric 
4568d75effSDimitry Andric Flags lsan_flags;
4668d75effSDimitry Andric 
4768d75effSDimitry Andric void DisableCounterUnderflow() {
4868d75effSDimitry Andric   if (common_flags()->detect_leaks) {
4968d75effSDimitry Andric     Report("Unmatched call to __lsan_enable().\n");
5068d75effSDimitry Andric     Die();
5168d75effSDimitry Andric   }
5268d75effSDimitry Andric }
5368d75effSDimitry Andric 
5468d75effSDimitry Andric void Flags::SetDefaults() {
5568d75effSDimitry Andric #  define LSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
5668d75effSDimitry Andric #  include "lsan_flags.inc"
5768d75effSDimitry Andric #  undef LSAN_FLAG
5868d75effSDimitry Andric }
5968d75effSDimitry Andric 
6068d75effSDimitry Andric void RegisterLsanFlags(FlagParser *parser, Flags *f) {
6168d75effSDimitry Andric #  define LSAN_FLAG(Type, Name, DefaultValue, Description) \
6268d75effSDimitry Andric     RegisterFlag(parser, #Name, Description, &f->Name);
6368d75effSDimitry Andric #  include "lsan_flags.inc"
6468d75effSDimitry Andric #  undef LSAN_FLAG
6568d75effSDimitry Andric }
6668d75effSDimitry Andric 
6768d75effSDimitry Andric #  define LOG_POINTERS(...)      \
6868d75effSDimitry Andric     do {                         \
690eae32dcSDimitry Andric       if (flags()->log_pointers) \
700eae32dcSDimitry Andric         Report(__VA_ARGS__);     \
7168d75effSDimitry Andric     } while (0)
7268d75effSDimitry Andric 
7368d75effSDimitry Andric #  define LOG_THREADS(...)      \
7468d75effSDimitry Andric     do {                        \
750eae32dcSDimitry Andric       if (flags()->log_threads) \
760eae32dcSDimitry Andric         Report(__VA_ARGS__);    \
7768d75effSDimitry Andric     } while (0)
7868d75effSDimitry Andric 
79e8d8bef9SDimitry Andric class LeakSuppressionContext {
80e8d8bef9SDimitry Andric   bool parsed = false;
81e8d8bef9SDimitry Andric   SuppressionContext context;
82e8d8bef9SDimitry Andric   bool suppressed_stacks_sorted = true;
83e8d8bef9SDimitry Andric   InternalMmapVector<u32> suppressed_stacks;
840eae32dcSDimitry Andric   const LoadedModule *suppress_module = nullptr;
85e8d8bef9SDimitry Andric 
86e8d8bef9SDimitry Andric   void LazyInit();
870eae32dcSDimitry Andric   Suppression *GetSuppressionForAddr(uptr addr);
880eae32dcSDimitry Andric   bool SuppressInvalid(const StackTrace &stack);
890eae32dcSDimitry Andric   bool SuppressByRule(const StackTrace &stack, uptr hit_count, uptr total_size);
90e8d8bef9SDimitry Andric 
91e8d8bef9SDimitry Andric  public:
92e8d8bef9SDimitry Andric   LeakSuppressionContext(const char *supprression_types[],
93e8d8bef9SDimitry Andric                          int suppression_types_num)
94e8d8bef9SDimitry Andric       : context(supprression_types, suppression_types_num) {}
95e8d8bef9SDimitry Andric 
960eae32dcSDimitry Andric   bool Suppress(u32 stack_trace_id, uptr hit_count, uptr total_size);
97e8d8bef9SDimitry Andric 
98e8d8bef9SDimitry Andric   const InternalMmapVector<u32> &GetSortedSuppressedStacks() {
99e8d8bef9SDimitry Andric     if (!suppressed_stacks_sorted) {
100e8d8bef9SDimitry Andric       suppressed_stacks_sorted = true;
101e8d8bef9SDimitry Andric       SortAndDedup(suppressed_stacks);
102e8d8bef9SDimitry Andric     }
103e8d8bef9SDimitry Andric     return suppressed_stacks;
104e8d8bef9SDimitry Andric   }
105e8d8bef9SDimitry Andric   void PrintMatchedSuppressions();
106e8d8bef9SDimitry Andric };
107e8d8bef9SDimitry Andric 
108e8d8bef9SDimitry Andric ALIGNED(64) static char suppression_placeholder[sizeof(LeakSuppressionContext)];
109e8d8bef9SDimitry Andric static LeakSuppressionContext *suppression_ctx = nullptr;
11068d75effSDimitry Andric static const char kSuppressionLeak[] = "leak";
11168d75effSDimitry Andric static const char *kSuppressionTypes[] = {kSuppressionLeak};
11268d75effSDimitry Andric static const char kStdSuppressions[] =
11368d75effSDimitry Andric #  if SANITIZER_SUPPRESS_LEAK_ON_PTHREAD_EXIT
11468d75effSDimitry Andric     // For more details refer to the SANITIZER_SUPPRESS_LEAK_ON_PTHREAD_EXIT
11568d75effSDimitry Andric     // definition.
11668d75effSDimitry Andric     "leak:*pthread_exit*\n"
11768d75effSDimitry Andric #  endif  // SANITIZER_SUPPRESS_LEAK_ON_PTHREAD_EXIT
11881ad6265SDimitry Andric #  if SANITIZER_APPLE
11968d75effSDimitry Andric     // For Darwin and os_log/os_trace: https://reviews.llvm.org/D35173
12068d75effSDimitry Andric     "leak:*_os_trace*\n"
12168d75effSDimitry Andric #  endif
12268d75effSDimitry Andric     // TLS leak in some glibc versions, described in
12368d75effSDimitry Andric     // https://sourceware.org/bugzilla/show_bug.cgi?id=12650.
12468d75effSDimitry Andric     "leak:*tls_get_addr*\n";
12568d75effSDimitry Andric 
12668d75effSDimitry Andric void InitializeSuppressions() {
12768d75effSDimitry Andric   CHECK_EQ(nullptr, suppression_ctx);
12868d75effSDimitry Andric   suppression_ctx = new (suppression_placeholder)
129e8d8bef9SDimitry Andric       LeakSuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
13068d75effSDimitry Andric }
13168d75effSDimitry Andric 
132e8d8bef9SDimitry Andric void LeakSuppressionContext::LazyInit() {
133e8d8bef9SDimitry Andric   if (!parsed) {
134e8d8bef9SDimitry Andric     parsed = true;
135e8d8bef9SDimitry Andric     context.ParseFromFile(flags()->suppressions);
136e8d8bef9SDimitry Andric     if (&__lsan_default_suppressions)
137e8d8bef9SDimitry Andric       context.Parse(__lsan_default_suppressions());
138e8d8bef9SDimitry Andric     context.Parse(kStdSuppressions);
1390eae32dcSDimitry Andric     if (flags()->use_tls && flags()->use_ld_allocations)
1400eae32dcSDimitry Andric       suppress_module = GetLinker();
141e8d8bef9SDimitry Andric   }
142e8d8bef9SDimitry Andric }
143e8d8bef9SDimitry Andric 
1440eae32dcSDimitry Andric Suppression *LeakSuppressionContext::GetSuppressionForAddr(uptr addr) {
1450eae32dcSDimitry Andric   Suppression *s = nullptr;
1460eae32dcSDimitry Andric 
1470eae32dcSDimitry Andric   // Suppress by module name.
14881ad6265SDimitry Andric   const char *module_name = Symbolizer::GetOrInit()->GetModuleNameForPc(addr);
14981ad6265SDimitry Andric   if (!module_name)
15081ad6265SDimitry Andric     module_name = "<unknown module>";
1510eae32dcSDimitry Andric   if (context.Match(module_name, kSuppressionLeak, &s))
1520eae32dcSDimitry Andric     return s;
1530eae32dcSDimitry Andric 
1540eae32dcSDimitry Andric   // Suppress by file or function name.
1550eae32dcSDimitry Andric   SymbolizedStack *frames = Symbolizer::GetOrInit()->SymbolizePC(addr);
1560eae32dcSDimitry Andric   for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
1570eae32dcSDimitry Andric     if (context.Match(cur->info.function, kSuppressionLeak, &s) ||
1580eae32dcSDimitry Andric         context.Match(cur->info.file, kSuppressionLeak, &s)) {
1590eae32dcSDimitry Andric       break;
1600eae32dcSDimitry Andric     }
1610eae32dcSDimitry Andric   }
1620eae32dcSDimitry Andric   frames->ClearAll();
1630eae32dcSDimitry Andric   return s;
1640eae32dcSDimitry Andric }
1650eae32dcSDimitry Andric 
1660eae32dcSDimitry Andric static uptr GetCallerPC(const StackTrace &stack) {
1670eae32dcSDimitry Andric   // The top frame is our malloc/calloc/etc. The next frame is the caller.
1680eae32dcSDimitry Andric   if (stack.size >= 2)
1690eae32dcSDimitry Andric     return stack.trace[1];
1700eae32dcSDimitry Andric   return 0;
1710eae32dcSDimitry Andric }
1720eae32dcSDimitry Andric 
173bdd1243dSDimitry Andric #  if SANITIZER_APPLE
174*06c3fb27SDimitry Andric // Several pointers in the Objective-C runtime (method cache and class_rw_t,
175*06c3fb27SDimitry Andric // for example) are tagged with additional bits we need to strip.
176*06c3fb27SDimitry Andric static inline void *TransformPointer(void *p) {
177bdd1243dSDimitry Andric   uptr ptr = reinterpret_cast<uptr>(p);
178*06c3fb27SDimitry Andric   return reinterpret_cast<void *>(ptr & OBJC_DATA_MASK);
179bdd1243dSDimitry Andric }
180bdd1243dSDimitry Andric #  endif
181bdd1243dSDimitry Andric 
1820eae32dcSDimitry Andric // On Linux, treats all chunks allocated from ld-linux.so as reachable, which
1830eae32dcSDimitry Andric // covers dynamically allocated TLS blocks, internal dynamic loader's loaded
1840eae32dcSDimitry Andric // modules accounting etc.
1850eae32dcSDimitry Andric // Dynamic TLS blocks contain the TLS variables of dynamically loaded modules.
1860eae32dcSDimitry Andric // They are allocated with a __libc_memalign() call in allocate_and_init()
1870eae32dcSDimitry Andric // (elf/dl-tls.c). Glibc won't tell us the address ranges occupied by those
1880eae32dcSDimitry Andric // blocks, but we can make sure they come from our own allocator by intercepting
1890eae32dcSDimitry Andric // __libc_memalign(). On top of that, there is no easy way to reach them. Their
1900eae32dcSDimitry Andric // addresses are stored in a dynamically allocated array (the DTV) which is
1910eae32dcSDimitry Andric // referenced from the static TLS. Unfortunately, we can't just rely on the DTV
1920eae32dcSDimitry Andric // being reachable from the static TLS, and the dynamic TLS being reachable from
1930eae32dcSDimitry Andric // the DTV. This is because the initial DTV is allocated before our interception
1940eae32dcSDimitry Andric // mechanism kicks in, and thus we don't recognize it as allocated memory. We
1950eae32dcSDimitry Andric // can't special-case it either, since we don't know its size.
1960eae32dcSDimitry Andric // Our solution is to include in the root set all allocations made from
1970eae32dcSDimitry Andric // ld-linux.so (which is where allocate_and_init() is implemented). This is
1980eae32dcSDimitry Andric // guaranteed to include all dynamic TLS blocks (and possibly other allocations
1990eae32dcSDimitry Andric // which we don't care about).
2000eae32dcSDimitry Andric // On all other platforms, this simply checks to ensure that the caller pc is
2010eae32dcSDimitry Andric // valid before reporting chunks as leaked.
2020eae32dcSDimitry Andric bool LeakSuppressionContext::SuppressInvalid(const StackTrace &stack) {
2030eae32dcSDimitry Andric   uptr caller_pc = GetCallerPC(stack);
2040eae32dcSDimitry Andric   // If caller_pc is unknown, this chunk may be allocated in a coroutine. Mark
2050eae32dcSDimitry Andric   // it as reachable, as we can't properly report its allocation stack anyway.
2060eae32dcSDimitry Andric   return !caller_pc ||
2070eae32dcSDimitry Andric          (suppress_module && suppress_module->containsAddress(caller_pc));
2080eae32dcSDimitry Andric }
2090eae32dcSDimitry Andric 
2100eae32dcSDimitry Andric bool LeakSuppressionContext::SuppressByRule(const StackTrace &stack,
2110eae32dcSDimitry Andric                                             uptr hit_count, uptr total_size) {
2120eae32dcSDimitry Andric   for (uptr i = 0; i < stack.size; i++) {
2130eae32dcSDimitry Andric     Suppression *s = GetSuppressionForAddr(
2140eae32dcSDimitry Andric         StackTrace::GetPreviousInstructionPc(stack.trace[i]));
2150eae32dcSDimitry Andric     if (s) {
2160eae32dcSDimitry Andric       s->weight += total_size;
2170eae32dcSDimitry Andric       atomic_fetch_add(&s->hit_count, hit_count, memory_order_relaxed);
2180eae32dcSDimitry Andric       return true;
2190eae32dcSDimitry Andric     }
2200eae32dcSDimitry Andric   }
2210eae32dcSDimitry Andric   return false;
2220eae32dcSDimitry Andric }
2230eae32dcSDimitry Andric 
2240eae32dcSDimitry Andric bool LeakSuppressionContext::Suppress(u32 stack_trace_id, uptr hit_count,
2250eae32dcSDimitry Andric                                       uptr total_size) {
2260eae32dcSDimitry Andric   LazyInit();
2270eae32dcSDimitry Andric   StackTrace stack = StackDepotGet(stack_trace_id);
2280eae32dcSDimitry Andric   if (!SuppressInvalid(stack) && !SuppressByRule(stack, hit_count, total_size))
2290eae32dcSDimitry Andric     return false;
2300eae32dcSDimitry Andric   suppressed_stacks_sorted = false;
2310eae32dcSDimitry Andric   suppressed_stacks.push_back(stack_trace_id);
2320eae32dcSDimitry Andric   return true;
2330eae32dcSDimitry Andric }
2340eae32dcSDimitry Andric 
235e8d8bef9SDimitry Andric static LeakSuppressionContext *GetSuppressionContext() {
23668d75effSDimitry Andric   CHECK(suppression_ctx);
23768d75effSDimitry Andric   return suppression_ctx;
23868d75effSDimitry Andric }
23968d75effSDimitry Andric 
24068d75effSDimitry Andric void InitCommonLsan() {
24168d75effSDimitry Andric   if (common_flags()->detect_leaks) {
24268d75effSDimitry Andric     // Initialization which can fail or print warnings should only be done if
24368d75effSDimitry Andric     // LSan is actually enabled.
24468d75effSDimitry Andric     InitializeSuppressions();
24568d75effSDimitry Andric     InitializePlatformSpecificModules();
24668d75effSDimitry Andric   }
24768d75effSDimitry Andric }
24868d75effSDimitry Andric 
24968d75effSDimitry Andric class Decorator : public __sanitizer::SanitizerCommonDecorator {
25068d75effSDimitry Andric  public:
25168d75effSDimitry Andric   Decorator() : SanitizerCommonDecorator() {}
25268d75effSDimitry Andric   const char *Error() { return Red(); }
25368d75effSDimitry Andric   const char *Leak() { return Blue(); }
25468d75effSDimitry Andric };
25568d75effSDimitry Andric 
25681ad6265SDimitry Andric static inline bool MaybeUserPointer(uptr p) {
25768d75effSDimitry Andric   // Since our heap is located in mmap-ed memory, we can assume a sensible lower
25868d75effSDimitry Andric   // bound on heap addresses.
25968d75effSDimitry Andric   const uptr kMinAddress = 4 * 4096;
2600eae32dcSDimitry Andric   if (p < kMinAddress)
2610eae32dcSDimitry Andric     return false;
26268d75effSDimitry Andric #  if defined(__x86_64__)
263*06c3fb27SDimitry Andric   // TODO: support LAM48 and 5 level page tables.
264*06c3fb27SDimitry Andric   // LAM_U57 mask format
265*06c3fb27SDimitry Andric   //  * top byte: 0x81 because the format is: [0] [6-bit tag] [0]
266*06c3fb27SDimitry Andric   //  * top-1 byte: 0xff because it should be 0
267*06c3fb27SDimitry Andric   //  * top-2 byte: 0x80 because Linux uses 128 TB VMA ending at 0x7fffffffffff
268*06c3fb27SDimitry Andric   constexpr uptr kLAM_U57Mask = 0x81ff80;
269*06c3fb27SDimitry Andric   constexpr uptr kPointerMask = kLAM_U57Mask << 40;
270*06c3fb27SDimitry Andric   return ((p & kPointerMask) == 0);
27168d75effSDimitry Andric #  elif defined(__mips64)
27268d75effSDimitry Andric   return ((p >> 40) == 0);
27368d75effSDimitry Andric #  elif defined(__aarch64__)
274*06c3fb27SDimitry Andric   // TBI (Top Byte Ignore) feature of AArch64: bits [63:56] are ignored in
275*06c3fb27SDimitry Andric   // address translation and can be used to store a tag.
276*06c3fb27SDimitry Andric   constexpr uptr kPointerMask = 255ULL << 48;
27781ad6265SDimitry Andric   // Accept up to 48 bit VMA.
278*06c3fb27SDimitry Andric   return ((p & kPointerMask) == 0);
279bdd1243dSDimitry Andric #  elif defined(__loongarch_lp64)
280bdd1243dSDimitry Andric   // Allow 47-bit user-space VMA at current.
281bdd1243dSDimitry Andric   return ((p >> 47) == 0);
28268d75effSDimitry Andric #  else
28368d75effSDimitry Andric   return true;
28468d75effSDimitry Andric #  endif
28568d75effSDimitry Andric }
28668d75effSDimitry Andric 
28768d75effSDimitry Andric // Scans the memory range, looking for byte patterns that point into allocator
28868d75effSDimitry Andric // chunks. Marks those chunks with |tag| and adds them to |frontier|.
28968d75effSDimitry Andric // There are two usage modes for this function: finding reachable chunks
29068d75effSDimitry Andric // (|tag| = kReachable) and finding indirectly leaked chunks
29168d75effSDimitry Andric // (|tag| = kIndirectlyLeaked). In the second case, there's no flood fill,
29268d75effSDimitry Andric // so |frontier| = 0.
2930eae32dcSDimitry Andric void ScanRangeForPointers(uptr begin, uptr end, Frontier *frontier,
29468d75effSDimitry Andric                           const char *region_type, ChunkTag tag) {
29568d75effSDimitry Andric   CHECK(tag == kReachable || tag == kIndirectlyLeaked);
29668d75effSDimitry Andric   const uptr alignment = flags()->pointer_alignment();
297349cc55cSDimitry Andric   LOG_POINTERS("Scanning %s range %p-%p.\n", region_type, (void *)begin,
298349cc55cSDimitry Andric                (void *)end);
29968d75effSDimitry Andric   uptr pp = begin;
30068d75effSDimitry Andric   if (pp % alignment)
30168d75effSDimitry Andric     pp = pp + alignment - pp % alignment;
30268d75effSDimitry Andric   for (; pp + sizeof(void *) <= end; pp += alignment) {
30368d75effSDimitry Andric     void *p = *reinterpret_cast<void **>(pp);
304bdd1243dSDimitry Andric #  if SANITIZER_APPLE
305*06c3fb27SDimitry Andric     p = TransformPointer(p);
306bdd1243dSDimitry Andric #  endif
30781ad6265SDimitry Andric     if (!MaybeUserPointer(reinterpret_cast<uptr>(p)))
3080eae32dcSDimitry Andric       continue;
30968d75effSDimitry Andric     uptr chunk = PointsIntoChunk(p);
3100eae32dcSDimitry Andric     if (!chunk)
3110eae32dcSDimitry Andric       continue;
31268d75effSDimitry Andric     // Pointers to self don't count. This matters when tag == kIndirectlyLeaked.
3130eae32dcSDimitry Andric     if (chunk == begin)
3140eae32dcSDimitry Andric       continue;
31568d75effSDimitry Andric     LsanMetadata m(chunk);
3160eae32dcSDimitry Andric     if (m.tag() == kReachable || m.tag() == kIgnored)
3170eae32dcSDimitry Andric       continue;
31868d75effSDimitry Andric 
31968d75effSDimitry Andric     // Do this check relatively late so we can log only the interesting cases.
32068d75effSDimitry Andric     if (!flags()->use_poisoned && WordIsPoisoned(pp)) {
32168d75effSDimitry Andric       LOG_POINTERS(
32268d75effSDimitry Andric           "%p is poisoned: ignoring %p pointing into chunk %p-%p of size "
32368d75effSDimitry Andric           "%zu.\n",
324349cc55cSDimitry Andric           (void *)pp, p, (void *)chunk, (void *)(chunk + m.requested_size()),
325349cc55cSDimitry Andric           m.requested_size());
32668d75effSDimitry Andric       continue;
32768d75effSDimitry Andric     }
32868d75effSDimitry Andric 
32968d75effSDimitry Andric     m.set_tag(tag);
330349cc55cSDimitry Andric     LOG_POINTERS("%p: found %p pointing into chunk %p-%p of size %zu.\n",
331349cc55cSDimitry Andric                  (void *)pp, p, (void *)chunk,
332349cc55cSDimitry Andric                  (void *)(chunk + m.requested_size()), m.requested_size());
33368d75effSDimitry Andric     if (frontier)
33468d75effSDimitry Andric       frontier->push_back(chunk);
33568d75effSDimitry Andric   }
33668d75effSDimitry Andric }
33768d75effSDimitry Andric 
33868d75effSDimitry Andric // Scans a global range for pointers
33968d75effSDimitry Andric void ScanGlobalRange(uptr begin, uptr end, Frontier *frontier) {
34068d75effSDimitry Andric   uptr allocator_begin = 0, allocator_end = 0;
34168d75effSDimitry Andric   GetAllocatorGlobalRange(&allocator_begin, &allocator_end);
34268d75effSDimitry Andric   if (begin <= allocator_begin && allocator_begin < end) {
34368d75effSDimitry Andric     CHECK_LE(allocator_begin, allocator_end);
34468d75effSDimitry Andric     CHECK_LE(allocator_end, end);
34568d75effSDimitry Andric     if (begin < allocator_begin)
34668d75effSDimitry Andric       ScanRangeForPointers(begin, allocator_begin, frontier, "GLOBAL",
34768d75effSDimitry Andric                            kReachable);
34868d75effSDimitry Andric     if (allocator_end < end)
34968d75effSDimitry Andric       ScanRangeForPointers(allocator_end, end, frontier, "GLOBAL", kReachable);
35068d75effSDimitry Andric   } else {
35168d75effSDimitry Andric     ScanRangeForPointers(begin, end, frontier, "GLOBAL", kReachable);
35268d75effSDimitry Andric   }
35368d75effSDimitry Andric }
35468d75effSDimitry Andric 
355bdd1243dSDimitry Andric void ScanExtraStackRanges(const InternalMmapVector<Range> &ranges,
356bdd1243dSDimitry Andric                           Frontier *frontier) {
357bdd1243dSDimitry Andric   for (uptr i = 0; i < ranges.size(); i++) {
358bdd1243dSDimitry Andric     ScanRangeForPointers(ranges[i].begin, ranges[i].end, frontier, "FAKE STACK",
359bdd1243dSDimitry Andric                          kReachable);
360bdd1243dSDimitry Andric   }
36168d75effSDimitry Andric }
36268d75effSDimitry Andric 
3635ffd83dbSDimitry Andric #  if SANITIZER_FUCHSIA
3645ffd83dbSDimitry Andric 
3655ffd83dbSDimitry Andric // Fuchsia handles all threads together with its own callback.
366bdd1243dSDimitry Andric static void ProcessThreads(SuspendedThreadsList const &, Frontier *, tid_t,
367bdd1243dSDimitry Andric                            uptr) {}
3685ffd83dbSDimitry Andric 
3695ffd83dbSDimitry Andric #  else
3705ffd83dbSDimitry Andric 
371e8d8bef9SDimitry Andric #    if SANITIZER_ANDROID
372e8d8bef9SDimitry Andric // FIXME: Move this out into *libcdep.cpp
373e8d8bef9SDimitry Andric extern "C" SANITIZER_WEAK_ATTRIBUTE void __libc_iterate_dynamic_tls(
374e8d8bef9SDimitry Andric     pid_t, void (*cb)(void *, void *, uptr, void *), void *);
375e8d8bef9SDimitry Andric #    endif
376e8d8bef9SDimitry Andric 
377e8d8bef9SDimitry Andric static void ProcessThreadRegistry(Frontier *frontier) {
378e8d8bef9SDimitry Andric   InternalMmapVector<uptr> ptrs;
379bdd1243dSDimitry Andric   GetAdditionalThreadContextPtrsLocked(&ptrs);
380e8d8bef9SDimitry Andric 
381e8d8bef9SDimitry Andric   for (uptr i = 0; i < ptrs.size(); ++i) {
382e8d8bef9SDimitry Andric     void *ptr = reinterpret_cast<void *>(ptrs[i]);
383e8d8bef9SDimitry Andric     uptr chunk = PointsIntoChunk(ptr);
384e8d8bef9SDimitry Andric     if (!chunk)
385e8d8bef9SDimitry Andric       continue;
386e8d8bef9SDimitry Andric     LsanMetadata m(chunk);
387e8d8bef9SDimitry Andric     if (!m.allocated())
388e8d8bef9SDimitry Andric       continue;
389e8d8bef9SDimitry Andric 
390e8d8bef9SDimitry Andric     // Mark as reachable and add to frontier.
391e8d8bef9SDimitry Andric     LOG_POINTERS("Treating pointer %p from ThreadContext as reachable\n", ptr);
392e8d8bef9SDimitry Andric     m.set_tag(kReachable);
393e8d8bef9SDimitry Andric     frontier->push_back(chunk);
394e8d8bef9SDimitry Andric   }
395e8d8bef9SDimitry Andric }
396e8d8bef9SDimitry Andric 
39768d75effSDimitry Andric // Scans thread data (stacks and TLS) for heap pointers.
39868d75effSDimitry Andric static void ProcessThreads(SuspendedThreadsList const &suspended_threads,
399bdd1243dSDimitry Andric                            Frontier *frontier, tid_t caller_tid,
400bdd1243dSDimitry Andric                            uptr caller_sp) {
401e8d8bef9SDimitry Andric   InternalMmapVector<uptr> registers;
402bdd1243dSDimitry Andric   InternalMmapVector<Range> extra_ranges;
40368d75effSDimitry Andric   for (uptr i = 0; i < suspended_threads.ThreadCount(); i++) {
40468d75effSDimitry Andric     tid_t os_id = static_cast<tid_t>(suspended_threads.GetThreadID(i));
405349cc55cSDimitry Andric     LOG_THREADS("Processing thread %llu.\n", os_id);
40668d75effSDimitry Andric     uptr stack_begin, stack_end, tls_begin, tls_end, cache_begin, cache_end;
40768d75effSDimitry Andric     DTLS *dtls;
4080eae32dcSDimitry Andric     bool thread_found =
4090eae32dcSDimitry Andric         GetThreadRangesLocked(os_id, &stack_begin, &stack_end, &tls_begin,
4100eae32dcSDimitry Andric                               &tls_end, &cache_begin, &cache_end, &dtls);
41168d75effSDimitry Andric     if (!thread_found) {
41268d75effSDimitry Andric       // If a thread can't be found in the thread registry, it's probably in the
41368d75effSDimitry Andric       // process of destruction. Log this event and move on.
414349cc55cSDimitry Andric       LOG_THREADS("Thread %llu not found in registry.\n", os_id);
41568d75effSDimitry Andric       continue;
41668d75effSDimitry Andric     }
41768d75effSDimitry Andric     uptr sp;
41868d75effSDimitry Andric     PtraceRegistersStatus have_registers =
419e8d8bef9SDimitry Andric         suspended_threads.GetRegistersAndSP(i, &registers, &sp);
42068d75effSDimitry Andric     if (have_registers != REGISTERS_AVAILABLE) {
421349cc55cSDimitry Andric       Report("Unable to get registers from thread %llu.\n", os_id);
42268d75effSDimitry Andric       // If unable to get SP, consider the entire stack to be reachable unless
42368d75effSDimitry Andric       // GetRegistersAndSP failed with ESRCH.
4240eae32dcSDimitry Andric       if (have_registers == REGISTERS_UNAVAILABLE_FATAL)
4250eae32dcSDimitry Andric         continue;
42668d75effSDimitry Andric       sp = stack_begin;
42768d75effSDimitry Andric     }
428bdd1243dSDimitry Andric     if (suspended_threads.GetThreadID(i) == caller_tid) {
429bdd1243dSDimitry Andric       sp = caller_sp;
430bdd1243dSDimitry Andric     }
43168d75effSDimitry Andric 
432e8d8bef9SDimitry Andric     if (flags()->use_registers && have_registers) {
433e8d8bef9SDimitry Andric       uptr registers_begin = reinterpret_cast<uptr>(registers.data());
434e8d8bef9SDimitry Andric       uptr registers_end =
435e8d8bef9SDimitry Andric           reinterpret_cast<uptr>(registers.data() + registers.size());
43668d75effSDimitry Andric       ScanRangeForPointers(registers_begin, registers_end, frontier,
43768d75effSDimitry Andric                            "REGISTERS", kReachable);
438e8d8bef9SDimitry Andric     }
43968d75effSDimitry Andric 
44068d75effSDimitry Andric     if (flags()->use_stacks) {
441349cc55cSDimitry Andric       LOG_THREADS("Stack at %p-%p (SP = %p).\n", (void *)stack_begin,
442349cc55cSDimitry Andric                   (void *)stack_end, (void *)sp);
44368d75effSDimitry Andric       if (sp < stack_begin || sp >= stack_end) {
44468d75effSDimitry Andric         // SP is outside the recorded stack range (e.g. the thread is running a
44568d75effSDimitry Andric         // signal handler on alternate stack, or swapcontext was used).
44668d75effSDimitry Andric         // Again, consider the entire stack range to be reachable.
44768d75effSDimitry Andric         LOG_THREADS("WARNING: stack pointer not in stack range.\n");
44868d75effSDimitry Andric         uptr page_size = GetPageSizeCached();
44968d75effSDimitry Andric         int skipped = 0;
45068d75effSDimitry Andric         while (stack_begin < stack_end &&
45168d75effSDimitry Andric                !IsAccessibleMemoryRange(stack_begin, 1)) {
45268d75effSDimitry Andric           skipped++;
45368d75effSDimitry Andric           stack_begin += page_size;
45468d75effSDimitry Andric         }
45568d75effSDimitry Andric         LOG_THREADS("Skipped %d guard page(s) to obtain stack %p-%p.\n",
456349cc55cSDimitry Andric                     skipped, (void *)stack_begin, (void *)stack_end);
45768d75effSDimitry Andric       } else {
45868d75effSDimitry Andric         // Shrink the stack range to ignore out-of-scope values.
45968d75effSDimitry Andric         stack_begin = sp;
46068d75effSDimitry Andric       }
46168d75effSDimitry Andric       ScanRangeForPointers(stack_begin, stack_end, frontier, "STACK",
46268d75effSDimitry Andric                            kReachable);
463bdd1243dSDimitry Andric       extra_ranges.clear();
464bdd1243dSDimitry Andric       GetThreadExtraStackRangesLocked(os_id, &extra_ranges);
465bdd1243dSDimitry Andric       ScanExtraStackRanges(extra_ranges, frontier);
46668d75effSDimitry Andric     }
46768d75effSDimitry Andric 
46868d75effSDimitry Andric     if (flags()->use_tls) {
46968d75effSDimitry Andric       if (tls_begin) {
470349cc55cSDimitry Andric         LOG_THREADS("TLS at %p-%p.\n", (void *)tls_begin, (void *)tls_end);
47168d75effSDimitry Andric         // If the tls and cache ranges don't overlap, scan full tls range,
47268d75effSDimitry Andric         // otherwise, only scan the non-overlapping portions
47368d75effSDimitry Andric         if (cache_begin == cache_end || tls_end < cache_begin ||
47468d75effSDimitry Andric             tls_begin > cache_end) {
47568d75effSDimitry Andric           ScanRangeForPointers(tls_begin, tls_end, frontier, "TLS", kReachable);
47668d75effSDimitry Andric         } else {
47768d75effSDimitry Andric           if (tls_begin < cache_begin)
47868d75effSDimitry Andric             ScanRangeForPointers(tls_begin, cache_begin, frontier, "TLS",
47968d75effSDimitry Andric                                  kReachable);
48068d75effSDimitry Andric           if (tls_end > cache_end)
48168d75effSDimitry Andric             ScanRangeForPointers(cache_end, tls_end, frontier, "TLS",
48268d75effSDimitry Andric                                  kReachable);
48368d75effSDimitry Andric         }
48468d75effSDimitry Andric       }
485e8d8bef9SDimitry Andric #    if SANITIZER_ANDROID
486e8d8bef9SDimitry Andric       auto *cb = +[](void *dtls_begin, void *dtls_end, uptr /*dso_idd*/,
487e8d8bef9SDimitry Andric                      void *arg) -> void {
488e8d8bef9SDimitry Andric         ScanRangeForPointers(reinterpret_cast<uptr>(dtls_begin),
489e8d8bef9SDimitry Andric                              reinterpret_cast<uptr>(dtls_end),
490e8d8bef9SDimitry Andric                              reinterpret_cast<Frontier *>(arg), "DTLS",
491e8d8bef9SDimitry Andric                              kReachable);
492e8d8bef9SDimitry Andric       };
493e8d8bef9SDimitry Andric 
494e8d8bef9SDimitry Andric       // FIXME: There might be a race-condition here (and in Bionic) if the
495e8d8bef9SDimitry Andric       // thread is suspended in the middle of updating its DTLS. IOWs, we
496e8d8bef9SDimitry Andric       // could scan already freed memory. (probably fine for now)
497e8d8bef9SDimitry Andric       __libc_iterate_dynamic_tls(os_id, cb, frontier);
498e8d8bef9SDimitry Andric #    else
49968d75effSDimitry Andric       if (dtls && !DTLSInDestruction(dtls)) {
500e8d8bef9SDimitry Andric         ForEachDVT(dtls, [&](const DTLS::DTV &dtv, int id) {
501e8d8bef9SDimitry Andric           uptr dtls_beg = dtv.beg;
502e8d8bef9SDimitry Andric           uptr dtls_end = dtls_beg + dtv.size;
50368d75effSDimitry Andric           if (dtls_beg < dtls_end) {
504349cc55cSDimitry Andric             LOG_THREADS("DTLS %d at %p-%p.\n", id, (void *)dtls_beg,
505349cc55cSDimitry Andric                         (void *)dtls_end);
50668d75effSDimitry Andric             ScanRangeForPointers(dtls_beg, dtls_end, frontier, "DTLS",
50768d75effSDimitry Andric                                  kReachable);
50868d75effSDimitry Andric           }
509e8d8bef9SDimitry Andric         });
51068d75effSDimitry Andric       } else {
51168d75effSDimitry Andric         // We are handling a thread with DTLS under destruction. Log about
51268d75effSDimitry Andric         // this and continue.
513349cc55cSDimitry Andric         LOG_THREADS("Thread %llu has DTLS under destruction.\n", os_id);
51468d75effSDimitry Andric       }
515e8d8bef9SDimitry Andric #    endif
51668d75effSDimitry Andric     }
51768d75effSDimitry Andric   }
518e8d8bef9SDimitry Andric 
519e8d8bef9SDimitry Andric   // Add pointers reachable from ThreadContexts
520e8d8bef9SDimitry Andric   ProcessThreadRegistry(frontier);
52168d75effSDimitry Andric }
52268d75effSDimitry Andric 
5235ffd83dbSDimitry Andric #  endif  // SANITIZER_FUCHSIA
5245ffd83dbSDimitry Andric 
525*06c3fb27SDimitry Andric // A map that contains [region_begin, region_end) pairs.
526*06c3fb27SDimitry Andric using RootRegions = DenseMap<detail::DenseMapPair<uptr, uptr>, uptr>;
527*06c3fb27SDimitry Andric 
528*06c3fb27SDimitry Andric static RootRegions &GetRootRegionsLocked() {
529*06c3fb27SDimitry Andric   global_mutex.CheckLocked();
530*06c3fb27SDimitry Andric   static RootRegions *regions = nullptr;
531*06c3fb27SDimitry Andric   alignas(RootRegions) static char placeholder[sizeof(RootRegions)];
532*06c3fb27SDimitry Andric   if (!regions)
533*06c3fb27SDimitry Andric     regions = new (placeholder) RootRegions();
534*06c3fb27SDimitry Andric   return *regions;
53568d75effSDimitry Andric }
53668d75effSDimitry Andric 
537*06c3fb27SDimitry Andric bool HasRootRegions() { return !GetRootRegionsLocked().empty(); }
538*06c3fb27SDimitry Andric 
539*06c3fb27SDimitry Andric void ScanRootRegions(Frontier *frontier,
540*06c3fb27SDimitry Andric                      const InternalMmapVectorNoCtor<Region> &mapped_regions) {
541*06c3fb27SDimitry Andric   if (!flags()->use_root_regions)
542*06c3fb27SDimitry Andric     return;
543*06c3fb27SDimitry Andric 
544*06c3fb27SDimitry Andric   InternalMmapVector<Region> regions;
545*06c3fb27SDimitry Andric   GetRootRegionsLocked().forEach([&](const auto &kv) {
546*06c3fb27SDimitry Andric     regions.push_back({kv.first.first, kv.first.second});
547*06c3fb27SDimitry Andric     return true;
548*06c3fb27SDimitry Andric   });
549*06c3fb27SDimitry Andric 
550*06c3fb27SDimitry Andric   InternalMmapVector<Region> intersection;
551*06c3fb27SDimitry Andric   Intersect(mapped_regions, regions, intersection);
552*06c3fb27SDimitry Andric 
553*06c3fb27SDimitry Andric   for (const Region &r : intersection) {
554*06c3fb27SDimitry Andric     LOG_POINTERS("Root region intersects with mapped region at %p-%p\n",
555*06c3fb27SDimitry Andric                  (void *)r.begin, (void *)r.end);
556*06c3fb27SDimitry Andric     ScanRangeForPointers(r.begin, r.end, frontier, "ROOT", kReachable);
55768d75effSDimitry Andric   }
55868d75effSDimitry Andric }
55968d75effSDimitry Andric 
56068d75effSDimitry Andric // Scans root regions for heap pointers.
56168d75effSDimitry Andric static void ProcessRootRegions(Frontier *frontier) {
562*06c3fb27SDimitry Andric   if (!flags()->use_root_regions || !HasRootRegions())
5630eae32dcSDimitry Andric     return;
564*06c3fb27SDimitry Andric   MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
565*06c3fb27SDimitry Andric   MemoryMappedSegment segment;
566*06c3fb27SDimitry Andric   InternalMmapVector<Region> mapped_regions;
567*06c3fb27SDimitry Andric   while (proc_maps.Next(&segment))
568*06c3fb27SDimitry Andric     if (segment.IsReadable())
569*06c3fb27SDimitry Andric       mapped_regions.push_back({segment.start, segment.end});
570*06c3fb27SDimitry Andric   ScanRootRegions(frontier, mapped_regions);
57168d75effSDimitry Andric }
57268d75effSDimitry Andric 
57368d75effSDimitry Andric static void FloodFillTag(Frontier *frontier, ChunkTag tag) {
57468d75effSDimitry Andric   while (frontier->size()) {
57568d75effSDimitry Andric     uptr next_chunk = frontier->back();
57668d75effSDimitry Andric     frontier->pop_back();
57768d75effSDimitry Andric     LsanMetadata m(next_chunk);
57868d75effSDimitry Andric     ScanRangeForPointers(next_chunk, next_chunk + m.requested_size(), frontier,
57968d75effSDimitry Andric                          "HEAP", tag);
58068d75effSDimitry Andric   }
58168d75effSDimitry Andric }
58268d75effSDimitry Andric 
58368d75effSDimitry Andric // ForEachChunk callback. If the chunk is marked as leaked, marks all chunks
58468d75effSDimitry Andric // which are reachable from it as indirectly leaked.
58568d75effSDimitry Andric static void MarkIndirectlyLeakedCb(uptr chunk, void *arg) {
58668d75effSDimitry Andric   chunk = GetUserBegin(chunk);
58768d75effSDimitry Andric   LsanMetadata m(chunk);
58868d75effSDimitry Andric   if (m.allocated() && m.tag() != kReachable) {
58968d75effSDimitry Andric     ScanRangeForPointers(chunk, chunk + m.requested_size(),
59068d75effSDimitry Andric                          /* frontier */ nullptr, "HEAP", kIndirectlyLeaked);
59168d75effSDimitry Andric   }
59268d75effSDimitry Andric }
59368d75effSDimitry Andric 
594e8d8bef9SDimitry Andric static void IgnoredSuppressedCb(uptr chunk, void *arg) {
595e8d8bef9SDimitry Andric   CHECK(arg);
596e8d8bef9SDimitry Andric   chunk = GetUserBegin(chunk);
597e8d8bef9SDimitry Andric   LsanMetadata m(chunk);
598e8d8bef9SDimitry Andric   if (!m.allocated() || m.tag() == kIgnored)
599e8d8bef9SDimitry Andric     return;
600e8d8bef9SDimitry Andric 
601e8d8bef9SDimitry Andric   const InternalMmapVector<u32> &suppressed =
602e8d8bef9SDimitry Andric       *static_cast<const InternalMmapVector<u32> *>(arg);
603e8d8bef9SDimitry Andric   uptr idx = InternalLowerBound(suppressed, m.stack_trace_id());
604e8d8bef9SDimitry Andric   if (idx >= suppressed.size() || m.stack_trace_id() != suppressed[idx])
605e8d8bef9SDimitry Andric     return;
606e8d8bef9SDimitry Andric 
607349cc55cSDimitry Andric   LOG_POINTERS("Suppressed: chunk %p-%p of size %zu.\n", (void *)chunk,
608349cc55cSDimitry Andric                (void *)(chunk + m.requested_size()), m.requested_size());
609e8d8bef9SDimitry Andric   m.set_tag(kIgnored);
610e8d8bef9SDimitry Andric }
611e8d8bef9SDimitry Andric 
61268d75effSDimitry Andric // ForEachChunk callback. If chunk is marked as ignored, adds its address to
61368d75effSDimitry Andric // frontier.
61468d75effSDimitry Andric static void CollectIgnoredCb(uptr chunk, void *arg) {
61568d75effSDimitry Andric   CHECK(arg);
61668d75effSDimitry Andric   chunk = GetUserBegin(chunk);
61768d75effSDimitry Andric   LsanMetadata m(chunk);
61868d75effSDimitry Andric   if (m.allocated() && m.tag() == kIgnored) {
619349cc55cSDimitry Andric     LOG_POINTERS("Ignored: chunk %p-%p of size %zu.\n", (void *)chunk,
620349cc55cSDimitry Andric                  (void *)(chunk + m.requested_size()), m.requested_size());
62168d75effSDimitry Andric     reinterpret_cast<Frontier *>(arg)->push_back(chunk);
62268d75effSDimitry Andric   }
62368d75effSDimitry Andric }
62468d75effSDimitry Andric 
62568d75effSDimitry Andric // Sets the appropriate tag on each chunk.
6265ffd83dbSDimitry Andric static void ClassifyAllChunks(SuspendedThreadsList const &suspended_threads,
627bdd1243dSDimitry Andric                               Frontier *frontier, tid_t caller_tid,
628bdd1243dSDimitry Andric                               uptr caller_sp) {
629e8d8bef9SDimitry Andric   const InternalMmapVector<u32> &suppressed_stacks =
630e8d8bef9SDimitry Andric       GetSuppressionContext()->GetSortedSuppressedStacks();
631e8d8bef9SDimitry Andric   if (!suppressed_stacks.empty()) {
632e8d8bef9SDimitry Andric     ForEachChunk(IgnoredSuppressedCb,
633e8d8bef9SDimitry Andric                  const_cast<InternalMmapVector<u32> *>(&suppressed_stacks));
634e8d8bef9SDimitry Andric   }
6355ffd83dbSDimitry Andric   ForEachChunk(CollectIgnoredCb, frontier);
6365ffd83dbSDimitry Andric   ProcessGlobalRegions(frontier);
637bdd1243dSDimitry Andric   ProcessThreads(suspended_threads, frontier, caller_tid, caller_sp);
6385ffd83dbSDimitry Andric   ProcessRootRegions(frontier);
6395ffd83dbSDimitry Andric   FloodFillTag(frontier, kReachable);
64068d75effSDimitry Andric 
64168d75effSDimitry Andric   // The check here is relatively expensive, so we do this in a separate flood
64268d75effSDimitry Andric   // fill. That way we can skip the check for chunks that are reachable
64368d75effSDimitry Andric   // otherwise.
64468d75effSDimitry Andric   LOG_POINTERS("Processing platform-specific allocations.\n");
6455ffd83dbSDimitry Andric   ProcessPlatformSpecificAllocations(frontier);
6465ffd83dbSDimitry Andric   FloodFillTag(frontier, kReachable);
64768d75effSDimitry Andric 
64868d75effSDimitry Andric   // Iterate over leaked chunks and mark those that are reachable from other
64968d75effSDimitry Andric   // leaked chunks.
65068d75effSDimitry Andric   LOG_POINTERS("Scanning leaked chunks.\n");
65168d75effSDimitry Andric   ForEachChunk(MarkIndirectlyLeakedCb, nullptr);
65268d75effSDimitry Andric }
65368d75effSDimitry Andric 
65468d75effSDimitry Andric // ForEachChunk callback. Resets the tags to pre-leak-check state.
65568d75effSDimitry Andric static void ResetTagsCb(uptr chunk, void *arg) {
65668d75effSDimitry Andric   (void)arg;
65768d75effSDimitry Andric   chunk = GetUserBegin(chunk);
65868d75effSDimitry Andric   LsanMetadata m(chunk);
65968d75effSDimitry Andric   if (m.allocated() && m.tag() != kIgnored)
66068d75effSDimitry Andric     m.set_tag(kDirectlyLeaked);
66168d75effSDimitry Andric }
66268d75effSDimitry Andric 
66368d75effSDimitry Andric // ForEachChunk callback. Aggregates information about unreachable chunks into
66468d75effSDimitry Andric // a LeakReport.
66568d75effSDimitry Andric static void CollectLeaksCb(uptr chunk, void *arg) {
66668d75effSDimitry Andric   CHECK(arg);
6670eae32dcSDimitry Andric   LeakedChunks *leaks = reinterpret_cast<LeakedChunks *>(arg);
66868d75effSDimitry Andric   chunk = GetUserBegin(chunk);
66968d75effSDimitry Andric   LsanMetadata m(chunk);
6700eae32dcSDimitry Andric   if (!m.allocated())
6710eae32dcSDimitry Andric     return;
6720eae32dcSDimitry Andric   if (m.tag() == kDirectlyLeaked || m.tag() == kIndirectlyLeaked)
6730eae32dcSDimitry Andric     leaks->push_back({chunk, m.stack_trace_id(), m.requested_size(), m.tag()});
67468d75effSDimitry Andric }
67568d75effSDimitry Andric 
676e8d8bef9SDimitry Andric void LeakSuppressionContext::PrintMatchedSuppressions() {
67768d75effSDimitry Andric   InternalMmapVector<Suppression *> matched;
678e8d8bef9SDimitry Andric   context.GetMatched(&matched);
67968d75effSDimitry Andric   if (!matched.size())
68068d75effSDimitry Andric     return;
68168d75effSDimitry Andric   const char *line = "-----------------------------------------------------";
68268d75effSDimitry Andric   Printf("%s\n", line);
68368d75effSDimitry Andric   Printf("Suppressions used:\n");
68468d75effSDimitry Andric   Printf("  count      bytes template\n");
685e8d8bef9SDimitry Andric   for (uptr i = 0; i < matched.size(); i++) {
686e8d8bef9SDimitry Andric     Printf("%7zu %10zu %s\n",
687e8d8bef9SDimitry Andric            static_cast<uptr>(atomic_load_relaxed(&matched[i]->hit_count)),
688e8d8bef9SDimitry Andric            matched[i]->weight, matched[i]->templ);
689e8d8bef9SDimitry Andric   }
69068d75effSDimitry Andric   Printf("%s\n\n", line);
69168d75effSDimitry Andric }
69268d75effSDimitry Andric 
6935ffd83dbSDimitry Andric #  if SANITIZER_FUCHSIA
6945ffd83dbSDimitry Andric 
6955ffd83dbSDimitry Andric // Fuchsia provides a libc interface that guarantees all threads are
6965ffd83dbSDimitry Andric // covered, and SuspendedThreadList is never really used.
6975ffd83dbSDimitry Andric static void ReportUnsuspendedThreads(const SuspendedThreadsList &) {}
6985ffd83dbSDimitry Andric 
6995ffd83dbSDimitry Andric #  else  // !SANITIZER_FUCHSIA
7005ffd83dbSDimitry Andric 
70168d75effSDimitry Andric static void ReportUnsuspendedThreads(
70268d75effSDimitry Andric     const SuspendedThreadsList &suspended_threads) {
70368d75effSDimitry Andric   InternalMmapVector<tid_t> threads(suspended_threads.ThreadCount());
70468d75effSDimitry Andric   for (uptr i = 0; i < suspended_threads.ThreadCount(); ++i)
70568d75effSDimitry Andric     threads[i] = suspended_threads.GetThreadID(i);
70668d75effSDimitry Andric 
70768d75effSDimitry Andric   Sort(threads.data(), threads.size());
70868d75effSDimitry Andric 
709bdd1243dSDimitry Andric   InternalMmapVector<tid_t> unsuspended;
710bdd1243dSDimitry Andric   GetRunningThreadsLocked(&unsuspended);
711bdd1243dSDimitry Andric 
712bdd1243dSDimitry Andric   for (auto os_id : unsuspended) {
713bdd1243dSDimitry Andric     uptr i = InternalLowerBound(threads, os_id);
714bdd1243dSDimitry Andric     if (i >= threads.size() || threads[i] != os_id)
715bdd1243dSDimitry Andric       Report(
716bdd1243dSDimitry Andric           "Running thread %zu was not suspended. False leaks are possible.\n",
717bdd1243dSDimitry Andric           os_id);
718bdd1243dSDimitry Andric   }
71968d75effSDimitry Andric }
72068d75effSDimitry Andric 
7215ffd83dbSDimitry Andric #  endif  // !SANITIZER_FUCHSIA
7225ffd83dbSDimitry Andric 
72368d75effSDimitry Andric static void CheckForLeaksCallback(const SuspendedThreadsList &suspended_threads,
72468d75effSDimitry Andric                                   void *arg) {
72568d75effSDimitry Andric   CheckForLeaksParam *param = reinterpret_cast<CheckForLeaksParam *>(arg);
72668d75effSDimitry Andric   CHECK(param);
72768d75effSDimitry Andric   CHECK(!param->success);
72868d75effSDimitry Andric   ReportUnsuspendedThreads(suspended_threads);
729bdd1243dSDimitry Andric   ClassifyAllChunks(suspended_threads, &param->frontier, param->caller_tid,
730bdd1243dSDimitry Andric                     param->caller_sp);
7310eae32dcSDimitry Andric   ForEachChunk(CollectLeaksCb, &param->leaks);
73268d75effSDimitry Andric   // Clean up for subsequent leak checks. This assumes we did not overwrite any
73368d75effSDimitry Andric   // kIgnored tags.
73468d75effSDimitry Andric   ForEachChunk(ResetTagsCb, nullptr);
73568d75effSDimitry Andric   param->success = true;
73668d75effSDimitry Andric }
73768d75effSDimitry Andric 
738e8d8bef9SDimitry Andric static bool PrintResults(LeakReport &report) {
739e8d8bef9SDimitry Andric   uptr unsuppressed_count = report.UnsuppressedLeakCount();
740e8d8bef9SDimitry Andric   if (unsuppressed_count) {
741e8d8bef9SDimitry Andric     Decorator d;
742e8d8bef9SDimitry Andric     Printf(
743e8d8bef9SDimitry Andric         "\n"
744e8d8bef9SDimitry Andric         "================================================================="
745e8d8bef9SDimitry Andric         "\n");
746e8d8bef9SDimitry Andric     Printf("%s", d.Error());
747e8d8bef9SDimitry Andric     Report("ERROR: LeakSanitizer: detected memory leaks\n");
748e8d8bef9SDimitry Andric     Printf("%s", d.Default());
749e8d8bef9SDimitry Andric     report.ReportTopLeaks(flags()->max_leaks);
750e8d8bef9SDimitry Andric   }
751e8d8bef9SDimitry Andric   if (common_flags()->print_suppressions)
752e8d8bef9SDimitry Andric     GetSuppressionContext()->PrintMatchedSuppressions();
753e8d8bef9SDimitry Andric   if (unsuppressed_count > 0) {
754e8d8bef9SDimitry Andric     report.PrintSummary();
755e8d8bef9SDimitry Andric     return true;
756e8d8bef9SDimitry Andric   }
757e8d8bef9SDimitry Andric   return false;
758e8d8bef9SDimitry Andric }
759e8d8bef9SDimitry Andric 
76068d75effSDimitry Andric static bool CheckForLeaks() {
761bdd1243dSDimitry Andric   if (&__lsan_is_turned_off && __lsan_is_turned_off()) {
762bdd1243dSDimitry Andric     VReport(1, "LeakSanitizer is disabled");
76368d75effSDimitry Andric     return false;
764bdd1243dSDimitry Andric   }
765bdd1243dSDimitry Andric   VReport(1, "LeakSanitizer: checking for leaks");
766e8d8bef9SDimitry Andric   // Inside LockStuffAndStopTheWorld we can't run symbolizer, so we can't match
767e8d8bef9SDimitry Andric   // suppressions. However if a stack id was previously suppressed, it should be
768e8d8bef9SDimitry Andric   // suppressed in future checks as well.
769e8d8bef9SDimitry Andric   for (int i = 0;; ++i) {
77068d75effSDimitry Andric     EnsureMainThreadIDIsCorrect();
77168d75effSDimitry Andric     CheckForLeaksParam param;
772bdd1243dSDimitry Andric     // Capture calling thread's stack pointer early, to avoid false negatives.
773bdd1243dSDimitry Andric     // Old frame with dead pointers might be overlapped by new frame inside
774bdd1243dSDimitry Andric     // CheckForLeaks which does not use bytes with pointers before the
775bdd1243dSDimitry Andric     // threads are suspended and stack pointers captured.
776bdd1243dSDimitry Andric     param.caller_tid = GetTid();
777bdd1243dSDimitry Andric     param.caller_sp = reinterpret_cast<uptr>(__builtin_frame_address(0));
77868d75effSDimitry Andric     LockStuffAndStopTheWorld(CheckForLeaksCallback, &param);
77968d75effSDimitry Andric     if (!param.success) {
78068d75effSDimitry Andric       Report("LeakSanitizer has encountered a fatal error.\n");
78168d75effSDimitry Andric       Report(
78268d75effSDimitry Andric           "HINT: For debugging, try setting environment variable "
78368d75effSDimitry Andric           "LSAN_OPTIONS=verbosity=1:log_threads=1\n");
78468d75effSDimitry Andric       Report(
785e8d8bef9SDimitry Andric           "HINT: LeakSanitizer does not work under ptrace (strace, gdb, "
786e8d8bef9SDimitry Andric           "etc)\n");
78768d75effSDimitry Andric       Die();
78868d75effSDimitry Andric     }
7890eae32dcSDimitry Andric     LeakReport leak_report;
7900eae32dcSDimitry Andric     leak_report.AddLeakedChunks(param.leaks);
7910eae32dcSDimitry Andric 
792e8d8bef9SDimitry Andric     // No new suppressions stacks, so rerun will not help and we can report.
7930eae32dcSDimitry Andric     if (!leak_report.ApplySuppressions())
7940eae32dcSDimitry Andric       return PrintResults(leak_report);
795e8d8bef9SDimitry Andric 
796e8d8bef9SDimitry Andric     // No indirect leaks to report, so we are done here.
7970eae32dcSDimitry Andric     if (!leak_report.IndirectUnsuppressedLeakCount())
7980eae32dcSDimitry Andric       return PrintResults(leak_report);
799e8d8bef9SDimitry Andric 
800e8d8bef9SDimitry Andric     if (i >= 8) {
801e8d8bef9SDimitry Andric       Report("WARNING: LeakSanitizer gave up on indirect leaks suppression.\n");
8020eae32dcSDimitry Andric       return PrintResults(leak_report);
80368d75effSDimitry Andric     }
804e8d8bef9SDimitry Andric 
805e8d8bef9SDimitry Andric     // We found a new previously unseen suppressed call stack. Rerun to make
806e8d8bef9SDimitry Andric     // sure it does not hold indirect leaks.
807e8d8bef9SDimitry Andric     VReport(1, "Rerun with %zu suppressed stacks.",
808e8d8bef9SDimitry Andric             GetSuppressionContext()->GetSortedSuppressedStacks().size());
80968d75effSDimitry Andric   }
81068d75effSDimitry Andric }
81168d75effSDimitry Andric 
81268d75effSDimitry Andric static bool has_reported_leaks = false;
81368d75effSDimitry Andric bool HasReportedLeaks() { return has_reported_leaks; }
81468d75effSDimitry Andric 
81568d75effSDimitry Andric void DoLeakCheck() {
816349cc55cSDimitry Andric   Lock l(&global_mutex);
81768d75effSDimitry Andric   static bool already_done;
8180eae32dcSDimitry Andric   if (already_done)
8190eae32dcSDimitry Andric     return;
82068d75effSDimitry Andric   already_done = true;
82168d75effSDimitry Andric   has_reported_leaks = CheckForLeaks();
8220eae32dcSDimitry Andric   if (has_reported_leaks)
8230eae32dcSDimitry Andric     HandleLeaks();
82468d75effSDimitry Andric }
82568d75effSDimitry Andric 
82668d75effSDimitry Andric static int DoRecoverableLeakCheck() {
827349cc55cSDimitry Andric   Lock l(&global_mutex);
82868d75effSDimitry Andric   bool have_leaks = CheckForLeaks();
82968d75effSDimitry Andric   return have_leaks ? 1 : 0;
83068d75effSDimitry Andric }
83168d75effSDimitry Andric 
83268d75effSDimitry Andric void DoRecoverableLeakCheckVoid() { DoRecoverableLeakCheck(); }
83368d75effSDimitry Andric 
83468d75effSDimitry Andric ///// LeakReport implementation. /////
83568d75effSDimitry Andric 
83668d75effSDimitry Andric // A hard limit on the number of distinct leaks, to avoid quadratic complexity
83768d75effSDimitry Andric // in LeakReport::AddLeakedChunk(). We don't expect to ever see this many leaks
83868d75effSDimitry Andric // in real-world applications.
8390eae32dcSDimitry Andric // FIXME: Get rid of this limit by moving logic into DedupLeaks.
84068d75effSDimitry Andric const uptr kMaxLeaksConsidered = 5000;
84168d75effSDimitry Andric 
8420eae32dcSDimitry Andric void LeakReport::AddLeakedChunks(const LeakedChunks &chunks) {
8430eae32dcSDimitry Andric   for (const LeakedChunk &leak : chunks) {
8440eae32dcSDimitry Andric     uptr chunk = leak.chunk;
8450eae32dcSDimitry Andric     u32 stack_trace_id = leak.stack_trace_id;
8460eae32dcSDimitry Andric     uptr leaked_size = leak.leaked_size;
8470eae32dcSDimitry Andric     ChunkTag tag = leak.tag;
84868d75effSDimitry Andric     CHECK(tag == kDirectlyLeaked || tag == kIndirectlyLeaked);
849349cc55cSDimitry Andric 
850349cc55cSDimitry Andric     if (u32 resolution = flags()->resolution) {
851349cc55cSDimitry Andric       StackTrace stack = StackDepotGet(stack_trace_id);
852349cc55cSDimitry Andric       stack.size = Min(stack.size, resolution);
853349cc55cSDimitry Andric       stack_trace_id = StackDepotPut(stack);
854349cc55cSDimitry Andric     }
855349cc55cSDimitry Andric 
85668d75effSDimitry Andric     bool is_directly_leaked = (tag == kDirectlyLeaked);
85768d75effSDimitry Andric     uptr i;
85868d75effSDimitry Andric     for (i = 0; i < leaks_.size(); i++) {
85968d75effSDimitry Andric       if (leaks_[i].stack_trace_id == stack_trace_id &&
86068d75effSDimitry Andric           leaks_[i].is_directly_leaked == is_directly_leaked) {
86168d75effSDimitry Andric         leaks_[i].hit_count++;
86268d75effSDimitry Andric         leaks_[i].total_size += leaked_size;
86368d75effSDimitry Andric         break;
86468d75effSDimitry Andric       }
86568d75effSDimitry Andric     }
86668d75effSDimitry Andric     if (i == leaks_.size()) {
8670eae32dcSDimitry Andric       if (leaks_.size() == kMaxLeaksConsidered)
8680eae32dcSDimitry Andric         return;
8690eae32dcSDimitry Andric       Leak leak = {next_id_++,         /* hit_count */ 1,
8700eae32dcSDimitry Andric                    leaked_size,        stack_trace_id,
87168d75effSDimitry Andric                    is_directly_leaked, /* is_suppressed */ false};
87268d75effSDimitry Andric       leaks_.push_back(leak);
87368d75effSDimitry Andric     }
87468d75effSDimitry Andric     if (flags()->report_objects) {
875*06c3fb27SDimitry Andric       LeakedObject obj = {leaks_[i].id, GetUserAddr(chunk), leaked_size};
87668d75effSDimitry Andric       leaked_objects_.push_back(obj);
87768d75effSDimitry Andric     }
87868d75effSDimitry Andric   }
8790eae32dcSDimitry Andric }
88068d75effSDimitry Andric 
88168d75effSDimitry Andric static bool LeakComparator(const Leak &leak1, const Leak &leak2) {
88268d75effSDimitry Andric   if (leak1.is_directly_leaked == leak2.is_directly_leaked)
88368d75effSDimitry Andric     return leak1.total_size > leak2.total_size;
88468d75effSDimitry Andric   else
88568d75effSDimitry Andric     return leak1.is_directly_leaked;
88668d75effSDimitry Andric }
88768d75effSDimitry Andric 
88868d75effSDimitry Andric void LeakReport::ReportTopLeaks(uptr num_leaks_to_report) {
88968d75effSDimitry Andric   CHECK(leaks_.size() <= kMaxLeaksConsidered);
89068d75effSDimitry Andric   Printf("\n");
89168d75effSDimitry Andric   if (leaks_.size() == kMaxLeaksConsidered)
8920eae32dcSDimitry Andric     Printf(
8930eae32dcSDimitry Andric         "Too many leaks! Only the first %zu leaks encountered will be "
89468d75effSDimitry Andric         "reported.\n",
89568d75effSDimitry Andric         kMaxLeaksConsidered);
89668d75effSDimitry Andric 
89768d75effSDimitry Andric   uptr unsuppressed_count = UnsuppressedLeakCount();
89868d75effSDimitry Andric   if (num_leaks_to_report > 0 && num_leaks_to_report < unsuppressed_count)
89968d75effSDimitry Andric     Printf("The %zu top leak(s):\n", num_leaks_to_report);
90068d75effSDimitry Andric   Sort(leaks_.data(), leaks_.size(), &LeakComparator);
90168d75effSDimitry Andric   uptr leaks_reported = 0;
90268d75effSDimitry Andric   for (uptr i = 0; i < leaks_.size(); i++) {
9030eae32dcSDimitry Andric     if (leaks_[i].is_suppressed)
9040eae32dcSDimitry Andric       continue;
90568d75effSDimitry Andric     PrintReportForLeak(i);
90668d75effSDimitry Andric     leaks_reported++;
9070eae32dcSDimitry Andric     if (leaks_reported == num_leaks_to_report)
9080eae32dcSDimitry Andric       break;
90968d75effSDimitry Andric   }
91068d75effSDimitry Andric   if (leaks_reported < unsuppressed_count) {
91168d75effSDimitry Andric     uptr remaining = unsuppressed_count - leaks_reported;
91268d75effSDimitry Andric     Printf("Omitting %zu more leak(s).\n", remaining);
91368d75effSDimitry Andric   }
91468d75effSDimitry Andric }
91568d75effSDimitry Andric 
91668d75effSDimitry Andric void LeakReport::PrintReportForLeak(uptr index) {
91768d75effSDimitry Andric   Decorator d;
91868d75effSDimitry Andric   Printf("%s", d.Leak());
91968d75effSDimitry Andric   Printf("%s leak of %zu byte(s) in %zu object(s) allocated from:\n",
92068d75effSDimitry Andric          leaks_[index].is_directly_leaked ? "Direct" : "Indirect",
92168d75effSDimitry Andric          leaks_[index].total_size, leaks_[index].hit_count);
92268d75effSDimitry Andric   Printf("%s", d.Default());
92368d75effSDimitry Andric 
924349cc55cSDimitry Andric   CHECK(leaks_[index].stack_trace_id);
925349cc55cSDimitry Andric   StackDepotGet(leaks_[index].stack_trace_id).Print();
92668d75effSDimitry Andric 
92768d75effSDimitry Andric   if (flags()->report_objects) {
92868d75effSDimitry Andric     Printf("Objects leaked above:\n");
92968d75effSDimitry Andric     PrintLeakedObjectsForLeak(index);
93068d75effSDimitry Andric     Printf("\n");
93168d75effSDimitry Andric   }
93268d75effSDimitry Andric }
93368d75effSDimitry Andric 
93468d75effSDimitry Andric void LeakReport::PrintLeakedObjectsForLeak(uptr index) {
93568d75effSDimitry Andric   u32 leak_id = leaks_[index].id;
93668d75effSDimitry Andric   for (uptr j = 0; j < leaked_objects_.size(); j++) {
93768d75effSDimitry Andric     if (leaked_objects_[j].leak_id == leak_id)
938349cc55cSDimitry Andric       Printf("%p (%zu bytes)\n", (void *)leaked_objects_[j].addr,
93968d75effSDimitry Andric              leaked_objects_[j].size);
94068d75effSDimitry Andric   }
94168d75effSDimitry Andric }
94268d75effSDimitry Andric 
94368d75effSDimitry Andric void LeakReport::PrintSummary() {
94468d75effSDimitry Andric   CHECK(leaks_.size() <= kMaxLeaksConsidered);
94568d75effSDimitry Andric   uptr bytes = 0, allocations = 0;
94668d75effSDimitry Andric   for (uptr i = 0; i < leaks_.size(); i++) {
9470eae32dcSDimitry Andric     if (leaks_[i].is_suppressed)
9480eae32dcSDimitry Andric       continue;
94968d75effSDimitry Andric     bytes += leaks_[i].total_size;
95068d75effSDimitry Andric     allocations += leaks_[i].hit_count;
95168d75effSDimitry Andric   }
952fe6060f1SDimitry Andric   InternalScopedString summary;
95368d75effSDimitry Andric   summary.append("%zu byte(s) leaked in %zu allocation(s).", bytes,
95468d75effSDimitry Andric                  allocations);
95568d75effSDimitry Andric   ReportErrorSummary(summary.data());
95668d75effSDimitry Andric }
95768d75effSDimitry Andric 
958e8d8bef9SDimitry Andric uptr LeakReport::ApplySuppressions() {
959e8d8bef9SDimitry Andric   LeakSuppressionContext *suppressions = GetSuppressionContext();
960*06c3fb27SDimitry Andric   uptr new_suppressions = 0;
96168d75effSDimitry Andric   for (uptr i = 0; i < leaks_.size(); i++) {
9620eae32dcSDimitry Andric     if (suppressions->Suppress(leaks_[i].stack_trace_id, leaks_[i].hit_count,
9630eae32dcSDimitry Andric                                leaks_[i].total_size)) {
96468d75effSDimitry Andric       leaks_[i].is_suppressed = true;
965e8d8bef9SDimitry Andric       ++new_suppressions;
96668d75effSDimitry Andric     }
96768d75effSDimitry Andric   }
968e8d8bef9SDimitry Andric   return new_suppressions;
96968d75effSDimitry Andric }
97068d75effSDimitry Andric 
97168d75effSDimitry Andric uptr LeakReport::UnsuppressedLeakCount() {
97268d75effSDimitry Andric   uptr result = 0;
97368d75effSDimitry Andric   for (uptr i = 0; i < leaks_.size(); i++)
9740eae32dcSDimitry Andric     if (!leaks_[i].is_suppressed)
9750eae32dcSDimitry Andric       result++;
97668d75effSDimitry Andric   return result;
97768d75effSDimitry Andric }
97868d75effSDimitry Andric 
979e8d8bef9SDimitry Andric uptr LeakReport::IndirectUnsuppressedLeakCount() {
980e8d8bef9SDimitry Andric   uptr result = 0;
981e8d8bef9SDimitry Andric   for (uptr i = 0; i < leaks_.size(); i++)
982e8d8bef9SDimitry Andric     if (!leaks_[i].is_suppressed && !leaks_[i].is_directly_leaked)
983e8d8bef9SDimitry Andric       result++;
984e8d8bef9SDimitry Andric   return result;
985e8d8bef9SDimitry Andric }
986e8d8bef9SDimitry Andric 
98768d75effSDimitry Andric }  // namespace __lsan
98868d75effSDimitry Andric #else   // CAN_SANITIZE_LEAKS
98968d75effSDimitry Andric namespace __lsan {
99068d75effSDimitry Andric void InitCommonLsan() {}
99168d75effSDimitry Andric void DoLeakCheck() {}
99268d75effSDimitry Andric void DoRecoverableLeakCheckVoid() {}
99368d75effSDimitry Andric void DisableInThisThread() {}
99468d75effSDimitry Andric void EnableInThisThread() {}
9950eae32dcSDimitry Andric }  // namespace __lsan
99668d75effSDimitry Andric #endif  // CAN_SANITIZE_LEAKS
99768d75effSDimitry Andric 
99868d75effSDimitry Andric using namespace __lsan;
99968d75effSDimitry Andric 
100068d75effSDimitry Andric extern "C" {
100168d75effSDimitry Andric SANITIZER_INTERFACE_ATTRIBUTE
100268d75effSDimitry Andric void __lsan_ignore_object(const void *p) {
100368d75effSDimitry Andric #if CAN_SANITIZE_LEAKS
100468d75effSDimitry Andric   if (!common_flags()->detect_leaks)
100568d75effSDimitry Andric     return;
100668d75effSDimitry Andric   // Cannot use PointsIntoChunk or LsanMetadata here, since the allocator is not
100768d75effSDimitry Andric   // locked.
1008349cc55cSDimitry Andric   Lock l(&global_mutex);
1009*06c3fb27SDimitry Andric   IgnoreObjectResult res = IgnoreObject(p);
101068d75effSDimitry Andric   if (res == kIgnoreObjectInvalid)
1011fcaf7f86SDimitry Andric     VReport(1, "__lsan_ignore_object(): no heap object found at %p\n", p);
101268d75effSDimitry Andric   if (res == kIgnoreObjectAlreadyIgnored)
10130eae32dcSDimitry Andric     VReport(1,
10140eae32dcSDimitry Andric             "__lsan_ignore_object(): "
10150eae32dcSDimitry Andric             "heap object at %p is already being ignored\n",
10160eae32dcSDimitry Andric             p);
101768d75effSDimitry Andric   if (res == kIgnoreObjectSuccess)
101868d75effSDimitry Andric     VReport(1, "__lsan_ignore_object(): ignoring heap object at %p\n", p);
101968d75effSDimitry Andric #endif  // CAN_SANITIZE_LEAKS
102068d75effSDimitry Andric }
102168d75effSDimitry Andric 
102268d75effSDimitry Andric SANITIZER_INTERFACE_ATTRIBUTE
102368d75effSDimitry Andric void __lsan_register_root_region(const void *begin, uptr size) {
102468d75effSDimitry Andric #if CAN_SANITIZE_LEAKS
1025349cc55cSDimitry Andric   VReport(1, "Registered root region at %p of size %zu\n", begin, size);
1026*06c3fb27SDimitry Andric   uptr b = reinterpret_cast<uptr>(begin);
1027*06c3fb27SDimitry Andric   uptr e = b + size;
1028*06c3fb27SDimitry Andric   CHECK_LT(b, e);
1029*06c3fb27SDimitry Andric 
1030*06c3fb27SDimitry Andric   Lock l(&global_mutex);
1031*06c3fb27SDimitry Andric   ++GetRootRegionsLocked()[{b, e}];
103268d75effSDimitry Andric #endif  // CAN_SANITIZE_LEAKS
103368d75effSDimitry Andric }
103468d75effSDimitry Andric 
103568d75effSDimitry Andric SANITIZER_INTERFACE_ATTRIBUTE
103668d75effSDimitry Andric void __lsan_unregister_root_region(const void *begin, uptr size) {
103768d75effSDimitry Andric #if CAN_SANITIZE_LEAKS
1038*06c3fb27SDimitry Andric   uptr b = reinterpret_cast<uptr>(begin);
1039*06c3fb27SDimitry Andric   uptr e = b + size;
1040*06c3fb27SDimitry Andric   CHECK_LT(b, e);
1041349cc55cSDimitry Andric   VReport(1, "Unregistered root region at %p of size %zu\n", begin, size);
1042*06c3fb27SDimitry Andric 
1043*06c3fb27SDimitry Andric   {
1044*06c3fb27SDimitry Andric     Lock l(&global_mutex);
1045*06c3fb27SDimitry Andric     if (auto *f = GetRootRegionsLocked().find({b, e})) {
1046*06c3fb27SDimitry Andric       if (--(f->second) == 0)
1047*06c3fb27SDimitry Andric         GetRootRegionsLocked().erase(f);
1048*06c3fb27SDimitry Andric       return;
104968d75effSDimitry Andric     }
105068d75effSDimitry Andric   }
105168d75effSDimitry Andric   Report(
1052349cc55cSDimitry Andric       "__lsan_unregister_root_region(): region at %p of size %zu has not "
105368d75effSDimitry Andric       "been registered.\n",
105468d75effSDimitry Andric       begin, size);
105568d75effSDimitry Andric   Die();
105668d75effSDimitry Andric #endif  // CAN_SANITIZE_LEAKS
105768d75effSDimitry Andric }
105868d75effSDimitry Andric 
105968d75effSDimitry Andric SANITIZER_INTERFACE_ATTRIBUTE
106068d75effSDimitry Andric void __lsan_disable() {
106168d75effSDimitry Andric #if CAN_SANITIZE_LEAKS
106268d75effSDimitry Andric   __lsan::DisableInThisThread();
106368d75effSDimitry Andric #endif
106468d75effSDimitry Andric }
106568d75effSDimitry Andric 
106668d75effSDimitry Andric SANITIZER_INTERFACE_ATTRIBUTE
106768d75effSDimitry Andric void __lsan_enable() {
106868d75effSDimitry Andric #if CAN_SANITIZE_LEAKS
106968d75effSDimitry Andric   __lsan::EnableInThisThread();
107068d75effSDimitry Andric #endif
107168d75effSDimitry Andric }
107268d75effSDimitry Andric 
107368d75effSDimitry Andric SANITIZER_INTERFACE_ATTRIBUTE
107468d75effSDimitry Andric void __lsan_do_leak_check() {
107568d75effSDimitry Andric #if CAN_SANITIZE_LEAKS
107668d75effSDimitry Andric   if (common_flags()->detect_leaks)
107768d75effSDimitry Andric     __lsan::DoLeakCheck();
107868d75effSDimitry Andric #endif  // CAN_SANITIZE_LEAKS
107968d75effSDimitry Andric }
108068d75effSDimitry Andric 
108168d75effSDimitry Andric SANITIZER_INTERFACE_ATTRIBUTE
108268d75effSDimitry Andric int __lsan_do_recoverable_leak_check() {
108368d75effSDimitry Andric #if CAN_SANITIZE_LEAKS
108468d75effSDimitry Andric   if (common_flags()->detect_leaks)
108568d75effSDimitry Andric     return __lsan::DoRecoverableLeakCheck();
108668d75effSDimitry Andric #endif  // CAN_SANITIZE_LEAKS
108768d75effSDimitry Andric   return 0;
108868d75effSDimitry Andric }
108968d75effSDimitry Andric 
1090e8d8bef9SDimitry Andric SANITIZER_INTERFACE_WEAK_DEF(const char *, __lsan_default_options, void) {
109168d75effSDimitry Andric   return "";
109268d75effSDimitry Andric }
109368d75effSDimitry Andric 
1094e8d8bef9SDimitry Andric #if !SANITIZER_SUPPORTS_WEAK_HOOKS
109581ad6265SDimitry Andric SANITIZER_INTERFACE_WEAK_DEF(int, __lsan_is_turned_off, void) {
109668d75effSDimitry Andric   return 0;
109768d75effSDimitry Andric }
109868d75effSDimitry Andric 
109981ad6265SDimitry Andric SANITIZER_INTERFACE_WEAK_DEF(const char *, __lsan_default_suppressions, void) {
110068d75effSDimitry Andric   return "";
110168d75effSDimitry Andric }
110268d75effSDimitry Andric #endif
110368d75effSDimitry Andric }  // extern "C"
1104