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