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 run-time libraries of sanitizers.
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_flags.h"
18 #include "sanitizer_interface_internal.h"
19 #include "sanitizer_internal_defs.h"
20 #include "sanitizer_libc.h"
21 #include "sanitizer_list.h"
22 #include "sanitizer_mutex.h"
24 #if defined(_MSC_VER) && !defined(__clang__)
25 extern "C" void _ReadWriteBarrier();
26 #pragma intrinsic(_ReadWriteBarrier)
29 namespace __sanitizer {
34 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
35 const uptr kWordSizeInBits = 8 * kWordSize;
37 #if defined(__powerpc__) || defined(__powerpc64__)
38 const uptr kCacheLineSize = 128;
40 const uptr kCacheLineSize = 64;
43 const uptr kMaxPathLength = 4096;
45 const uptr kMaxThreadStackSize = 1 << 30; // 1Gb
47 static const uptr kErrorMessageBufferSize = 1 << 16;
49 // Denotes fake PC values that come from JIT/JAVA/etc.
50 // For such PC values __tsan_symbolize_external() will be called.
51 const u64 kExternalPCBit = 1ULL << 60;
53 extern const char *SanitizerToolName; // Can be changed by the tool.
55 extern atomic_uint32_t current_verbosity;
56 INLINE void SetVerbosity(int verbosity) {
57 atomic_store(¤t_verbosity, verbosity, memory_order_relaxed);
59 INLINE int Verbosity() {
60 return atomic_load(¤t_verbosity, memory_order_relaxed);
64 extern uptr PageSizeCached;
65 INLINE uptr GetPageSizeCached() {
67 PageSizeCached = GetPageSize();
68 return PageSizeCached;
70 uptr GetMmapGranularity();
71 uptr GetMaxVirtualAddress();
75 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
77 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
78 uptr *tls_addr, uptr *tls_size);
81 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report = false);
82 INLINE void *MmapOrDieQuietly(uptr size, const char *mem_type) {
83 return MmapOrDie(size, mem_type, /*raw_report*/ true);
85 void UnmapOrDie(void *addr, uptr size);
86 // Behaves just like MmapOrDie, but tolerates out of memory condition, in that
87 // case returns nullptr.
88 void *MmapOrDieOnFatalError(uptr size, const char *mem_type);
89 void *MmapFixedNoReserve(uptr fixed_addr, uptr size,
90 const char *name = nullptr);
91 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
92 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
93 // Behaves just like MmapFixedOrDie, but tolerates out of memory condition, in
94 // that case returns nullptr.
95 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size);
96 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name = nullptr);
97 void *MmapNoAccess(uptr size);
98 // Map aligned chunk of address space; size and alignment are powers of two.
99 // Dies on all but out of memory errors, in the latter case returns nullptr.
100 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
101 const char *mem_type);
102 // Disallow access to a memory range. Use MmapFixedNoAccess to allocate an
103 // unaccessible memory.
104 bool MprotectNoAccess(uptr addr, uptr size);
105 bool MprotectReadOnly(uptr addr, uptr size);
107 // Find an available address space.
108 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding);
110 // Used to check if we can map shadow memory to a fixed location.
111 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
112 void ReleaseMemoryToOS(uptr addr, uptr size);
113 void IncreaseTotalMmap(uptr size);
114 void DecreaseTotalMmap(uptr size);
116 void NoHugePagesInRegion(uptr addr, uptr length);
117 void DontDumpShadowMemory(uptr addr, uptr length);
118 // Check if the built VMA size matches the runtime one.
120 void RunMallocHooks(const void *ptr, uptr size);
121 void RunFreeHooks(const void *ptr);
123 // InternalScopedBuffer can be used instead of large stack arrays to
124 // keep frame size low.
125 // FIXME: use InternalAlloc instead of MmapOrDie once
126 // InternalAlloc is made libc-free.
127 template <typename T>
128 class InternalScopedBuffer {
130 explicit InternalScopedBuffer(uptr cnt) {
132 ptr_ = (T *)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
134 ~InternalScopedBuffer() { UnmapOrDie(ptr_, cnt_ * sizeof(T)); }
135 T &operator[](uptr i) { return ptr_[i]; }
136 T *data() { return ptr_; }
137 uptr size() { return cnt_ * sizeof(T); }
142 // Disallow copies and moves.
143 InternalScopedBuffer(const InternalScopedBuffer &) = delete;
144 InternalScopedBuffer &operator=(const InternalScopedBuffer &) = delete;
145 InternalScopedBuffer(InternalScopedBuffer &&) = delete;
146 InternalScopedBuffer &operator=(InternalScopedBuffer &&) = delete;
149 class InternalScopedString : public InternalScopedBuffer<char> {
151 explicit InternalScopedString(uptr max_length)
152 : InternalScopedBuffer<char>(max_length), length_(0) {
155 uptr length() { return length_; }
160 void append(const char *format, ...);
166 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
167 // constructor, so all instances of LowLevelAllocator should be
168 // linker initialized.
169 class LowLevelAllocator {
171 // Requires an external lock.
172 void *Allocate(uptr size);
174 char *allocated_end_;
175 char *allocated_current_;
177 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
178 // Allows to register tool-specific callbacks for LowLevelAllocator.
179 // Passing NULL removes the callback.
180 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
183 void RawWrite(const char *buffer);
184 bool ColorizeReports();
185 void RemoveANSIEscapeSequencesFromString(char *buffer);
186 void Printf(const char *format, ...);
187 void Report(const char *format, ...);
188 void SetPrintfAndReportCallback(void (*callback)(const char *));
189 #define VReport(level, ...) \
191 if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
193 #define VPrintf(level, ...) \
195 if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
198 // Can be used to prevent mixing error reports from different sanitizers.
199 extern StaticSpinMutex CommonSanitizerReportMutex;
202 void Write(const char *buffer, uptr length);
203 bool SupportsColors();
204 void SetReportPath(const char *path);
206 // Don't use fields directly. They are only declared public to allow
207 // aggregate initialization.
209 // Protects fields below.
211 // Opened file descriptor. Defaults to stderr. It may be equal to
212 // kInvalidFd, in which case new file will be opened when necessary.
214 // Path prefix of report file, set via __sanitizer_set_report_path.
215 char path_prefix[kMaxPathLength];
216 // Full path to report, obtained as <path_prefix>.PID
217 char full_path[kMaxPathLength];
218 // PID of the process that opened fd. If a fork() occurs,
219 // the PID of child will be different from fd_pid.
223 void ReopenIfNecessary();
225 extern ReportFile report_file;
227 extern uptr stoptheworld_tracer_pid;
228 extern uptr stoptheworld_tracer_ppid;
230 enum FileAccessMode {
236 // Returns kInvalidFd on error.
237 fd_t OpenFile(const char *filename, FileAccessMode mode,
238 error_t *errno_p = nullptr);
239 void CloseFile(fd_t);
241 // Return true on success, false on error.
242 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size,
243 uptr *bytes_read = nullptr, error_t *error_p = nullptr);
244 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size,
245 uptr *bytes_written = nullptr, error_t *error_p = nullptr);
247 bool RenameFile(const char *oldpath, const char *newpath,
248 error_t *error_p = nullptr);
250 // Scoped file handle closer.
252 explicit FileCloser(fd_t fd) : fd(fd) {}
253 ~FileCloser() { CloseFile(fd); }
257 bool SupportsColoredOutput(fd_t fd);
259 // Opens the file 'file_name" and reads up to 'max_len' bytes.
260 // The resulting buffer is mmaped and stored in '*buff'.
261 // The size of the mmaped region is stored in '*buff_size'.
262 // The total number of read bytes is stored in '*read_len'.
263 // Returns true if file was successfully opened and read.
264 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
265 uptr *read_len, uptr max_len = 1 << 26,
266 error_t *errno_p = nullptr);
267 // Maps given file to virtual memory, and returns pointer to it
268 // (or NULL if mapping fails). Stores the size of mmaped region
270 void *MapFileToMemory(const char *file_name, uptr *buff_size);
271 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset);
273 bool IsAccessibleMemoryRange(uptr beg, uptr size);
275 // Error report formatting.
276 const char *StripPathPrefix(const char *filepath,
277 const char *strip_file_prefix);
278 // Strip the directories from the module name.
279 const char *StripModuleName(const char *module);
282 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
283 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
284 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len);
285 const char *GetProcessName();
286 void UpdateProcessName();
287 void CacheBinaryName();
288 void DisableCoreDumperIfNecessary();
289 void DumpProcessMap();
290 bool FileExists(const char *filename);
291 const char *GetEnv(const char *name);
292 bool SetEnv(const char *name, const char *value);
293 const char *GetPwd();
294 char *FindPathToBinary(const char *name);
295 bool IsPathSeparator(const char c);
296 bool IsAbsolutePath(const char *path);
297 // Starts a subprocess and returs its pid.
298 // If *_fd parameters are not kInvalidFd their corresponding input/output
299 // streams will be redirect to the file. The files will always be closed
300 // in parent process even in case of an error.
301 // The child process will close all fds after STDERR_FILENO
302 // before passing control to a program.
303 pid_t StartSubprocess(const char *filename, const char *const argv[],
304 fd_t stdin_fd = kInvalidFd, fd_t stdout_fd = kInvalidFd,
305 fd_t stderr_fd = kInvalidFd);
306 // Checks if specified process is still running
307 bool IsProcessRunning(pid_t pid);
308 // Waits for the process to finish and returns its exit code.
309 // Returns -1 in case of an error.
310 int WaitForProcess(pid_t pid);
316 bool StackSizeIsUnlimited();
317 uptr GetStackSizeLimitInBytes();
318 void SetStackSizeLimitInBytes(uptr limit);
319 bool AddressSpaceIsUnlimited();
320 void SetAddressSpaceUnlimited();
321 void AdjustStackSize(void *attr);
322 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args);
323 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args);
324 void SetSandboxingCallback(void (*f)());
326 void CoverageUpdateMapping();
327 void CovBeforeFork();
328 void CovAfterFork(int child_pid);
330 void InitializeCoverage(bool enabled, const char *coverage_dir);
331 void ReInitializeCoverage(bool enabled, const char *coverage_dir);
337 void SleepForSeconds(int seconds);
338 void SleepForMillis(int millis);
340 int Atexit(void (*function)(void));
341 void SortArray(uptr *array, uptr size);
342 void SortArray(u32 *array, uptr size);
343 bool TemplateMatch(const char *templ, const char *str);
346 void NORETURN Abort();
349 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
350 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
351 const char *mmap_type, error_t err,
352 bool raw_report = false);
354 // Set the name of the current thread to 'name', return true on succees.
355 // The name may be truncated to a system-dependent limit.
356 bool SanitizerSetThreadName(const char *name);
357 // Get the name of the current thread (no more than max_len bytes),
358 // return true on succees. name should have space for at least max_len+1 bytes.
359 bool SanitizerGetThreadName(char *name, int max_len);
361 // Specific tools may override behavior of "Die" and "CheckFailed" functions
362 // to do tool-specific job.
363 typedef void (*DieCallbackType)(void);
365 // It's possible to add several callbacks that would be run when "Die" is
366 // called. The callbacks will be run in the opposite order. The tools are
367 // strongly recommended to setup all callbacks during initialization, when there
368 // is only a single thread.
369 bool AddDieCallback(DieCallbackType callback);
370 bool RemoveDieCallback(DieCallbackType callback);
372 void SetUserDieCallback(DieCallbackType callback);
374 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
376 void SetCheckFailedCallback(CheckFailedCallbackType callback);
378 // Callback will be called if soft_rss_limit_mb is given and the limit is
379 // exceeded (exceeded==true) or if rss went down below the limit
380 // (exceeded==false).
381 // The callback should be registered once at the tool init time.
382 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
384 // Callback to be called when we want to try releasing unused allocator memory
386 typedef void (*AllocatorReleaseToOSCallback)();
387 // The callback should be registered once at the tool init time.
388 void SetAllocatorReleaseToOSCallback(AllocatorReleaseToOSCallback Callback);
390 // Functions related to signal handling.
391 typedef void (*SignalHandlerType)(int, void *, void *);
392 bool IsHandledDeadlySignal(int signum);
393 void InstallDeadlySignalHandlers(SignalHandlerType handler);
394 // Alternative signal stack (POSIX-only).
395 void SetAlternateSignalStack();
396 void UnsetAlternateSignalStack();
398 // We don't want a summary too long.
399 const int kMaxSummaryLength = 1024;
400 // Construct a one-line string:
401 // SUMMARY: SanitizerToolName: error_message
402 // and pass it to __sanitizer_report_error_summary.
403 void ReportErrorSummary(const char *error_message);
404 // Same as above, but construct error_message as:
405 // error_type file:line[:column][ function]
406 void ReportErrorSummary(const char *error_type, const AddressInfo &info);
407 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
408 void ReportErrorSummary(const char *error_type, const StackTrace *trace);
411 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
413 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
414 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
416 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
417 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
422 INLINE uptr MostSignificantSetBitIndex(uptr x) {
424 unsigned long up; // NOLINT
425 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
427 up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
429 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
431 #elif defined(_WIN64)
432 _BitScanReverse64(&up, x);
434 _BitScanReverse(&up, x);
439 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
441 unsigned long up; // NOLINT
442 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
444 up = __builtin_ctzll(x);
446 up = __builtin_ctzl(x);
448 #elif defined(_WIN64)
449 _BitScanForward64(&up, x);
451 _BitScanForward(&up, x);
456 INLINE bool IsPowerOfTwo(uptr x) {
457 return (x & (x - 1)) == 0;
460 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
462 if (IsPowerOfTwo(size)) return size;
464 uptr up = MostSignificantSetBitIndex(size);
465 CHECK_LT(size, (1ULL << (up + 1)));
466 CHECK_GT(size, (1ULL << up));
467 return 1ULL << (up + 1);
470 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
471 RAW_CHECK(IsPowerOfTwo(boundary));
472 return (size + boundary - 1) & ~(boundary - 1);
475 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
476 return x & ~(boundary - 1);
479 INLINE bool IsAligned(uptr a, uptr alignment) {
480 return (a & (alignment - 1)) == 0;
483 INLINE uptr Log2(uptr x) {
484 CHECK(IsPowerOfTwo(x));
485 return LeastSignificantSetBitIndex(x);
488 // Don't use std::min, std::max or std::swap, to minimize dependency
490 template<class T> T Min(T a, T b) { return a < b ? a : b; }
491 template<class T> T Max(T a, T b) { return a > b ? a : b; }
492 template<class T> void Swap(T& a, T& b) {
499 INLINE bool IsSpace(int c) {
500 return (c == ' ') || (c == '\n') || (c == '\t') ||
501 (c == '\f') || (c == '\r') || (c == '\v');
503 INLINE bool IsDigit(int c) {
504 return (c >= '0') && (c <= '9');
506 INLINE int ToLower(int c) {
507 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
510 // A low-level vector based on mmap. May incur a significant memory overhead for
512 // WARNING: The current implementation supports only POD types.
514 class InternalMmapVectorNoCtor {
516 void Initialize(uptr initial_capacity) {
517 capacity_ = Max(initial_capacity, (uptr)1);
519 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
522 UnmapOrDie(data_, capacity_ * sizeof(T));
524 T &operator[](uptr i) {
528 const T &operator[](uptr i) const {
532 void push_back(const T &element) {
533 CHECK_LE(size_, capacity_);
534 if (size_ == capacity_) {
535 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
536 Resize(new_capacity);
538 internal_memcpy(&data_[size_++], &element, sizeof(T));
542 return data_[size_ - 1];
551 const T *data() const {
557 uptr capacity() const {
561 void clear() { size_ = 0; }
562 bool empty() const { return size() == 0; }
564 const T *begin() const {
570 const T *end() const {
571 return data() + size();
574 return data() + size();
578 void Resize(uptr new_capacity) {
579 CHECK_GT(new_capacity, 0);
580 CHECK_LE(size_, new_capacity);
581 T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
582 "InternalMmapVector");
583 internal_memcpy(new_data, data_, size_ * sizeof(T));
586 UnmapOrDie(old_data, capacity_ * sizeof(T));
587 capacity_ = new_capacity;
596 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
598 explicit InternalMmapVector(uptr initial_capacity) {
599 InternalMmapVectorNoCtor<T>::Initialize(initial_capacity);
601 ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
602 // Disallow evil constructors.
603 InternalMmapVector(const InternalMmapVector&);
604 void operator=(const InternalMmapVector&);
607 // HeapSort for arrays and InternalMmapVector.
608 template<class Container, class Compare>
609 void InternalSort(Container *v, uptr size, Compare comp) {
612 // Stage 1: insert elements to the heap.
613 for (uptr i = 1; i < size; i++) {
615 for (j = i; j > 0; j = p) {
617 if (comp((*v)[p], (*v)[j]))
618 Swap((*v)[j], (*v)[p]);
623 // Stage 2: swap largest element with the last one,
624 // and sink the new top.
625 for (uptr i = size - 1; i > 0; i--) {
626 Swap((*v)[0], (*v)[i]);
628 for (j = 0; j < i; j = max_ind) {
629 uptr left = 2 * j + 1;
630 uptr right = 2 * j + 2;
632 if (left < i && comp((*v)[max_ind], (*v)[left]))
634 if (right < i && comp((*v)[max_ind], (*v)[right]))
637 Swap((*v)[j], (*v)[max_ind]);
644 template<class Container, class Value, class Compare>
645 uptr InternalBinarySearch(const Container &v, uptr first, uptr last,
646 const Value &val, Compare comp) {
647 uptr not_found = last + 1;
648 while (last >= first) {
649 uptr mid = (first + last) / 2;
650 if (comp(v[mid], val))
652 else if (comp(val, v[mid]))
660 // Represents a binary loaded into virtual memory (e.g. this can be an
661 // executable or a shared object).
664 LoadedModule() : full_name_(nullptr), base_address_(0) { ranges_.clear(); }
665 void set(const char *module_name, uptr base_address);
667 void addAddressRange(uptr beg, uptr end, bool executable);
668 bool containsAddress(uptr address) const;
670 const char *full_name() const { return full_name_; }
671 uptr base_address() const { return base_address_; }
673 struct AddressRange {
679 AddressRange(uptr beg, uptr end, bool executable)
680 : next(nullptr), beg(beg), end(end), executable(executable) {}
683 const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
686 char *full_name_; // Owned.
688 IntrusiveList<AddressRange> ranges_;
691 // List of LoadedModules. OS-dependent implementation is responsible for
692 // filling this information.
693 class ListOfModules {
695 ListOfModules() : modules_(kInitialCapacity) {}
696 ~ListOfModules() { clear(); }
698 const LoadedModule *begin() const { return modules_.begin(); }
699 LoadedModule *begin() { return modules_.begin(); }
700 const LoadedModule *end() const { return modules_.end(); }
701 LoadedModule *end() { return modules_.end(); }
702 uptr size() const { return modules_.size(); }
703 const LoadedModule &operator[](uptr i) const {
704 CHECK_LT(i, modules_.size());
710 for (auto &module : modules_) module.clear();
714 InternalMmapVector<LoadedModule> modules_;
715 // We rarely have more than 16K loaded modules.
716 static const uptr kInitialCapacity = 1 << 14;
719 // Callback type for iterating over a set of memory ranges.
720 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
722 enum AndroidApiLevel {
723 ANDROID_NOT_ANDROID = 0,
725 ANDROID_LOLLIPOP_MR1 = 22,
726 ANDROID_POST_LOLLIPOP = 23
729 void WriteToSyslog(const char *buffer);
732 void LogFullErrorReport(const char *buffer);
734 INLINE void LogFullErrorReport(const char *buffer) {}
737 #if SANITIZER_LINUX || SANITIZER_MAC
738 void WriteOneLineToSyslog(const char *s);
739 void LogMessageOnPrintf(const char *str);
741 INLINE void WriteOneLineToSyslog(const char *s) {}
742 INLINE void LogMessageOnPrintf(const char *str) {}
746 // Initialize Android logging. Any writes before this are silently lost.
747 void AndroidLogInit();
749 INLINE void AndroidLogInit() {}
752 #if SANITIZER_ANDROID
753 void SanitizerInitializeUnwinder();
754 AndroidApiLevel AndroidGetApiLevel();
756 INLINE void AndroidLogWrite(const char *buffer_unused) {}
757 INLINE void SanitizerInitializeUnwinder() {}
758 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
761 INLINE uptr GetPthreadDestructorIterations() {
762 #if SANITIZER_ANDROID
763 return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
764 #elif SANITIZER_POSIX
767 // Unused on Windows.
772 void *internal_start_thread(void(*func)(void*), void *arg);
773 void internal_join_thread(void *th);
774 void MaybeStartBackgroudThread();
776 // Make the compiler think that something is going on there.
777 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
778 // compiler from recognising it and turning it into an actual call to
779 // memset/memcpy/etc.
780 static inline void SanitizerBreakOptimization(void *arg) {
781 #if defined(_MSC_VER) && !defined(__clang__)
784 __asm__ __volatile__("" : : "r" (arg) : "memory");
788 struct SignalContext {
794 bool is_memory_access;
796 enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
798 SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp,
799 bool is_memory_access, WriteFlag write_flag)
805 is_memory_access(is_memory_access),
806 write_flag(write_flag) {}
808 // Creates signal context in a platform-specific manner.
809 static SignalContext Create(void *siginfo, void *context);
811 // Returns true if the "context" indicates a memory write.
812 static WriteFlag GetWriteFlag(void *context);
815 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
817 const char *GetRuntimeOptions(const char *env_option, const char *filename,
822 template <typename Fn>
823 class RunOnDestruction {
825 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
826 ~RunOnDestruction() { fn_(); }
832 // A simple scope guard. Usage:
833 // auto cleanup = at_scope_exit([]{ do_cleanup; });
834 template <typename Fn>
835 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
836 return RunOnDestruction<Fn>(fn);
839 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
840 // if a process uses virtual memory over 4TB (as many sanitizers like
841 // to do). This function will abort the process if running on a kernel
842 // that looks vulnerable.
843 #if SANITIZER_LINUX && SANITIZER_S390_64
844 void AvoidCVE_2016_2143();
846 INLINE void AvoidCVE_2016_2143() {}
849 struct StackDepotStats {
854 } // namespace __sanitizer
856 inline void *operator new(__sanitizer::operator_new_size_type size,
857 __sanitizer::LowLevelAllocator &alloc) {
858 return alloc.Allocate(size);
861 #endif // SANITIZER_COMMON_H