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 run-time libraries of sanitizers.
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_flags.h"
20 #include "sanitizer_interface_internal.h"
21 #include "sanitizer_internal_defs.h"
22 #include "sanitizer_libc.h"
23 #include "sanitizer_list.h"
24 #include "sanitizer_mutex.h"
27 extern "C" void _ReadWriteBarrier();
28 #pragma intrinsic(_ReadWriteBarrier)
31 namespace __sanitizer {
36 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
37 const uptr kWordSizeInBits = 8 * kWordSize;
39 #if defined(__powerpc__) || defined(__powerpc64__)
40 const uptr kCacheLineSize = 128;
42 const uptr kCacheLineSize = 64;
45 const uptr kMaxPathLength = 4096;
47 // 16K loaded modules should be enough for everyone.
48 static const uptr kMaxNumberOfModules = 1 << 14;
50 const uptr kMaxThreadStackSize = 1 << 30; // 1Gb
52 // Denotes fake PC values that come from JIT/JAVA/etc.
53 // For such PC values __tsan_symbolize_external() will be called.
54 const u64 kExternalPCBit = 1ULL << 60;
56 extern const char *SanitizerToolName; // Can be changed by the tool.
58 extern atomic_uint32_t current_verbosity;
59 INLINE void SetVerbosity(int verbosity) {
60 atomic_store(¤t_verbosity, verbosity, memory_order_relaxed);
62 INLINE int Verbosity() {
63 return atomic_load(¤t_verbosity, memory_order_relaxed);
67 uptr GetPageSizeCached();
68 uptr GetMmapGranularity();
69 uptr GetMaxVirtualAddress();
73 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
75 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
76 uptr *tls_addr, uptr *tls_size);
79 void *MmapOrDie(uptr size, const char *mem_type);
80 void UnmapOrDie(void *addr, uptr size);
81 void *MmapFixedNoReserve(uptr fixed_addr, uptr size,
82 const char *name = nullptr);
83 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
84 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
85 void *MmapNoAccess(uptr fixed_addr, uptr size, const char *name = nullptr);
86 // Map aligned chunk of address space; size and alignment are powers of two.
87 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
88 // Disallow access to a memory range. Use MmapNoAccess to allocate an
89 // unaccessible memory.
90 bool MprotectNoAccess(uptr addr, uptr size);
92 // Used to check if we can map shadow memory to a fixed location.
93 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
94 void FlushUnneededShadowMemory(uptr addr, uptr size);
95 void IncreaseTotalMmap(uptr size);
96 void DecreaseTotalMmap(uptr size);
98 void NoHugePagesInRegion(uptr addr, uptr length);
99 void DontDumpShadowMemory(uptr addr, uptr length);
101 // InternalScopedBuffer can be used instead of large stack arrays to
102 // keep frame size low.
103 // FIXME: use InternalAlloc instead of MmapOrDie once
104 // InternalAlloc is made libc-free.
106 class InternalScopedBuffer {
108 explicit InternalScopedBuffer(uptr cnt) {
110 ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
112 ~InternalScopedBuffer() {
113 UnmapOrDie(ptr_, cnt_ * sizeof(T));
115 T &operator[](uptr i) { return ptr_[i]; }
116 T *data() { return ptr_; }
117 uptr size() { return cnt_ * sizeof(T); }
122 // Disallow evil constructors.
123 InternalScopedBuffer(const InternalScopedBuffer&);
124 void operator=(const InternalScopedBuffer&);
127 class InternalScopedString : public InternalScopedBuffer<char> {
129 explicit InternalScopedString(uptr max_length)
130 : InternalScopedBuffer<char>(max_length), length_(0) {
133 uptr length() { return length_; }
138 void append(const char *format, ...);
144 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
145 // constructor, so all instances of LowLevelAllocator should be
146 // linker initialized.
147 class LowLevelAllocator {
149 // Requires an external lock.
150 void *Allocate(uptr size);
152 char *allocated_end_;
153 char *allocated_current_;
155 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
156 // Allows to register tool-specific callbacks for LowLevelAllocator.
157 // Passing NULL removes the callback.
158 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
161 void RawWrite(const char *buffer);
162 bool ColorizeReports();
163 void Printf(const char *format, ...);
164 void Report(const char *format, ...);
165 void SetPrintfAndReportCallback(void (*callback)(const char *));
166 #define VReport(level, ...) \
168 if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
170 #define VPrintf(level, ...) \
172 if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
175 // Can be used to prevent mixing error reports from different sanitizers.
176 extern StaticSpinMutex CommonSanitizerReportMutex;
179 void Write(const char *buffer, uptr length);
180 bool SupportsColors();
181 void SetReportPath(const char *path);
183 // Don't use fields directly. They are only declared public to allow
184 // aggregate initialization.
186 // Protects fields below.
188 // Opened file descriptor. Defaults to stderr. It may be equal to
189 // kInvalidFd, in which case new file will be opened when necessary.
191 // Path prefix of report file, set via __sanitizer_set_report_path.
192 char path_prefix[kMaxPathLength];
193 // Full path to report, obtained as <path_prefix>.PID
194 char full_path[kMaxPathLength];
195 // PID of the process that opened fd. If a fork() occurs,
196 // the PID of child will be different from fd_pid.
200 void ReopenIfNecessary();
202 extern ReportFile report_file;
204 extern uptr stoptheworld_tracer_pid;
205 extern uptr stoptheworld_tracer_ppid;
207 enum FileAccessMode {
213 // Returns kInvalidFd on error.
214 fd_t OpenFile(const char *filename, FileAccessMode mode,
215 error_t *errno_p = nullptr);
216 void CloseFile(fd_t);
218 // Return true on success, false on error.
219 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size,
220 uptr *bytes_read = nullptr, error_t *error_p = nullptr);
221 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size,
222 uptr *bytes_written = nullptr, error_t *error_p = nullptr);
224 bool RenameFile(const char *oldpath, const char *newpath,
225 error_t *error_p = nullptr);
227 bool SupportsColoredOutput(fd_t fd);
229 // Opens the file 'file_name" and reads up to 'max_len' bytes.
230 // The resulting buffer is mmaped and stored in '*buff'.
231 // The size of the mmaped region is stored in '*buff_size',
232 // Returns the number of read bytes or 0 if file can not be opened.
233 uptr ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
234 uptr max_len, error_t *errno_p = nullptr);
235 // Maps given file to virtual memory, and returns pointer to it
236 // (or NULL if mapping fails). Stores the size of mmaped region
238 void *MapFileToMemory(const char *file_name, uptr *buff_size);
239 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset);
241 bool IsAccessibleMemoryRange(uptr beg, uptr size);
243 // Error report formatting.
244 const char *StripPathPrefix(const char *filepath,
245 const char *strip_file_prefix);
246 // Strip the directories from the module name.
247 const char *StripModuleName(const char *module);
250 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
251 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
252 const char *GetBinaryBasename();
253 void CacheBinaryName();
254 void DisableCoreDumperIfNecessary();
255 void DumpProcessMap();
256 bool FileExists(const char *filename);
257 const char *GetEnv(const char *name);
258 bool SetEnv(const char *name, const char *value);
259 const char *GetPwd();
260 char *FindPathToBinary(const char *name);
261 bool IsPathSeparator(const char c);
262 bool IsAbsolutePath(const char *path);
266 bool StackSizeIsUnlimited();
267 void SetStackSizeLimitInBytes(uptr limit);
268 bool AddressSpaceIsUnlimited();
269 void SetAddressSpaceUnlimited();
270 void AdjustStackSize(void *attr);
271 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args);
272 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args);
273 void SetSandboxingCallback(void (*f)());
275 void CoverageUpdateMapping();
276 void CovBeforeFork();
277 void CovAfterFork(int child_pid);
279 void InitializeCoverage(bool enabled, const char *coverage_dir);
280 void ReInitializeCoverage(bool enabled, const char *coverage_dir);
286 void SleepForSeconds(int seconds);
287 void SleepForMillis(int millis);
289 int Atexit(void (*function)(void));
290 void SortArray(uptr *array, uptr size);
291 bool TemplateMatch(const char *templ, const char *str);
294 void NORETURN Abort();
297 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
299 // Set the name of the current thread to 'name', return true on succees.
300 // The name may be truncated to a system-dependent limit.
301 bool SanitizerSetThreadName(const char *name);
302 // Get the name of the current thread (no more than max_len bytes),
303 // return true on succees. name should have space for at least max_len+1 bytes.
304 bool SanitizerGetThreadName(char *name, int max_len);
306 // Specific tools may override behavior of "Die" and "CheckFailed" functions
307 // to do tool-specific job.
308 typedef void (*DieCallbackType)(void);
309 void SetDieCallback(DieCallbackType);
310 void SetUserDieCallback(DieCallbackType);
311 DieCallbackType GetDieCallback();
312 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
314 void SetCheckFailedCallback(CheckFailedCallbackType callback);
316 // Callback will be called if soft_rss_limit_mb is given and the limit is
317 // exceeded (exceeded==true) or if rss went down below the limit
318 // (exceeded==false).
319 // The callback should be registered once at the tool init time.
320 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
322 // Functions related to signal handling.
323 typedef void (*SignalHandlerType)(int, void *, void *);
324 bool IsDeadlySignal(int signum);
325 void InstallDeadlySignalHandlers(SignalHandlerType handler);
326 // Alternative signal stack (POSIX-only).
327 void SetAlternateSignalStack();
328 void UnsetAlternateSignalStack();
330 // We don't want a summary too long.
331 const int kMaxSummaryLength = 1024;
332 // Construct a one-line string:
333 // SUMMARY: SanitizerToolName: error_message
334 // and pass it to __sanitizer_report_error_summary.
335 void ReportErrorSummary(const char *error_message);
336 // Same as above, but construct error_message as:
337 // error_type file:line[:column][ function]
338 void ReportErrorSummary(const char *error_type, const AddressInfo &info);
339 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
340 void ReportErrorSummary(const char *error_type, StackTrace *trace);
343 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
345 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
346 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
348 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
349 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
354 INLINE uptr MostSignificantSetBitIndex(uptr x) {
356 unsigned long up; // NOLINT
357 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
359 up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
361 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
363 #elif defined(_WIN64)
364 _BitScanReverse64(&up, x);
366 _BitScanReverse(&up, x);
371 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
373 unsigned long up; // NOLINT
374 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
376 up = __builtin_ctzll(x);
378 up = __builtin_ctzl(x);
380 #elif defined(_WIN64)
381 _BitScanForward64(&up, x);
383 _BitScanForward(&up, x);
388 INLINE bool IsPowerOfTwo(uptr x) {
389 return (x & (x - 1)) == 0;
392 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
394 if (IsPowerOfTwo(size)) return size;
396 uptr up = MostSignificantSetBitIndex(size);
397 CHECK(size < (1ULL << (up + 1)));
398 CHECK(size > (1ULL << up));
399 return 1ULL << (up + 1);
402 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
403 CHECK(IsPowerOfTwo(boundary));
404 return (size + boundary - 1) & ~(boundary - 1);
407 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
408 return x & ~(boundary - 1);
411 INLINE bool IsAligned(uptr a, uptr alignment) {
412 return (a & (alignment - 1)) == 0;
415 INLINE uptr Log2(uptr x) {
416 CHECK(IsPowerOfTwo(x));
417 return LeastSignificantSetBitIndex(x);
420 // Don't use std::min, std::max or std::swap, to minimize dependency
422 template<class T> T Min(T a, T b) { return a < b ? a : b; }
423 template<class T> T Max(T a, T b) { return a > b ? a : b; }
424 template<class T> void Swap(T& a, T& b) {
431 INLINE bool IsSpace(int c) {
432 return (c == ' ') || (c == '\n') || (c == '\t') ||
433 (c == '\f') || (c == '\r') || (c == '\v');
435 INLINE bool IsDigit(int c) {
436 return (c >= '0') && (c <= '9');
438 INLINE int ToLower(int c) {
439 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
442 // A low-level vector based on mmap. May incur a significant memory overhead for
444 // WARNING: The current implementation supports only POD types.
446 class InternalMmapVectorNoCtor {
448 void Initialize(uptr initial_capacity) {
449 capacity_ = Max(initial_capacity, (uptr)1);
451 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
454 UnmapOrDie(data_, capacity_ * sizeof(T));
456 T &operator[](uptr i) {
460 const T &operator[](uptr i) const {
464 void push_back(const T &element) {
465 CHECK_LE(size_, capacity_);
466 if (size_ == capacity_) {
467 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
468 Resize(new_capacity);
470 data_[size_++] = element;
474 return data_[size_ - 1];
483 const T *data() const {
489 uptr capacity() const {
493 void clear() { size_ = 0; }
494 bool empty() const { return size() == 0; }
497 void Resize(uptr new_capacity) {
498 CHECK_GT(new_capacity, 0);
499 CHECK_LE(size_, new_capacity);
500 T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
501 "InternalMmapVector");
502 internal_memcpy(new_data, data_, size_ * sizeof(T));
505 UnmapOrDie(old_data, capacity_ * sizeof(T));
506 capacity_ = new_capacity;
515 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
517 explicit InternalMmapVector(uptr initial_capacity) {
518 InternalMmapVectorNoCtor<T>::Initialize(initial_capacity);
520 ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
521 // Disallow evil constructors.
522 InternalMmapVector(const InternalMmapVector&);
523 void operator=(const InternalMmapVector&);
526 // HeapSort for arrays and InternalMmapVector.
527 template<class Container, class Compare>
528 void InternalSort(Container *v, uptr size, Compare comp) {
531 // Stage 1: insert elements to the heap.
532 for (uptr i = 1; i < size; i++) {
534 for (j = i; j > 0; j = p) {
536 if (comp((*v)[p], (*v)[j]))
537 Swap((*v)[j], (*v)[p]);
542 // Stage 2: swap largest element with the last one,
543 // and sink the new top.
544 for (uptr i = size - 1; i > 0; i--) {
545 Swap((*v)[0], (*v)[i]);
547 for (j = 0; j < i; j = max_ind) {
548 uptr left = 2 * j + 1;
549 uptr right = 2 * j + 2;
551 if (left < i && comp((*v)[max_ind], (*v)[left]))
553 if (right < i && comp((*v)[max_ind], (*v)[right]))
556 Swap((*v)[j], (*v)[max_ind]);
563 template<class Container, class Value, class Compare>
564 uptr InternalBinarySearch(const Container &v, uptr first, uptr last,
565 const Value &val, Compare comp) {
566 uptr not_found = last + 1;
567 while (last >= first) {
568 uptr mid = (first + last) / 2;
569 if (comp(v[mid], val))
571 else if (comp(val, v[mid]))
579 // Represents a binary loaded into virtual memory (e.g. this can be an
580 // executable or a shared object).
583 LoadedModule() : full_name_(nullptr), base_address_(0) { ranges_.clear(); }
584 void set(const char *module_name, uptr base_address);
586 void addAddressRange(uptr beg, uptr end, bool executable);
587 bool containsAddress(uptr address) const;
589 const char *full_name() const { return full_name_; }
590 uptr base_address() const { return base_address_; }
592 struct AddressRange {
598 AddressRange(uptr beg, uptr end, bool executable)
599 : next(nullptr), beg(beg), end(end), executable(executable) {}
602 typedef IntrusiveList<AddressRange>::ConstIterator Iterator;
603 Iterator ranges() const { return Iterator(&ranges_); }
606 char *full_name_; // Owned.
608 IntrusiveList<AddressRange> ranges_;
611 // OS-dependent function that fills array with descriptions of at most
612 // "max_modules" currently loaded modules. Returns the number of
613 // initialized modules. If filter is nonzero, ignores modules for which
614 // filter(full_name) is false.
615 typedef bool (*string_predicate_t)(const char *);
616 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
617 string_predicate_t filter);
619 // Callback type for iterating over a set of memory ranges.
620 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
622 enum AndroidApiLevel {
623 ANDROID_NOT_ANDROID = 0,
625 ANDROID_LOLLIPOP_MR1 = 22,
626 ANDROID_POST_LOLLIPOP = 23
629 #if SANITIZER_ANDROID
630 // Initialize Android logging. Any writes before this are silently lost.
631 void AndroidLogInit();
632 void AndroidLogWrite(const char *buffer);
633 void GetExtraActivationFlags(char *buf, uptr size);
634 void SanitizerInitializeUnwinder();
635 AndroidApiLevel AndroidGetApiLevel();
637 INLINE void AndroidLogInit() {}
638 INLINE void AndroidLogWrite(const char *buffer_unused) {}
639 INLINE void GetExtraActivationFlags(char *buf, uptr size) { *buf = '\0'; }
640 INLINE void SanitizerInitializeUnwinder() {}
641 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
644 INLINE uptr GetPthreadDestructorIterations() {
645 #if SANITIZER_ANDROID
646 return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
647 #elif SANITIZER_POSIX
650 // Unused on Windows.
655 void *internal_start_thread(void(*func)(void*), void *arg);
656 void internal_join_thread(void *th);
657 void MaybeStartBackgroudThread();
659 // Make the compiler think that something is going on there.
660 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
661 // compiler from recognising it and turning it into an actual call to
662 // memset/memcpy/etc.
663 static inline void SanitizerBreakOptimization(void *arg) {
664 #if _MSC_VER && !defined(__clang__)
667 __asm__ __volatile__("" : : "r" (arg) : "memory");
671 struct SignalContext {
678 SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp) :
679 context(context), addr(addr), pc(pc), sp(sp), bp(bp) {
682 // Creates signal context in a platform-specific manner.
683 static SignalContext Create(void *siginfo, void *context);
686 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
688 } // namespace __sanitizer
690 inline void *operator new(__sanitizer::operator_new_size_type size,
691 __sanitizer::LowLevelAllocator &alloc) {
692 return alloc.Allocate(size);
695 struct StackDepotStats {
700 #endif // SANITIZER_COMMON_H