1//=-- lsan_common.h -------------------------------------------------------===//
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// Private LSan header.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LSAN_COMMON_H
15#define LSAN_COMMON_H
16
17#include "sanitizer_common/sanitizer_allocator.h"
18#include "sanitizer_common/sanitizer_common.h"
19#include "sanitizer_common/sanitizer_internal_defs.h"
20#include "sanitizer_common/sanitizer_platform.h"
21#include "sanitizer_common/sanitizer_stoptheworld.h"
22#include "sanitizer_common/sanitizer_symbolizer.h"
23
24// LeakSanitizer relies on some Glibc's internals (e.g. TLS machinery) on Linux.
25// Also, LSan doesn't like 32 bit architectures
26// because of "small" (4 bytes) pointer size that leads to high false negative
27// ratio on large leaks. But we still want to have it for some 32 bit arches
28// (e.g. x86), see https://github.com/google/sanitizers/issues/403.
29// To enable LeakSanitizer on a new architecture, one needs to implement the
30// internal_clone function as well as (probably) adjust the TLS machinery for
31// the new architecture inside the sanitizer library.
32#if (SANITIZER_LINUX && !SANITIZER_ANDROID || SANITIZER_MAC) && \
33    (SANITIZER_WORDSIZE == 64) &&                               \
34    (defined(__x86_64__) || defined(__mips64) || defined(__aarch64__) || \
35     defined(__powerpc64__))
36#define CAN_SANITIZE_LEAKS 1
37#elif defined(__i386__) && \
38    (SANITIZER_LINUX && !SANITIZER_ANDROID || SANITIZER_MAC)
39#define CAN_SANITIZE_LEAKS 1
40#elif defined(__arm__) && \
41    SANITIZER_LINUX && !SANITIZER_ANDROID
42#define CAN_SANITIZE_LEAKS 1
43#elif SANITIZER_NETBSD
44#define CAN_SANITIZE_LEAKS 1
45#else
46#define CAN_SANITIZE_LEAKS 0
47#endif
48
49namespace __sanitizer {
50class FlagParser;
51class ThreadRegistry;
52struct DTLS;
53}
54
55namespace __lsan {
56
57// Chunk tags.
58enum ChunkTag {
59  kDirectlyLeaked = 0,  // default
60  kIndirectlyLeaked = 1,
61  kReachable = 2,
62  kIgnored = 3
63};
64
65const u32 kInvalidTid = (u32) -1;
66
67struct Flags {
68#define LSAN_FLAG(Type, Name, DefaultValue, Description) Type Name;
69#include "lsan_flags.inc"
70#undef LSAN_FLAG
71
72  void SetDefaults();
73  uptr pointer_alignment() const {
74    return use_unaligned ? 1 : sizeof(uptr);
75  }
76};
77
78extern Flags lsan_flags;
79inline Flags *flags() { return &lsan_flags; }
80void RegisterLsanFlags(FlagParser *parser, Flags *f);
81
82struct Leak {
83  u32 id;
84  uptr hit_count;
85  uptr total_size;
86  u32 stack_trace_id;
87  bool is_directly_leaked;
88  bool is_suppressed;
89};
90
91struct LeakedObject {
92  u32 leak_id;
93  uptr addr;
94  uptr size;
95};
96
97// Aggregates leaks by stack trace prefix.
98class LeakReport {
99 public:
100  LeakReport() {}
101  void AddLeakedChunk(uptr chunk, u32 stack_trace_id, uptr leaked_size,
102                      ChunkTag tag);
103  void ReportTopLeaks(uptr max_leaks);
104  void PrintSummary();
105  void ApplySuppressions();
106  uptr UnsuppressedLeakCount();
107
108 private:
109  void PrintReportForLeak(uptr index);
110  void PrintLeakedObjectsForLeak(uptr index);
111
112  u32 next_id_ = 0;
113  InternalMmapVector<Leak> leaks_;
114  InternalMmapVector<LeakedObject> leaked_objects_;
115};
116
117typedef InternalMmapVector<uptr> Frontier;
118
119// Platform-specific functions.
120void InitializePlatformSpecificModules();
121void ProcessGlobalRegions(Frontier *frontier);
122void ProcessPlatformSpecificAllocations(Frontier *frontier);
123
124struct RootRegion {
125  uptr begin;
126  uptr size;
127};
128
129InternalMmapVector<RootRegion> const *GetRootRegions();
130void ScanRootRegion(Frontier *frontier, RootRegion const &region,
131                    uptr region_begin, uptr region_end, bool is_readable);
132// Run stoptheworld while holding any platform-specific locks, as well as the
133// allocator and thread registry locks.
134void LockStuffAndStopTheWorld(StopTheWorldCallback callback, void* argument);
135
136void ScanRangeForPointers(uptr begin, uptr end,
137                          Frontier *frontier,
138                          const char *region_type, ChunkTag tag);
139void ScanGlobalRange(uptr begin, uptr end, Frontier *frontier);
140
141enum IgnoreObjectResult {
142  kIgnoreObjectSuccess,
143  kIgnoreObjectAlreadyIgnored,
144  kIgnoreObjectInvalid
145};
146
147// Functions called from the parent tool.
148const char *MaybeCallLsanDefaultOptions();
149void InitCommonLsan();
150void DoLeakCheck();
151void DoRecoverableLeakCheckVoid();
152void DisableCounterUnderflow();
153bool DisabledInThisThread();
154
155// Used to implement __lsan::ScopedDisabler.
156void DisableInThisThread();
157void EnableInThisThread();
158// Can be used to ignore memory allocated by an intercepted
159// function.
160struct ScopedInterceptorDisabler {
161  ScopedInterceptorDisabler() { DisableInThisThread(); }
162  ~ScopedInterceptorDisabler() { EnableInThisThread(); }
163};
164
165// According to Itanium C++ ABI array cookie is a one word containing
166// size of allocated array.
167static inline bool IsItaniumABIArrayCookie(uptr chunk_beg, uptr chunk_size,
168                                           uptr addr) {
169  return chunk_size == sizeof(uptr) && chunk_beg + chunk_size == addr &&
170         *reinterpret_cast<uptr *>(chunk_beg) == 0;
171}
172
173// According to ARM C++ ABI array cookie consists of two words:
174// struct array_cookie {
175//   std::size_t element_size; // element_size != 0
176//   std::size_t element_count;
177// };
178static inline bool IsARMABIArrayCookie(uptr chunk_beg, uptr chunk_size,
179                                       uptr addr) {
180  return chunk_size == 2 * sizeof(uptr) && chunk_beg + chunk_size == addr &&
181         *reinterpret_cast<uptr *>(chunk_beg + sizeof(uptr)) == 0;
182}
183
184// Special case for "new T[0]" where T is a type with DTOR.
185// new T[0] will allocate a cookie (one or two words) for the array size (0)
186// and store a pointer to the end of allocated chunk. The actual cookie layout
187// varies between platforms according to their C++ ABI implementation.
188inline bool IsSpecialCaseOfOperatorNew0(uptr chunk_beg, uptr chunk_size,
189                                        uptr addr) {
190#if defined(__arm__)
191  return IsARMABIArrayCookie(chunk_beg, chunk_size, addr);
192#else
193  return IsItaniumABIArrayCookie(chunk_beg, chunk_size, addr);
194#endif
195}
196
197// The following must be implemented in the parent tool.
198
199void ForEachChunk(ForEachChunkCallback callback, void *arg);
200// Returns the address range occupied by the global allocator object.
201void GetAllocatorGlobalRange(uptr *begin, uptr *end);
202// Wrappers for allocator's ForceLock()/ForceUnlock().
203void LockAllocator();
204void UnlockAllocator();
205// Returns true if [addr, addr + sizeof(void *)) is poisoned.
206bool WordIsPoisoned(uptr addr);
207// Wrappers for ThreadRegistry access.
208void LockThreadRegistry();
209void UnlockThreadRegistry();
210ThreadRegistry *GetThreadRegistryLocked();
211bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
212                           uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
213                           uptr *cache_end, DTLS **dtls);
214void ForEachExtraStackRange(tid_t os_id, RangeIteratorCallback callback,
215                            void *arg);
216// If called from the main thread, updates the main thread's TID in the thread
217// registry. We need this to handle processes that fork() without a subsequent
218// exec(), which invalidates the recorded TID. To update it, we must call
219// gettid() from the main thread. Our solution is to call this function before
220// leak checking and also before every call to pthread_create() (to handle cases
221// where leak checking is initiated from a non-main thread).
222void EnsureMainThreadIDIsCorrect();
223// If p points into a chunk that has been allocated to the user, returns its
224// user-visible address. Otherwise, returns 0.
225uptr PointsIntoChunk(void *p);
226// Returns address of user-visible chunk contained in this allocator chunk.
227uptr GetUserBegin(uptr chunk);
228// Helper for __lsan_ignore_object().
229IgnoreObjectResult IgnoreObjectLocked(const void *p);
230
231// Return the linker module, if valid for the platform.
232LoadedModule *GetLinker();
233
234// Return true if LSan has finished leak checking and reported leaks.
235bool HasReportedLeaks();
236
237// Run platform-specific leak handlers.
238void HandleLeaks();
239
240// Wrapper for chunk metadata operations.
241class LsanMetadata {
242 public:
243  // Constructor accepts address of user-visible chunk.
244  explicit LsanMetadata(uptr chunk);
245  bool allocated() const;
246  ChunkTag tag() const;
247  void set_tag(ChunkTag value);
248  uptr requested_size() const;
249  u32 stack_trace_id() const;
250 private:
251  void *metadata_;
252};
253
254}  // namespace __lsan
255
256extern "C" {
257SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
258const char *__lsan_default_options();
259
260SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
261int __lsan_is_turned_off();
262
263SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
264const char *__lsan_default_suppressions();
265}  // extern "C"
266
267#endif  // LSAN_COMMON_H
268