1 //===-- sanitizer_common.h --------------------------------------*- C++ -*-===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // It declares common functions and classes that are used in both runtimes.
11 // Implementation of some functions are provided in sanitizer_common, while
12 // others must be defined by run-time library itself.
13 //===----------------------------------------------------------------------===//
14 #ifndef SANITIZER_COMMON_H
15 #define SANITIZER_COMMON_H
17 #include "sanitizer_internal_defs.h"
19 namespace __sanitizer
{
23 const uptr kWordSize
= SANITIZER_WORDSIZE
/ 8;
24 const uptr kWordSizeInBits
= 8 * kWordSize
;
26 #if defined(__powerpc__) || defined(__powerpc64__)
27 const uptr kCacheLineSize
= 128;
29 const uptr kCacheLineSize
= 64;
32 extern const char *SanitizerToolName
; // Can be changed by the tool.
35 uptr
GetPageSizeCached();
36 uptr
GetMmapGranularity();
41 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
45 void *MmapOrDie(uptr size
, const char *mem_type
);
46 void UnmapOrDie(void *addr
, uptr size
);
47 void *MmapFixedNoReserve(uptr fixed_addr
, uptr size
);
48 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
);
49 void *Mprotect(uptr fixed_addr
, uptr size
);
50 // Map aligned chunk of address space; size and alignment are powers of two.
51 void *MmapAlignedOrDie(uptr size
, uptr alignment
, const char *mem_type
);
52 // Used to check if we can map shadow memory to a fixed location.
53 bool MemoryRangeIsAvailable(uptr range_start
, uptr range_end
);
54 void FlushUnneededShadowMemory(uptr addr
, uptr size
);
57 void *InternalAlloc(uptr size
);
58 void InternalFree(void *p
);
60 // InternalScopedBuffer can be used instead of large stack arrays to
61 // keep frame size low.
62 // FIXME: use InternalAlloc instead of MmapOrDie once
63 // InternalAlloc is made libc-free.
65 class InternalScopedBuffer
{
67 explicit InternalScopedBuffer(uptr cnt
) {
69 ptr_
= (T
*)MmapOrDie(cnt
* sizeof(T
), "InternalScopedBuffer");
71 ~InternalScopedBuffer() {
72 UnmapOrDie(ptr_
, cnt_
* sizeof(T
));
74 T
&operator[](uptr i
) { return ptr_
[i
]; }
75 T
*data() { return ptr_
; }
76 uptr
size() { return cnt_
* sizeof(T
); }
81 // Disallow evil constructors.
82 InternalScopedBuffer(const InternalScopedBuffer
&);
83 void operator=(const InternalScopedBuffer
&);
86 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
87 // constructor, so all instances of LowLevelAllocator should be
88 // linker initialized.
89 class LowLevelAllocator
{
91 // Requires an external lock.
92 void *Allocate(uptr size
);
95 char *allocated_current_
;
97 typedef void (*LowLevelAllocateCallback
)(uptr ptr
, uptr size
);
98 // Allows to register tool-specific callbacks for LowLevelAllocator.
99 // Passing NULL removes the callback.
100 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback
);
103 void RawWrite(const char *buffer
);
105 void Printf(const char *format
, ...);
106 void Report(const char *format
, ...);
107 void SetPrintfAndReportCallback(void (*callback
)(const char *));
109 fd_t
OpenFile(const char *filename
, bool write
);
110 // Opens the file 'file_name" and reads up to 'max_len' bytes.
111 // The resulting buffer is mmaped and stored in '*buff'.
112 // The size of the mmaped region is stored in '*buff_size',
113 // Returns the number of read bytes or 0 if file can not be opened.
114 uptr
ReadFileToBuffer(const char *file_name
, char **buff
,
115 uptr
*buff_size
, uptr max_len
);
116 // Maps given file to virtual memory, and returns pointer to it
117 // (or NULL if the mapping failes). Stores the size of mmaped region
119 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
);
122 void DisableCoreDumper();
123 void DumpProcessMap();
124 bool FileExists(const char *filename
);
125 const char *GetEnv(const char *name
);
126 const char *GetPwd();
129 bool StackSizeIsUnlimited();
130 void SetStackSizeLimitInBytes(uptr limit
);
131 void PrepareForSandboxing();
134 void SleepForSeconds(int seconds
);
135 void SleepForMillis(int millis
);
136 int Atexit(void (*function
)(void));
137 void SortArray(uptr
*array
, uptr size
);
140 void NORETURN
Abort();
142 void NORETURN SANITIZER_INTERFACE_ATTRIBUTE
143 CheckFailed(const char *file
, int line
, const char *cond
, u64 v1
, u64 v2
);
145 // Set the name of the current thread to 'name', return true on succees.
146 // The name may be truncated to a system-dependent limit.
147 bool SanitizerSetThreadName(const char *name
);
148 // Get the name of the current thread (no more than max_len bytes),
149 // return true on succees. name should have space for at least max_len+1 bytes.
150 bool SanitizerGetThreadName(char *name
, int max_len
);
152 // Specific tools may override behavior of "Die" and "CheckFailed" functions
153 // to do tool-specific job.
154 void SetDieCallback(void (*callback
)(void));
155 typedef void (*CheckFailedCallbackType
)(const char *, int, const char *,
157 void SetCheckFailedCallback(CheckFailedCallbackType callback
);
159 // Construct a one-line string like
160 // SanitizerToolName: error_type file:line function
161 // and call __sanitizer_report_error_summary on it.
162 void ReportErrorSummary(const char *error_type
, const char *file
,
163 int line
, const char *function
);
166 #if defined(_WIN32) && !defined(__clang__)
168 unsigned char _BitScanForward(unsigned long *index
, unsigned long mask
); // NOLINT
169 unsigned char _BitScanReverse(unsigned long *index
, unsigned long mask
); // NOLINT
171 unsigned char _BitScanForward64(unsigned long *index
, unsigned __int64 mask
); // NOLINT
172 unsigned char _BitScanReverse64(unsigned long *index
, unsigned __int64 mask
); // NOLINT
177 INLINE uptr
MostSignificantSetBitIndex(uptr x
) {
179 unsigned long up
; // NOLINT
180 #if !defined(_WIN32) || defined(__clang__)
181 up
= SANITIZER_WORDSIZE
- 1 - __builtin_clzl(x
);
182 #elif defined(_WIN64)
183 _BitScanReverse64(&up
, x
);
185 _BitScanReverse(&up
, x
);
190 INLINE
bool IsPowerOfTwo(uptr x
) {
191 return (x
& (x
- 1)) == 0;
194 INLINE uptr
RoundUpToPowerOfTwo(uptr size
) {
196 if (IsPowerOfTwo(size
)) return size
;
198 uptr up
= MostSignificantSetBitIndex(size
);
199 CHECK(size
< (1ULL << (up
+ 1)));
200 CHECK(size
> (1ULL << up
));
201 return 1UL << (up
+ 1);
204 INLINE uptr
RoundUpTo(uptr size
, uptr boundary
) {
205 CHECK(IsPowerOfTwo(boundary
));
206 return (size
+ boundary
- 1) & ~(boundary
- 1);
209 INLINE uptr
RoundDownTo(uptr x
, uptr boundary
) {
210 return x
& ~(boundary
- 1);
213 INLINE
bool IsAligned(uptr a
, uptr alignment
) {
214 return (a
& (alignment
- 1)) == 0;
217 INLINE uptr
Log2(uptr x
) {
218 CHECK(IsPowerOfTwo(x
));
219 #if !defined(_WIN32) || defined(__clang__)
220 return __builtin_ctzl(x
);
221 #elif defined(_WIN64)
222 unsigned long ret
; // NOLINT
223 _BitScanForward64(&ret
, x
);
226 unsigned long ret
; // NOLINT
227 _BitScanForward(&ret
, x
);
232 // Don't use std::min, std::max or std::swap, to minimize dependency
234 template<class T
> T
Min(T a
, T b
) { return a
< b
? a
: b
; }
235 template<class T
> T
Max(T a
, T b
) { return a
> b
? a
: b
; }
236 template<class T
> void Swap(T
& a
, T
& b
) {
243 INLINE
bool IsSpace(int c
) {
244 return (c
== ' ') || (c
== '\n') || (c
== '\t') ||
245 (c
== '\f') || (c
== '\r') || (c
== '\v');
247 INLINE
bool IsDigit(int c
) {
248 return (c
>= '0') && (c
<= '9');
250 INLINE
int ToLower(int c
) {
251 return (c
>= 'A' && c
<= 'Z') ? (c
+ 'a' - 'A') : c
;
254 #if SANITIZER_WORDSIZE == 64
255 # define FIRST_32_SECOND_64(a, b) (b)
257 # define FIRST_32_SECOND_64(a, b) (a)
260 } // namespace __sanitizer
262 #endif // SANITIZER_COMMON_H