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"
18 #include "sanitizer_libc.h"
19 #include "sanitizer_mutex.h"
20 #include "sanitizer_flags.h"
22 namespace __sanitizer
{
26 const uptr kWordSize
= SANITIZER_WORDSIZE
/ 8;
27 const uptr kWordSizeInBits
= 8 * kWordSize
;
29 #if defined(__powerpc__) || defined(__powerpc64__)
30 const uptr kCacheLineSize
= 128;
32 const uptr kCacheLineSize
= 64;
35 const uptr kMaxPathLength
= 512;
37 const uptr kMaxThreadStackSize
= 1 << 30; // 1Gb
39 extern const char *SanitizerToolName
; // Can be changed by the tool.
42 uptr
GetPageSizeCached();
43 uptr
GetMmapGranularity();
44 uptr
GetMaxVirtualAddress();
48 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
50 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
51 uptr
*tls_addr
, uptr
*tls_size
);
54 void *MmapOrDie(uptr size
, const char *mem_type
);
55 void UnmapOrDie(void *addr
, uptr size
);
56 void *MmapFixedNoReserve(uptr fixed_addr
, uptr size
);
57 void *MmapNoReserveOrDie(uptr size
, const char *mem_type
);
58 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
);
59 void *Mprotect(uptr fixed_addr
, uptr size
);
60 // Map aligned chunk of address space; size and alignment are powers of two.
61 void *MmapAlignedOrDie(uptr size
, uptr alignment
, const char *mem_type
);
62 // Used to check if we can map shadow memory to a fixed location.
63 bool MemoryRangeIsAvailable(uptr range_start
, uptr range_end
);
64 void FlushUnneededShadowMemory(uptr addr
, uptr size
);
65 void IncreaseTotalMmap(uptr size
);
66 void DecreaseTotalMmap(uptr size
);
68 // InternalScopedBuffer can be used instead of large stack arrays to
69 // keep frame size low.
70 // FIXME: use InternalAlloc instead of MmapOrDie once
71 // InternalAlloc is made libc-free.
73 class InternalScopedBuffer
{
75 explicit InternalScopedBuffer(uptr cnt
) {
77 ptr_
= (T
*)MmapOrDie(cnt
* sizeof(T
), "InternalScopedBuffer");
79 ~InternalScopedBuffer() {
80 UnmapOrDie(ptr_
, cnt_
* sizeof(T
));
82 T
&operator[](uptr i
) { return ptr_
[i
]; }
83 T
*data() { return ptr_
; }
84 uptr
size() { return cnt_
* sizeof(T
); }
89 // Disallow evil constructors.
90 InternalScopedBuffer(const InternalScopedBuffer
&);
91 void operator=(const InternalScopedBuffer
&);
94 class InternalScopedString
: public InternalScopedBuffer
<char> {
96 explicit InternalScopedString(uptr max_length
)
97 : InternalScopedBuffer
<char>(max_length
), length_(0) {
100 uptr
length() { return length_
; }
105 void append(const char *format
, ...);
111 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
112 // constructor, so all instances of LowLevelAllocator should be
113 // linker initialized.
114 class LowLevelAllocator
{
116 // Requires an external lock.
117 void *Allocate(uptr size
);
119 char *allocated_end_
;
120 char *allocated_current_
;
122 typedef void (*LowLevelAllocateCallback
)(uptr ptr
, uptr size
);
123 // Allows to register tool-specific callbacks for LowLevelAllocator.
124 // Passing NULL removes the callback.
125 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback
);
128 void RawWrite(const char *buffer
);
130 // Caching version of PrintsToTty(). Not thread-safe.
131 bool PrintsToTtyCached();
132 bool ColorizeReports();
133 void Printf(const char *format
, ...);
134 void Report(const char *format
, ...);
135 void SetPrintfAndReportCallback(void (*callback
)(const char *));
136 #define VReport(level, ...) \
138 if ((uptr)common_flags()->verbosity >= (level)) Report(__VA_ARGS__); \
140 #define VPrintf(level, ...) \
142 if ((uptr)common_flags()->verbosity >= (level)) Printf(__VA_ARGS__); \
145 // Can be used to prevent mixing error reports from different sanitizers.
146 extern StaticSpinMutex CommonSanitizerReportMutex
;
147 void MaybeOpenReportFile();
148 extern fd_t report_fd
;
149 extern bool log_to_file
;
150 extern char report_path_prefix
[4096];
151 extern uptr report_fd_pid
;
152 extern uptr stoptheworld_tracer_pid
;
153 extern uptr stoptheworld_tracer_ppid
;
155 uptr
OpenFile(const char *filename
, bool write
);
156 // Opens the file 'file_name" and reads up to 'max_len' bytes.
157 // The resulting buffer is mmaped and stored in '*buff'.
158 // The size of the mmaped region is stored in '*buff_size',
159 // Returns the number of read bytes or 0 if file can not be opened.
160 uptr
ReadFileToBuffer(const char *file_name
, char **buff
,
161 uptr
*buff_size
, uptr max_len
);
162 // Maps given file to virtual memory, and returns pointer to it
163 // (or NULL if the mapping failes). Stores the size of mmaped region
165 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
);
167 // Error report formatting.
168 const char *StripPathPrefix(const char *filepath
,
169 const char *strip_file_prefix
);
170 void PrintSourceLocation(InternalScopedString
*buffer
, const char *file
,
171 int line
, int column
);
172 void PrintModuleAndOffset(InternalScopedString
*buffer
,
173 const char *module
, uptr offset
);
176 void DisableCoreDumper();
177 void DumpProcessMap();
178 bool FileExists(const char *filename
);
179 const char *GetEnv(const char *name
);
180 bool SetEnv(const char *name
, const char *value
);
181 const char *GetPwd();
182 char *FindPathToBinary(const char *name
);
185 bool StackSizeIsUnlimited();
186 void SetStackSizeLimitInBytes(uptr limit
);
187 void AdjustStackSize(void *attr
);
188 void PrepareForSandboxing(__sanitizer_sandbox_arguments
*args
);
189 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments
*args
);
190 void SetSandboxingCallback(void (*f
)());
196 void SleepForSeconds(int seconds
);
197 void SleepForMillis(int millis
);
199 int Atexit(void (*function
)(void));
200 void SortArray(uptr
*array
, uptr size
);
201 // Strip the directories from the module name, return a new string allocated
202 // with internal_strdup.
203 char *StripModuleName(const char *module
);
206 void NORETURN
Abort();
209 CheckFailed(const char *file
, int line
, const char *cond
, u64 v1
, u64 v2
);
211 // Set the name of the current thread to 'name', return true on succees.
212 // The name may be truncated to a system-dependent limit.
213 bool SanitizerSetThreadName(const char *name
);
214 // Get the name of the current thread (no more than max_len bytes),
215 // return true on succees. name should have space for at least max_len+1 bytes.
216 bool SanitizerGetThreadName(char *name
, int max_len
);
218 // Specific tools may override behavior of "Die" and "CheckFailed" functions
219 // to do tool-specific job.
220 typedef void (*DieCallbackType
)(void);
221 void SetDieCallback(DieCallbackType
);
222 DieCallbackType
GetDieCallback();
223 typedef void (*CheckFailedCallbackType
)(const char *, int, const char *,
225 void SetCheckFailedCallback(CheckFailedCallbackType callback
);
227 // Functions related to signal handling.
228 typedef void (*SignalHandlerType
)(int, void *, void *);
229 bool IsDeadlySignal(int signum
);
230 void InstallDeadlySignalHandlers(SignalHandlerType handler
);
231 // Alternative signal stack (POSIX-only).
232 void SetAlternateSignalStack();
233 void UnsetAlternateSignalStack();
235 // We don't want a summary too long.
236 const int kMaxSummaryLength
= 1024;
237 // Construct a one-line string:
238 // SUMMARY: SanitizerToolName: error_message
239 // and pass it to __sanitizer_report_error_summary.
240 void ReportErrorSummary(const char *error_message
);
241 // Same as above, but construct error_message as:
242 // error_type: file:line function
243 void ReportErrorSummary(const char *error_type
, const char *file
,
244 int line
, const char *function
);
245 void ReportErrorSummary(const char *error_type
, StackTrace
*trace
);
248 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
250 unsigned char _BitScanForward(unsigned long *index
, unsigned long mask
); // NOLINT
251 unsigned char _BitScanReverse(unsigned long *index
, unsigned long mask
); // NOLINT
253 unsigned char _BitScanForward64(unsigned long *index
, unsigned __int64 mask
); // NOLINT
254 unsigned char _BitScanReverse64(unsigned long *index
, unsigned __int64 mask
); // NOLINT
259 INLINE uptr
MostSignificantSetBitIndex(uptr x
) {
261 unsigned long up
; // NOLINT
262 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
263 up
= SANITIZER_WORDSIZE
- 1 - __builtin_clzl(x
);
264 #elif defined(_WIN64)
265 _BitScanReverse64(&up
, x
);
267 _BitScanReverse(&up
, x
);
272 INLINE uptr
LeastSignificantSetBitIndex(uptr x
) {
274 unsigned long up
; // NOLINT
275 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
276 up
= __builtin_ctzl(x
);
277 #elif defined(_WIN64)
278 _BitScanForward64(&up
, x
);
280 _BitScanForward(&up
, x
);
285 INLINE
bool IsPowerOfTwo(uptr x
) {
286 return (x
& (x
- 1)) == 0;
289 INLINE uptr
RoundUpToPowerOfTwo(uptr size
) {
291 if (IsPowerOfTwo(size
)) return size
;
293 uptr up
= MostSignificantSetBitIndex(size
);
294 CHECK(size
< (1ULL << (up
+ 1)));
295 CHECK(size
> (1ULL << up
));
296 return 1UL << (up
+ 1);
299 INLINE uptr
RoundUpTo(uptr size
, uptr boundary
) {
300 CHECK(IsPowerOfTwo(boundary
));
301 return (size
+ boundary
- 1) & ~(boundary
- 1);
304 INLINE uptr
RoundDownTo(uptr x
, uptr boundary
) {
305 return x
& ~(boundary
- 1);
308 INLINE
bool IsAligned(uptr a
, uptr alignment
) {
309 return (a
& (alignment
- 1)) == 0;
312 INLINE uptr
Log2(uptr x
) {
313 CHECK(IsPowerOfTwo(x
));
314 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
315 return __builtin_ctzl(x
);
316 #elif defined(_WIN64)
317 unsigned long ret
; // NOLINT
318 _BitScanForward64(&ret
, x
);
321 unsigned long ret
; // NOLINT
322 _BitScanForward(&ret
, x
);
327 // Don't use std::min, std::max or std::swap, to minimize dependency
329 template<class T
> T
Min(T a
, T b
) { return a
< b
? a
: b
; }
330 template<class T
> T
Max(T a
, T b
) { return a
> b
? a
: b
; }
331 template<class T
> void Swap(T
& a
, T
& b
) {
338 INLINE
bool IsSpace(int c
) {
339 return (c
== ' ') || (c
== '\n') || (c
== '\t') ||
340 (c
== '\f') || (c
== '\r') || (c
== '\v');
342 INLINE
bool IsDigit(int c
) {
343 return (c
>= '0') && (c
<= '9');
345 INLINE
int ToLower(int c
) {
346 return (c
>= 'A' && c
<= 'Z') ? (c
+ 'a' - 'A') : c
;
349 // A low-level vector based on mmap. May incur a significant memory overhead for
351 // WARNING: The current implementation supports only POD types.
353 class InternalMmapVector
{
355 explicit InternalMmapVector(uptr initial_capacity
) {
356 capacity_
= Max(initial_capacity
, (uptr
)1);
358 data_
= (T
*)MmapOrDie(capacity_
* sizeof(T
), "InternalMmapVector");
360 ~InternalMmapVector() {
361 UnmapOrDie(data_
, capacity_
* sizeof(T
));
363 T
&operator[](uptr i
) {
367 const T
&operator[](uptr i
) const {
371 void push_back(const T
&element
) {
372 CHECK_LE(size_
, capacity_
);
373 if (size_
== capacity_
) {
374 uptr new_capacity
= RoundUpToPowerOfTwo(size_
+ 1);
375 Resize(new_capacity
);
377 data_
[size_
++] = element
;
381 return data_
[size_
- 1];
390 const T
*data() const {
393 uptr
capacity() const {
397 void clear() { size_
= 0; }
400 void Resize(uptr new_capacity
) {
401 CHECK_GT(new_capacity
, 0);
402 CHECK_LE(size_
, new_capacity
);
403 T
*new_data
= (T
*)MmapOrDie(new_capacity
* sizeof(T
),
404 "InternalMmapVector");
405 internal_memcpy(new_data
, data_
, size_
* sizeof(T
));
408 UnmapOrDie(old_data
, capacity_
* sizeof(T
));
409 capacity_
= new_capacity
;
411 // Disallow evil constructors.
412 InternalMmapVector(const InternalMmapVector
&);
413 void operator=(const InternalMmapVector
&);
420 // HeapSort for arrays and InternalMmapVector.
421 template<class Container
, class Compare
>
422 void InternalSort(Container
*v
, uptr size
, Compare comp
) {
425 // Stage 1: insert elements to the heap.
426 for (uptr i
= 1; i
< size
; i
++) {
428 for (j
= i
; j
> 0; j
= p
) {
430 if (comp((*v
)[p
], (*v
)[j
]))
431 Swap((*v
)[j
], (*v
)[p
]);
436 // Stage 2: swap largest element with the last one,
437 // and sink the new top.
438 for (uptr i
= size
- 1; i
> 0; i
--) {
439 Swap((*v
)[0], (*v
)[i
]);
441 for (j
= 0; j
< i
; j
= max_ind
) {
442 uptr left
= 2 * j
+ 1;
443 uptr right
= 2 * j
+ 2;
445 if (left
< i
&& comp((*v
)[max_ind
], (*v
)[left
]))
447 if (right
< i
&& comp((*v
)[max_ind
], (*v
)[right
]))
450 Swap((*v
)[j
], (*v
)[max_ind
]);
457 template<class Container
, class Value
, class Compare
>
458 uptr
InternalBinarySearch(const Container
&v
, uptr first
, uptr last
,
459 const Value
&val
, Compare comp
) {
460 uptr not_found
= last
+ 1;
461 while (last
>= first
) {
462 uptr mid
= (first
+ last
) / 2;
463 if (comp(v
[mid
], val
))
465 else if (comp(val
, v
[mid
]))
473 // Represents a binary loaded into virtual memory (e.g. this can be an
474 // executable or a shared object).
477 LoadedModule(const char *module_name
, uptr base_address
);
478 void addAddressRange(uptr beg
, uptr end
);
479 bool containsAddress(uptr address
) const;
481 const char *full_name() const { return full_name_
; }
482 uptr
base_address() const { return base_address_
; }
485 struct AddressRange
{
491 static const uptr kMaxNumberOfAddressRanges
= 6;
492 AddressRange ranges_
[kMaxNumberOfAddressRanges
];
496 // OS-dependent function that fills array with descriptions of at most
497 // "max_modules" currently loaded modules. Returns the number of
498 // initialized modules. If filter is nonzero, ignores modules for which
499 // filter(full_name) is false.
500 typedef bool (*string_predicate_t
)(const char *);
501 uptr
GetListOfModules(LoadedModule
*modules
, uptr max_modules
,
502 string_predicate_t filter
);
505 const uptr kPthreadDestructorIterations
= 4;
507 // Unused on Windows.
508 const uptr kPthreadDestructorIterations
= 0;
511 // Callback type for iterating over a set of memory ranges.
512 typedef void (*RangeIteratorCallback
)(uptr begin
, uptr end
, void *arg
);
514 #if (SANITIZER_FREEBSD || SANITIZER_LINUX) && !defined(SANITIZER_GO)
515 extern uptr indirect_call_wrapper
;
516 void SetIndirectCallWrapper(uptr wrapper
);
518 template <typename F
>
519 F
IndirectExternCall(F f
) {
520 typedef F (*WrapF
)(F
);
521 return indirect_call_wrapper
? ((WrapF
)indirect_call_wrapper
)(f
) : f
;
524 INLINE
void SetIndirectCallWrapper(uptr wrapper
) {}
525 template <typename F
>
526 F
IndirectExternCall(F f
) {
531 #if SANITIZER_ANDROID
532 void AndroidLogWrite(const char *buffer
);
533 void GetExtraActivationFlags(char *buf
, uptr size
);
534 void SanitizerInitializeUnwinder();
536 INLINE
void AndroidLogWrite(const char *buffer_unused
) {}
537 INLINE
void GetExtraActivationFlags(char *buf
, uptr size
) { *buf
= '\0'; }
538 INLINE
void SanitizerInitializeUnwinder() {}
540 } // namespace __sanitizer
542 inline void *operator new(__sanitizer::operator_new_size_type size
,
543 __sanitizer::LowLevelAllocator
&alloc
) {
544 return alloc
.Allocate(size
);
547 #endif // SANITIZER_COMMON_H