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