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