xref: /freebsd/contrib/llvm-project/compiler-rt/lib/lsan/lsan_common.h (revision 7029da5c36f2d3cf6bb6c81bf551229f416399e8)
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 
49 namespace __sanitizer {
50 class FlagParser;
51 class ThreadRegistry;
52 struct DTLS;
53 }
54 
55 namespace __lsan {
56 
57 // Chunk tags.
58 enum ChunkTag {
59   kDirectlyLeaked = 0,  // default
60   kIndirectlyLeaked = 1,
61   kReachable = 2,
62   kIgnored = 3
63 };
64 
65 const u32 kInvalidTid = (u32) -1;
66 
67 struct 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 
78 extern Flags lsan_flags;
79 inline Flags *flags() { return &lsan_flags; }
80 void RegisterLsanFlags(FlagParser *parser, Flags *f);
81 
82 struct 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 
91 struct LeakedObject {
92   u32 leak_id;
93   uptr addr;
94   uptr size;
95 };
96 
97 // Aggregates leaks by stack trace prefix.
98 class 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 
117 typedef InternalMmapVector<uptr> Frontier;
118 
119 // Platform-specific functions.
120 void InitializePlatformSpecificModules();
121 void ProcessGlobalRegions(Frontier *frontier);
122 void ProcessPlatformSpecificAllocations(Frontier *frontier);
123 
124 struct RootRegion {
125   uptr begin;
126   uptr size;
127 };
128 
129 InternalMmapVector<RootRegion> const *GetRootRegions();
130 void 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.
133 void DoStopTheWorld(StopTheWorldCallback callback, void* argument);
134 
135 void ScanRangeForPointers(uptr begin, uptr end,
136                           Frontier *frontier,
137                           const char *region_type, ChunkTag tag);
138 void ScanGlobalRange(uptr begin, uptr end, Frontier *frontier);
139 
140 enum IgnoreObjectResult {
141   kIgnoreObjectSuccess,
142   kIgnoreObjectAlreadyIgnored,
143   kIgnoreObjectInvalid
144 };
145 
146 // Functions called from the parent tool.
147 const char *MaybeCallLsanDefaultOptions();
148 void InitCommonLsan();
149 void DoLeakCheck();
150 void DoRecoverableLeakCheckVoid();
151 void DisableCounterUnderflow();
152 bool DisabledInThisThread();
153 
154 // Used to implement __lsan::ScopedDisabler.
155 void DisableInThisThread();
156 void EnableInThisThread();
157 // Can be used to ignore memory allocated by an intercepted
158 // function.
159 struct ScopedInterceptorDisabler {
160   ScopedInterceptorDisabler() { DisableInThisThread(); }
161   ~ScopedInterceptorDisabler() { EnableInThisThread(); }
162 };
163 
164 // According to Itanium C++ ABI array cookie is a one word containing
165 // size of allocated array.
166 static inline bool IsItaniumABIArrayCookie(uptr chunk_beg, uptr chunk_size,
167                                            uptr addr) {
168   return chunk_size == sizeof(uptr) && chunk_beg + chunk_size == addr &&
169          *reinterpret_cast<uptr *>(chunk_beg) == 0;
170 }
171 
172 // According to ARM C++ ABI array cookie consists of two words:
173 // struct array_cookie {
174 //   std::size_t element_size; // element_size != 0
175 //   std::size_t element_count;
176 // };
177 static inline bool IsARMABIArrayCookie(uptr chunk_beg, uptr chunk_size,
178                                        uptr addr) {
179   return chunk_size == 2 * sizeof(uptr) && chunk_beg + chunk_size == addr &&
180          *reinterpret_cast<uptr *>(chunk_beg + sizeof(uptr)) == 0;
181 }
182 
183 // Special case for "new T[0]" where T is a type with DTOR.
184 // new T[0] will allocate a cookie (one or two words) for the array size (0)
185 // and store a pointer to the end of allocated chunk. The actual cookie layout
186 // varies between platforms according to their C++ ABI implementation.
187 inline bool IsSpecialCaseOfOperatorNew0(uptr chunk_beg, uptr chunk_size,
188                                         uptr addr) {
189 #if defined(__arm__)
190   return IsARMABIArrayCookie(chunk_beg, chunk_size, addr);
191 #else
192   return IsItaniumABIArrayCookie(chunk_beg, chunk_size, addr);
193 #endif
194 }
195 
196 // The following must be implemented in the parent tool.
197 
198 void ForEachChunk(ForEachChunkCallback callback, void *arg);
199 // Returns the address range occupied by the global allocator object.
200 void GetAllocatorGlobalRange(uptr *begin, uptr *end);
201 // Wrappers for allocator's ForceLock()/ForceUnlock().
202 void LockAllocator();
203 void UnlockAllocator();
204 // Returns true if [addr, addr + sizeof(void *)) is poisoned.
205 bool WordIsPoisoned(uptr addr);
206 // Wrappers for ThreadRegistry access.
207 void LockThreadRegistry();
208 void UnlockThreadRegistry();
209 ThreadRegistry *GetThreadRegistryLocked();
210 bool GetThreadRangesLocked(tid_t os_id, uptr *stack_begin, uptr *stack_end,
211                            uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
212                            uptr *cache_end, DTLS **dtls);
213 void ForEachExtraStackRange(tid_t os_id, RangeIteratorCallback callback,
214                             void *arg);
215 // If called from the main thread, updates the main thread's TID in the thread
216 // registry. We need this to handle processes that fork() without a subsequent
217 // exec(), which invalidates the recorded TID. To update it, we must call
218 // gettid() from the main thread. Our solution is to call this function before
219 // leak checking and also before every call to pthread_create() (to handle cases
220 // where leak checking is initiated from a non-main thread).
221 void EnsureMainThreadIDIsCorrect();
222 // If p points into a chunk that has been allocated to the user, returns its
223 // user-visible address. Otherwise, returns 0.
224 uptr PointsIntoChunk(void *p);
225 // Returns address of user-visible chunk contained in this allocator chunk.
226 uptr GetUserBegin(uptr chunk);
227 // Helper for __lsan_ignore_object().
228 IgnoreObjectResult IgnoreObjectLocked(const void *p);
229 
230 // Return the linker module, if valid for the platform.
231 LoadedModule *GetLinker();
232 
233 // Return true if LSan has finished leak checking and reported leaks.
234 bool HasReportedLeaks();
235 
236 // Run platform-specific leak handlers.
237 void HandleLeaks();
238 
239 // Wrapper for chunk metadata operations.
240 class LsanMetadata {
241  public:
242   // Constructor accepts address of user-visible chunk.
243   explicit LsanMetadata(uptr chunk);
244   bool allocated() const;
245   ChunkTag tag() const;
246   void set_tag(ChunkTag value);
247   uptr requested_size() const;
248   u32 stack_trace_id() const;
249  private:
250   void *metadata_;
251 };
252 
253 }  // namespace __lsan
254 
255 extern "C" {
256 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
257 const char *__lsan_default_options();
258 
259 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
260 int __lsan_is_turned_off();
261 
262 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
263 const char *__lsan_default_suppressions();
264 }  // extern "C"
265 
266 #endif  // LSAN_COMMON_H
267