1 //===-- sanitizer_common.h --------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries.
12 // It declares common functions and classes that are used in both runtimes.
13 // Implementation of some functions are provided in sanitizer_common, while
14 // others must be defined by run-time library itself.
15 //===----------------------------------------------------------------------===//
16 #ifndef SANITIZER_COMMON_H
17 #define SANITIZER_COMMON_H
19 #include "sanitizer_internal_defs.h"
20 #include "sanitizer_libc.h"
21 #include "sanitizer_mutex.h"
23 namespace __sanitizer
{
27 const uptr kWordSize
= SANITIZER_WORDSIZE
/ 8;
28 const uptr kWordSizeInBits
= 8 * kWordSize
;
30 #if defined(__powerpc__) || defined(__powerpc64__)
31 const uptr kCacheLineSize
= 128;
33 const uptr kCacheLineSize
= 64;
36 const uptr kMaxPathLength
= 512;
38 extern const char *SanitizerToolName
; // Can be changed by the tool.
41 uptr
GetPageSizeCached();
42 uptr
GetMmapGranularity();
43 uptr
GetMaxVirtualAddress();
47 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
49 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
50 uptr
*tls_addr
, uptr
*tls_size
);
53 void *MmapOrDie(uptr size
, const char *mem_type
);
54 void UnmapOrDie(void *addr
, uptr size
);
55 void *MmapFixedNoReserve(uptr fixed_addr
, uptr size
);
56 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
);
57 void *Mprotect(uptr fixed_addr
, uptr size
);
58 // Map aligned chunk of address space; size and alignment are powers of two.
59 void *MmapAlignedOrDie(uptr size
, uptr alignment
, const char *mem_type
);
60 // Used to check if we can map shadow memory to a fixed location.
61 bool MemoryRangeIsAvailable(uptr range_start
, uptr range_end
);
62 void FlushUnneededShadowMemory(uptr addr
, uptr size
);
64 // InternalScopedBuffer can be used instead of large stack arrays to
65 // keep frame size low.
66 // FIXME: use InternalAlloc instead of MmapOrDie once
67 // InternalAlloc is made libc-free.
69 class InternalScopedBuffer
{
71 explicit InternalScopedBuffer(uptr cnt
) {
73 ptr_
= (T
*)MmapOrDie(cnt
* sizeof(T
), "InternalScopedBuffer");
75 ~InternalScopedBuffer() {
76 UnmapOrDie(ptr_
, cnt_
* sizeof(T
));
78 T
&operator[](uptr i
) { return ptr_
[i
]; }
79 T
*data() { return ptr_
; }
80 uptr
size() { return cnt_
* sizeof(T
); }
85 // Disallow evil constructors.
86 InternalScopedBuffer(const InternalScopedBuffer
&);
87 void operator=(const InternalScopedBuffer
&);
90 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
91 // constructor, so all instances of LowLevelAllocator should be
92 // linker initialized.
93 class LowLevelAllocator
{
95 // Requires an external lock.
96 void *Allocate(uptr size
);
99 char *allocated_current_
;
101 typedef void (*LowLevelAllocateCallback
)(uptr ptr
, uptr size
);
102 // Allows to register tool-specific callbacks for LowLevelAllocator.
103 // Passing NULL removes the callback.
104 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback
);
107 void RawWrite(const char *buffer
);
109 // Caching version of PrintsToTty(). Not thread-safe.
110 bool PrintsToTtyCached();
111 void Printf(const char *format
, ...);
112 void Report(const char *format
, ...);
113 void SetPrintfAndReportCallback(void (*callback
)(const char *));
114 // Can be used to prevent mixing error reports from different sanitizers.
115 extern StaticSpinMutex CommonSanitizerReportMutex
;
116 void MaybeOpenReportFile();
117 extern fd_t report_fd
;
118 extern bool log_to_file
;
119 extern char report_path_prefix
[4096];
120 extern uptr report_fd_pid
;
122 uptr
OpenFile(const char *filename
, bool write
);
123 // Opens the file 'file_name" and reads up to 'max_len' bytes.
124 // The resulting buffer is mmaped and stored in '*buff'.
125 // The size of the mmaped region is stored in '*buff_size',
126 // Returns the number of read bytes or 0 if file can not be opened.
127 uptr
ReadFileToBuffer(const char *file_name
, char **buff
,
128 uptr
*buff_size
, uptr max_len
);
129 // Maps given file to virtual memory, and returns pointer to it
130 // (or NULL if the mapping failes). Stores the size of mmaped region
132 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
);
134 // Error report formatting.
135 const char *StripPathPrefix(const char *filepath
,
136 const char *strip_file_prefix
);
137 void PrintSourceLocation(const char *file
, int line
, int column
);
138 void PrintModuleAndOffset(const char *module
, uptr offset
);
142 void DisableCoreDumper();
143 void DumpProcessMap();
144 bool FileExists(const char *filename
);
145 const char *GetEnv(const char *name
);
146 bool SetEnv(const char *name
, const char *value
);
147 const char *GetPwd();
148 char *FindPathToBinary(const char *name
);
151 bool StackSizeIsUnlimited();
152 void SetStackSizeLimitInBytes(uptr limit
);
153 void PrepareForSandboxing();
159 void SleepForSeconds(int seconds
);
160 void SleepForMillis(int millis
);
162 int Atexit(void (*function
)(void));
163 void SortArray(uptr
*array
, uptr size
);
166 void NORETURN
Abort();
169 CheckFailed(const char *file
, int line
, const char *cond
, u64 v1
, u64 v2
);
171 // Set the name of the current thread to 'name', return true on succees.
172 // The name may be truncated to a system-dependent limit.
173 bool SanitizerSetThreadName(const char *name
);
174 // Get the name of the current thread (no more than max_len bytes),
175 // return true on succees. name should have space for at least max_len+1 bytes.
176 bool SanitizerGetThreadName(char *name
, int max_len
);
178 // Specific tools may override behavior of "Die" and "CheckFailed" functions
179 // to do tool-specific job.
180 typedef void (*DieCallbackType
)(void);
181 void SetDieCallback(DieCallbackType
);
182 DieCallbackType
GetDieCallback();
183 typedef void (*CheckFailedCallbackType
)(const char *, int, const char *,
185 void SetCheckFailedCallback(CheckFailedCallbackType callback
);
187 // Construct a one-line string like
188 // SanitizerToolName: error_type file:line function
189 // and call __sanitizer_report_error_summary on it.
190 void ReportErrorSummary(const char *error_type
, const char *file
,
191 int line
, const char *function
);
194 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
196 unsigned char _BitScanForward(unsigned long *index
, unsigned long mask
); // NOLINT
197 unsigned char _BitScanReverse(unsigned long *index
, unsigned long mask
); // NOLINT
199 unsigned char _BitScanForward64(unsigned long *index
, unsigned __int64 mask
); // NOLINT
200 unsigned char _BitScanReverse64(unsigned long *index
, unsigned __int64 mask
); // NOLINT
205 INLINE uptr
MostSignificantSetBitIndex(uptr x
) {
207 unsigned long up
; // NOLINT
208 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
209 up
= SANITIZER_WORDSIZE
- 1 - __builtin_clzl(x
);
210 #elif defined(_WIN64)
211 _BitScanReverse64(&up
, x
);
213 _BitScanReverse(&up
, x
);
218 INLINE
bool IsPowerOfTwo(uptr x
) {
219 return (x
& (x
- 1)) == 0;
222 INLINE uptr
RoundUpToPowerOfTwo(uptr size
) {
224 if (IsPowerOfTwo(size
)) return size
;
226 uptr up
= MostSignificantSetBitIndex(size
);
227 CHECK(size
< (1ULL << (up
+ 1)));
228 CHECK(size
> (1ULL << up
));
229 return 1UL << (up
+ 1);
232 INLINE uptr
RoundUpTo(uptr size
, uptr boundary
) {
233 CHECK(IsPowerOfTwo(boundary
));
234 return (size
+ boundary
- 1) & ~(boundary
- 1);
237 INLINE uptr
RoundDownTo(uptr x
, uptr boundary
) {
238 return x
& ~(boundary
- 1);
241 INLINE
bool IsAligned(uptr a
, uptr alignment
) {
242 return (a
& (alignment
- 1)) == 0;
245 INLINE uptr
Log2(uptr x
) {
246 CHECK(IsPowerOfTwo(x
));
247 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
248 return __builtin_ctzl(x
);
249 #elif defined(_WIN64)
250 unsigned long ret
; // NOLINT
251 _BitScanForward64(&ret
, x
);
254 unsigned long ret
; // NOLINT
255 _BitScanForward(&ret
, x
);
260 // Don't use std::min, std::max or std::swap, to minimize dependency
262 template<class T
> T
Min(T a
, T b
) { return a
< b
? a
: b
; }
263 template<class T
> T
Max(T a
, T b
) { return a
> b
? a
: b
; }
264 template<class T
> void Swap(T
& a
, T
& b
) {
271 INLINE
bool IsSpace(int c
) {
272 return (c
== ' ') || (c
== '\n') || (c
== '\t') ||
273 (c
== '\f') || (c
== '\r') || (c
== '\v');
275 INLINE
bool IsDigit(int c
) {
276 return (c
>= '0') && (c
<= '9');
278 INLINE
int ToLower(int c
) {
279 return (c
>= 'A' && c
<= 'Z') ? (c
+ 'a' - 'A') : c
;
282 #if SANITIZER_WORDSIZE == 64
283 # define FIRST_32_SECOND_64(a, b) (b)
285 # define FIRST_32_SECOND_64(a, b) (a)
288 // A low-level vector based on mmap. May incur a significant memory overhead for
290 // WARNING: The current implementation supports only POD types.
292 class InternalMmapVector
{
294 explicit InternalMmapVector(uptr initial_capacity
) {
295 CHECK_GT(initial_capacity
, 0);
296 capacity_
= initial_capacity
;
298 data_
= (T
*)MmapOrDie(capacity_
* sizeof(T
), "InternalMmapVector");
300 ~InternalMmapVector() {
301 UnmapOrDie(data_
, capacity_
* sizeof(T
));
303 T
&operator[](uptr i
) {
307 const T
&operator[](uptr i
) const {
311 void push_back(const T
&element
) {
312 CHECK_LE(size_
, capacity_
);
313 if (size_
== capacity_
) {
314 uptr new_capacity
= RoundUpToPowerOfTwo(size_
+ 1);
315 Resize(new_capacity
);
317 data_
[size_
++] = element
;
321 return data_
[size_
- 1];
330 const T
*data() const {
333 uptr
capacity() const {
338 void Resize(uptr new_capacity
) {
339 CHECK_GT(new_capacity
, 0);
340 CHECK_LE(size_
, new_capacity
);
341 T
*new_data
= (T
*)MmapOrDie(new_capacity
* sizeof(T
),
342 "InternalMmapVector");
343 internal_memcpy(new_data
, data_
, size_
* sizeof(T
));
346 UnmapOrDie(old_data
, capacity_
* sizeof(T
));
347 capacity_
= new_capacity
;
349 // Disallow evil constructors.
350 InternalMmapVector(const InternalMmapVector
&);
351 void operator=(const InternalMmapVector
&);
358 // HeapSort for arrays and InternalMmapVector.
359 template<class Container
, class Compare
>
360 void InternalSort(Container
*v
, uptr size
, Compare comp
) {
363 // Stage 1: insert elements to the heap.
364 for (uptr i
= 1; i
< size
; i
++) {
366 for (j
= i
; j
> 0; j
= p
) {
368 if (comp((*v
)[p
], (*v
)[j
]))
369 Swap((*v
)[j
], (*v
)[p
]);
374 // Stage 2: swap largest element with the last one,
375 // and sink the new top.
376 for (uptr i
= size
- 1; i
> 0; i
--) {
377 Swap((*v
)[0], (*v
)[i
]);
379 for (j
= 0; j
< i
; j
= max_ind
) {
380 uptr left
= 2 * j
+ 1;
381 uptr right
= 2 * j
+ 2;
383 if (left
< i
&& comp((*v
)[max_ind
], (*v
)[left
]))
385 if (right
< i
&& comp((*v
)[max_ind
], (*v
)[right
]))
388 Swap((*v
)[j
], (*v
)[max_ind
]);
395 template<class Container
, class Value
, class Compare
>
396 uptr
InternalBinarySearch(const Container
&v
, uptr first
, uptr last
,
397 const Value
&val
, Compare comp
) {
398 uptr not_found
= last
+ 1;
399 while (last
>= first
) {
400 uptr mid
= (first
+ last
) / 2;
401 if (comp(v
[mid
], val
))
403 else if (comp(val
, v
[mid
]))
411 // Represents a binary loaded into virtual memory (e.g. this can be an
412 // executable or a shared object).
415 LoadedModule(const char *module_name
, uptr base_address
);
416 void addAddressRange(uptr beg
, uptr end
);
417 bool containsAddress(uptr address
) const;
419 const char *full_name() const { return full_name_
; }
420 uptr
base_address() const { return base_address_
; }
423 struct AddressRange
{
429 static const uptr kMaxNumberOfAddressRanges
= 6;
430 AddressRange ranges_
[kMaxNumberOfAddressRanges
];
434 // OS-dependent function that fills array with descriptions of at most
435 // "max_modules" currently loaded modules. Returns the number of
436 // initialized modules. If filter is nonzero, ignores modules for which
437 // filter(full_name) is false.
438 typedef bool (*string_predicate_t
)(const char *);
439 uptr
GetListOfModules(LoadedModule
*modules
, uptr max_modules
,
440 string_predicate_t filter
);
443 const uptr kPthreadDestructorIterations
= 4;
445 // Unused on Windows.
446 const uptr kPthreadDestructorIterations
= 0;
449 // Callback type for iterating over a set of memory ranges.
450 typedef void (*RangeIteratorCallback
)(uptr begin
, uptr end
, void *arg
);
451 } // namespace __sanitizer
453 #endif // SANITIZER_COMMON_H