1 //===-- sanitizer_common.h --------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is shared between run-time libraries of sanitizers.
11 // It declares common functions and classes that are used in both runtimes.
12 // Implementation of some functions are provided in sanitizer_common, while
13 // others must be defined by run-time library itself.
14 //===----------------------------------------------------------------------===//
15 #ifndef SANITIZER_COMMON_H
16 #define SANITIZER_COMMON_H
18 #include "sanitizer_flags.h"
19 #include "sanitizer_interface_internal.h"
20 #include "sanitizer_internal_defs.h"
21 #include "sanitizer_libc.h"
22 #include "sanitizer_list.h"
23 #include "sanitizer_mutex.h"
25 #if defined(_MSC_VER) && !defined(__clang__)
26 extern "C" void _ReadWriteBarrier();
27 #pragma intrinsic(_ReadWriteBarrier)
30 namespace __sanitizer {
33 struct BufferedStackTrace;
38 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
39 const uptr kWordSizeInBits = 8 * kWordSize;
41 const uptr kCacheLineSize = SANITIZER_CACHE_LINE_SIZE;
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_ex() 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 INLINE uptr GetPageSize() {
65 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
68 INLINE uptr GetPageSizeCached() {
73 extern uptr PageSizeCached;
74 INLINE uptr GetPageSizeCached() {
76 PageSizeCached = GetPageSize();
77 return PageSizeCached;
80 uptr GetMmapGranularity();
81 uptr GetMaxVirtualAddress();
82 uptr GetMaxUserVirtualAddress();
85 int TgKill(pid_t pid, tid_t tid, int sig);
87 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
89 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
90 uptr *tls_addr, uptr *tls_size);
93 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report = false);
94 INLINE void *MmapOrDieQuietly(uptr size, const char *mem_type) {
95 return MmapOrDie(size, mem_type, /*raw_report*/ true);
97 void UnmapOrDie(void *addr, uptr size);
98 // Behaves just like MmapOrDie, but tolerates out of memory condition, in that
99 // case returns nullptr.
100 void *MmapOrDieOnFatalError(uptr size, const char *mem_type);
101 bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name = nullptr)
103 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
104 void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name = nullptr);
105 // Behaves just like MmapFixedOrDie, but tolerates out of memory condition, in
106 // that case returns nullptr.
107 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size,
108 const char *name = nullptr);
109 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name = nullptr);
110 void *MmapNoAccess(uptr size);
111 // Map aligned chunk of address space; size and alignment are powers of two.
112 // Dies on all but out of memory errors, in the latter case returns nullptr.
113 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
114 const char *mem_type);
115 // Disallow access to a memory range. Use MmapFixedNoAccess to allocate an
116 // unaccessible memory.
117 bool MprotectNoAccess(uptr addr, uptr size);
118 bool MprotectReadOnly(uptr addr, uptr size);
120 void MprotectMallocZones(void *addr, int prot);
122 // Find an available address space.
123 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
124 uptr *largest_gap_found, uptr *max_occupied_addr);
126 // Used to check if we can map shadow memory to a fixed location.
127 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
128 // Releases memory pages entirely within the [beg, end] address range. Noop if
129 // the provided range does not contain at least one entire page.
130 void ReleaseMemoryPagesToOS(uptr beg, uptr end);
131 void IncreaseTotalMmap(uptr size);
132 void DecreaseTotalMmap(uptr size);
134 bool NoHugePagesInRegion(uptr addr, uptr length);
135 bool DontDumpShadowMemory(uptr addr, uptr length);
136 // Check if the built VMA size matches the runtime one.
138 void RunMallocHooks(const void *ptr, uptr size);
139 void RunFreeHooks(const void *ptr);
141 class ReservedAddressRange {
143 uptr Init(uptr size, const char *name = nullptr, uptr fixed_addr = 0);
144 uptr Map(uptr fixed_addr, uptr size, const char *name = nullptr);
145 uptr MapOrDie(uptr fixed_addr, uptr size, const char *name = nullptr);
146 void Unmap(uptr addr, uptr size);
147 void *base() const { return base_; }
148 uptr size() const { return size_; }
157 typedef void (*fill_profile_f)(uptr start, uptr rss, bool file,
158 /*out*/uptr *stats, uptr stats_size);
160 // Parse the contents of /proc/self/smaps and generate a memory profile.
161 // |cb| is a tool-specific callback that fills the |stats| array containing
162 // |stats_size| elements.
163 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size);
165 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
166 // constructor, so all instances of LowLevelAllocator should be
167 // linker initialized.
168 class LowLevelAllocator {
170 // Requires an external lock.
171 void *Allocate(uptr size);
173 char *allocated_end_;
174 char *allocated_current_;
176 // Set the min alignment of LowLevelAllocator to at least alignment.
177 void SetLowLevelAllocateMinAlignment(uptr alignment);
178 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
179 // Allows to register tool-specific callbacks for LowLevelAllocator.
180 // Passing NULL removes the callback.
181 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
184 void CatastrophicErrorWrite(const char *buffer, uptr length);
185 void RawWrite(const char *buffer);
186 bool ColorizeReports();
187 void RemoveANSIEscapeSequencesFromString(char *buffer);
188 void Printf(const char *format, ...);
189 void Report(const char *format, ...);
190 void SetPrintfAndReportCallback(void (*callback)(const char *));
191 #define VReport(level, ...) \
193 if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
195 #define VPrintf(level, ...) \
197 if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
200 // Lock sanitizer error reporting and protects against nested errors.
201 class ScopedErrorReportLock {
203 ScopedErrorReportLock();
204 ~ScopedErrorReportLock();
206 static void CheckLocked();
209 extern uptr stoptheworld_tracer_pid;
210 extern uptr stoptheworld_tracer_ppid;
212 bool IsAccessibleMemoryRange(uptr beg, uptr size);
214 // Error report formatting.
215 const char *StripPathPrefix(const char *filepath,
216 const char *strip_file_prefix);
217 // Strip the directories from the module name.
218 const char *StripModuleName(const char *module);
221 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
222 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
223 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len);
224 const char *GetProcessName();
225 void UpdateProcessName();
226 void CacheBinaryName();
227 void DisableCoreDumperIfNecessary();
228 void DumpProcessMap();
229 void PrintModuleMap();
230 const char *GetEnv(const char *name);
231 bool SetEnv(const char *name, const char *value);
236 void CheckMPROTECT();
240 bool StackSizeIsUnlimited();
241 void SetStackSizeLimitInBytes(uptr limit);
242 bool AddressSpaceIsUnlimited();
243 void SetAddressSpaceUnlimited();
244 void AdjustStackSize(void *attr);
245 void PlatformPrepareForSandboxing(__sanitizer_sandbox_arguments *args);
246 void SetSandboxingCallback(void (*f)());
248 void InitializeCoverage(bool enabled, const char *coverage_dir);
254 void SleepForSeconds(int seconds);
255 void SleepForMillis(int millis);
257 u64 MonotonicNanoTime();
258 int Atexit(void (*function)(void));
259 bool TemplateMatch(const char *templ, const char *str);
262 void NORETURN Abort();
265 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
266 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
267 const char *mmap_type, error_t err,
268 bool raw_report = false);
270 // Specific tools may override behavior of "Die" and "CheckFailed" functions
271 // to do tool-specific job.
272 typedef void (*DieCallbackType)(void);
274 // It's possible to add several callbacks that would be run when "Die" is
275 // called. The callbacks will be run in the opposite order. The tools are
276 // strongly recommended to setup all callbacks during initialization, when there
277 // is only a single thread.
278 bool AddDieCallback(DieCallbackType callback);
279 bool RemoveDieCallback(DieCallbackType callback);
281 void SetUserDieCallback(DieCallbackType callback);
283 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
285 void SetCheckFailedCallback(CheckFailedCallbackType callback);
287 // Callback will be called if soft_rss_limit_mb is given and the limit is
288 // exceeded (exceeded==true) or if rss went down below the limit
289 // (exceeded==false).
290 // The callback should be registered once at the tool init time.
291 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
293 // Functions related to signal handling.
294 typedef void (*SignalHandlerType)(int, void *, void *);
295 HandleSignalMode GetHandleSignalMode(int signum);
296 void InstallDeadlySignalHandlers(SignalHandlerType handler);
299 // Each sanitizer uses slightly different implementation of stack unwinding.
300 typedef void (*UnwindSignalStackCallbackType)(const SignalContext &sig,
301 const void *callback_context,
302 BufferedStackTrace *stack);
303 // Print deadly signal report and die.
304 void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
305 UnwindSignalStackCallbackType unwind,
306 const void *unwind_context);
308 // Part of HandleDeadlySignal, exposed for asan.
309 void StartReportDeadlySignal();
310 // Part of HandleDeadlySignal, exposed for asan.
311 void ReportDeadlySignal(const SignalContext &sig, u32 tid,
312 UnwindSignalStackCallbackType unwind,
313 const void *unwind_context);
315 // Alternative signal stack (POSIX-only).
316 void SetAlternateSignalStack();
317 void UnsetAlternateSignalStack();
319 // We don't want a summary too long.
320 const int kMaxSummaryLength = 1024;
321 // Construct a one-line string:
322 // SUMMARY: SanitizerToolName: error_message
323 // and pass it to __sanitizer_report_error_summary.
324 // If alt_tool_name is provided, it's used in place of SanitizerToolName.
325 void ReportErrorSummary(const char *error_message,
326 const char *alt_tool_name = nullptr);
327 // Same as above, but construct error_message as:
328 // error_type file:line[:column][ function]
329 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
330 const char *alt_tool_name = nullptr);
331 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
332 void ReportErrorSummary(const char *error_type, const StackTrace *trace,
333 const char *alt_tool_name = nullptr);
335 void ReportMmapWriteExec(int prot);
338 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
340 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
341 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
343 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
344 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
349 INLINE uptr MostSignificantSetBitIndex(uptr x) {
351 unsigned long up; // NOLINT
352 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
354 up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
356 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
358 #elif defined(_WIN64)
359 _BitScanReverse64(&up, x);
361 _BitScanReverse(&up, x);
366 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
368 unsigned long up; // NOLINT
369 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
371 up = __builtin_ctzll(x);
373 up = __builtin_ctzl(x);
375 #elif defined(_WIN64)
376 _BitScanForward64(&up, x);
378 _BitScanForward(&up, x);
383 INLINE bool IsPowerOfTwo(uptr x) {
384 return (x & (x - 1)) == 0;
387 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
389 if (IsPowerOfTwo(size)) return size;
391 uptr up = MostSignificantSetBitIndex(size);
392 CHECK_LT(size, (1ULL << (up + 1)));
393 CHECK_GT(size, (1ULL << up));
394 return 1ULL << (up + 1);
397 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
398 RAW_CHECK(IsPowerOfTwo(boundary));
399 return (size + boundary - 1) & ~(boundary - 1);
402 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
403 return x & ~(boundary - 1);
406 INLINE bool IsAligned(uptr a, uptr alignment) {
407 return (a & (alignment - 1)) == 0;
410 INLINE uptr Log2(uptr x) {
411 CHECK(IsPowerOfTwo(x));
412 return LeastSignificantSetBitIndex(x);
415 // Don't use std::min, std::max or std::swap, to minimize dependency
417 template<class T> T Min(T a, T b) { return a < b ? a : b; }
418 template<class T> T Max(T a, T b) { return a > b ? a : b; }
419 template<class T> void Swap(T& a, T& b) {
426 INLINE bool IsSpace(int c) {
427 return (c == ' ') || (c == '\n') || (c == '\t') ||
428 (c == '\f') || (c == '\r') || (c == '\v');
430 INLINE bool IsDigit(int c) {
431 return (c >= '0') && (c <= '9');
433 INLINE int ToLower(int c) {
434 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
437 // A low-level vector based on mmap. May incur a significant memory overhead for
439 // WARNING: The current implementation supports only POD types.
441 class InternalMmapVectorNoCtor {
443 void Initialize(uptr initial_capacity) {
447 reserve(initial_capacity);
449 void Destroy() { UnmapOrDie(data_, capacity_bytes_); }
450 T &operator[](uptr i) {
454 const T &operator[](uptr i) const {
458 void push_back(const T &element) {
459 CHECK_LE(size_, capacity());
460 if (size_ == capacity()) {
461 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
462 Realloc(new_capacity);
464 internal_memcpy(&data_[size_++], &element, sizeof(T));
468 return data_[size_ - 1];
477 const T *data() const {
483 uptr capacity() const { return capacity_bytes_ / sizeof(T); }
484 void reserve(uptr new_size) {
485 // Never downsize internal buffer.
486 if (new_size > capacity())
489 void resize(uptr new_size) {
490 if (new_size > size_) {
492 internal_memset(&data_[size_], 0, sizeof(T) * (new_size - size_));
497 void clear() { size_ = 0; }
498 bool empty() const { return size() == 0; }
500 const T *begin() const {
506 const T *end() const {
507 return data() + size();
510 return data() + size();
513 void swap(InternalMmapVectorNoCtor &other) {
514 Swap(data_, other.data_);
515 Swap(capacity_bytes_, other.capacity_bytes_);
516 Swap(size_, other.size_);
520 void Realloc(uptr new_capacity) {
521 CHECK_GT(new_capacity, 0);
522 CHECK_LE(size_, new_capacity);
523 uptr new_capacity_bytes =
524 RoundUpTo(new_capacity * sizeof(T), GetPageSizeCached());
525 T *new_data = (T *)MmapOrDie(new_capacity_bytes, "InternalMmapVector");
526 internal_memcpy(new_data, data_, size_ * sizeof(T));
527 UnmapOrDie(data_, capacity_bytes_);
529 capacity_bytes_ = new_capacity_bytes;
533 uptr capacity_bytes_;
537 template <typename T>
538 bool operator==(const InternalMmapVectorNoCtor<T> &lhs,
539 const InternalMmapVectorNoCtor<T> &rhs) {
540 if (lhs.size() != rhs.size()) return false;
541 return internal_memcmp(lhs.data(), rhs.data(), lhs.size() * sizeof(T)) == 0;
544 template <typename T>
545 bool operator!=(const InternalMmapVectorNoCtor<T> &lhs,
546 const InternalMmapVectorNoCtor<T> &rhs) {
547 return !(lhs == rhs);
551 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
553 InternalMmapVector() { InternalMmapVectorNoCtor<T>::Initialize(1); }
554 explicit InternalMmapVector(uptr cnt) {
555 InternalMmapVectorNoCtor<T>::Initialize(cnt);
558 ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
559 // Disallow copies and moves.
560 InternalMmapVector(const InternalMmapVector &) = delete;
561 InternalMmapVector &operator=(const InternalMmapVector &) = delete;
562 InternalMmapVector(InternalMmapVector &&) = delete;
563 InternalMmapVector &operator=(InternalMmapVector &&) = delete;
566 class InternalScopedString : public InternalMmapVector<char> {
568 explicit InternalScopedString(uptr max_length)
569 : InternalMmapVector<char>(max_length), length_(0) {
572 uptr length() { return length_; }
577 void append(const char *format, ...);
585 bool operator()(const T &a, const T &b) const { return a < b; }
588 // HeapSort for arrays and InternalMmapVector.
589 template <class T, class Compare = CompareLess<T>>
590 void Sort(T *v, uptr size, Compare comp = {}) {
593 // Stage 1: insert elements to the heap.
594 for (uptr i = 1; i < size; i++) {
596 for (j = i; j > 0; j = p) {
598 if (comp(v[p], v[j]))
604 // Stage 2: swap largest element with the last one,
605 // and sink the new top.
606 for (uptr i = size - 1; i > 0; i--) {
609 for (j = 0; j < i; j = max_ind) {
610 uptr left = 2 * j + 1;
611 uptr right = 2 * j + 2;
613 if (left < i && comp(v[max_ind], v[left]))
615 if (right < i && comp(v[max_ind], v[right]))
618 Swap(v[j], v[max_ind]);
625 // Works like std::lower_bound: finds the first element that is not less
627 template <class Container, class Value, class Compare>
628 uptr InternalLowerBound(const Container &v, uptr first, uptr last,
629 const Value &val, Compare comp) {
630 while (last > first) {
631 uptr mid = (first + last) / 2;
632 if (comp(v[mid], val))
652 // Opens the file 'file_name" and reads up to 'max_len' bytes.
653 // The resulting buffer is mmaped and stored in '*buff'.
654 // Returns true if file was successfully opened and read.
655 bool ReadFileToVector(const char *file_name,
656 InternalMmapVectorNoCtor<char> *buff,
657 uptr max_len = 1 << 26, error_t *errno_p = nullptr);
659 // Opens the file 'file_name" and reads up to 'max_len' bytes.
660 // This function is less I/O efficient than ReadFileToVector as it may reread
661 // file multiple times to avoid mmap during read attempts. It's used to read
662 // procmap, so short reads with mmap in between can produce inconsistent result.
663 // The resulting buffer is mmaped and stored in '*buff'.
664 // The size of the mmaped region is stored in '*buff_size'.
665 // The total number of read bytes is stored in '*read_len'.
666 // Returns true if file was successfully opened and read.
667 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
668 uptr *read_len, uptr max_len = 1 << 26,
669 error_t *errno_p = nullptr);
671 // When adding a new architecture, don't forget to also update
672 // script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cc.
673 inline const char *ModuleArchToString(ModuleArch arch) {
675 case kModuleArchUnknown:
677 case kModuleArchI386:
679 case kModuleArchX86_64:
681 case kModuleArchX86_64H:
683 case kModuleArchARMV6:
685 case kModuleArchARMV7:
687 case kModuleArchARMV7S:
689 case kModuleArchARMV7K:
691 case kModuleArchARM64:
694 CHECK(0 && "Invalid module arch");
698 const uptr kModuleUUIDSize = 16;
699 const uptr kMaxSegName = 16;
701 // Represents a binary loaded into virtual memory (e.g. this can be an
702 // executable or a shared object).
706 : full_name_(nullptr),
708 max_executable_address_(0),
709 arch_(kModuleArchUnknown),
710 instrumented_(false) {
711 internal_memset(uuid_, 0, kModuleUUIDSize);
714 void set(const char *module_name, uptr base_address);
715 void set(const char *module_name, uptr base_address, ModuleArch arch,
716 u8 uuid[kModuleUUIDSize], bool instrumented);
718 void addAddressRange(uptr beg, uptr end, bool executable, bool writable,
719 const char *name = nullptr);
720 bool containsAddress(uptr address) const;
722 const char *full_name() const { return full_name_; }
723 uptr base_address() const { return base_address_; }
724 uptr max_executable_address() const { return max_executable_address_; }
725 ModuleArch arch() const { return arch_; }
726 const u8 *uuid() const { return uuid_; }
727 bool instrumented() const { return instrumented_; }
729 struct AddressRange {
735 char name[kMaxSegName];
737 AddressRange(uptr beg, uptr end, bool executable, bool writable,
742 executable(executable),
744 internal_strncpy(this->name, (name ? name : ""), ARRAY_SIZE(this->name));
748 const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
751 char *full_name_; // Owned.
753 uptr max_executable_address_;
755 u8 uuid_[kModuleUUIDSize];
757 IntrusiveList<AddressRange> ranges_;
760 // List of LoadedModules. OS-dependent implementation is responsible for
761 // filling this information.
762 class ListOfModules {
764 ListOfModules() : initialized(false) {}
765 ~ListOfModules() { clear(); }
767 void fallbackInit(); // Uses fallback init if available, otherwise clears
768 const LoadedModule *begin() const { return modules_.begin(); }
769 LoadedModule *begin() { return modules_.begin(); }
770 const LoadedModule *end() const { return modules_.end(); }
771 LoadedModule *end() { return modules_.end(); }
772 uptr size() const { return modules_.size(); }
773 const LoadedModule &operator[](uptr i) const {
774 CHECK_LT(i, modules_.size());
780 for (auto &module : modules_) module.clear();
784 initialized ? clear() : modules_.Initialize(kInitialCapacity);
788 InternalMmapVectorNoCtor<LoadedModule> modules_;
789 // We rarely have more than 16K loaded modules.
790 static const uptr kInitialCapacity = 1 << 14;
794 // Callback type for iterating over a set of memory ranges.
795 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
797 enum AndroidApiLevel {
798 ANDROID_NOT_ANDROID = 0,
800 ANDROID_LOLLIPOP_MR1 = 22,
801 ANDROID_POST_LOLLIPOP = 23
804 void WriteToSyslog(const char *buffer);
806 #if defined(SANITIZER_WINDOWS) && defined(_MSC_VER) && !defined(__clang__)
807 #define SANITIZER_WIN_TRACE 1
809 #define SANITIZER_WIN_TRACE 0
812 #if SANITIZER_MAC || SANITIZER_WIN_TRACE
813 void LogFullErrorReport(const char *buffer);
815 INLINE void LogFullErrorReport(const char *buffer) {}
818 #if SANITIZER_LINUX || SANITIZER_MAC
819 void WriteOneLineToSyslog(const char *s);
820 void LogMessageOnPrintf(const char *str);
822 INLINE void WriteOneLineToSyslog(const char *s) {}
823 INLINE void LogMessageOnPrintf(const char *str) {}
826 #if SANITIZER_LINUX || SANITIZER_WIN_TRACE
827 // Initialize Android logging. Any writes before this are silently lost.
828 void AndroidLogInit();
829 void SetAbortMessage(const char *);
831 INLINE void AndroidLogInit() {}
832 // FIXME: MacOS implementation could use CRSetCrashLogMessage.
833 INLINE void SetAbortMessage(const char *) {}
836 #if SANITIZER_ANDROID
837 void SanitizerInitializeUnwinder();
838 AndroidApiLevel AndroidGetApiLevel();
840 INLINE void AndroidLogWrite(const char *buffer_unused) {}
841 INLINE void SanitizerInitializeUnwinder() {}
842 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
845 INLINE uptr GetPthreadDestructorIterations() {
846 #if SANITIZER_ANDROID
847 return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
848 #elif SANITIZER_POSIX
851 // Unused on Windows.
856 void *internal_start_thread(void(*func)(void*), void *arg);
857 void internal_join_thread(void *th);
858 void MaybeStartBackgroudThread();
860 // Make the compiler think that something is going on there.
861 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
862 // compiler from recognising it and turning it into an actual call to
863 // memset/memcpy/etc.
864 static inline void SanitizerBreakOptimization(void *arg) {
865 #if defined(_MSC_VER) && !defined(__clang__)
868 __asm__ __volatile__("" : : "r" (arg) : "memory");
872 struct SignalContext {
879 bool is_memory_access;
880 enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
882 // VS2013 doesn't implement unrestricted unions, so we need a trivial default
884 SignalContext() = default;
886 // Creates signal context in a platform-specific manner.
887 // SignalContext is going to keep pointers to siginfo and context without
889 SignalContext(void *siginfo, void *context)
893 is_memory_access(IsMemoryAccess()),
894 write_flag(GetWriteFlag()) {
898 static void DumpAllRegisters(void *context);
900 // Type of signal e.g. SIGSEGV or EXCEPTION_ACCESS_VIOLATION.
903 // String description of the signal.
904 const char *Describe() const;
906 // Returns true if signal is stack overflow.
907 bool IsStackOverflow() const;
910 // Platform specific initialization.
912 uptr GetAddress() const;
913 WriteFlag GetWriteFlag() const;
914 bool IsMemoryAccess() const;
917 void InitializePlatformEarly();
920 template <typename Fn>
921 class RunOnDestruction {
923 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
924 ~RunOnDestruction() { fn_(); }
930 // A simple scope guard. Usage:
931 // auto cleanup = at_scope_exit([]{ do_cleanup; });
932 template <typename Fn>
933 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
934 return RunOnDestruction<Fn>(fn);
937 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
938 // if a process uses virtual memory over 4TB (as many sanitizers like
939 // to do). This function will abort the process if running on a kernel
940 // that looks vulnerable.
941 #if SANITIZER_LINUX && SANITIZER_S390_64
942 void AvoidCVE_2016_2143();
944 INLINE void AvoidCVE_2016_2143() {}
947 struct StackDepotStats {
952 // The default value for allocator_release_to_os_interval_ms common flag to
953 // indicate that sanitizer allocator should not attempt to release memory to OS.
954 const s32 kReleaseToOSIntervalNever = -1;
956 void CheckNoDeepBind(const char *filename, int flag);
958 // Returns the requested amount of random data (up to 256 bytes) that can then
959 // be used to seed a PRNG. Defaults to blocking like the underlying syscall.
960 bool GetRandom(void *buffer, uptr length, bool blocking = true);
962 // Returns the number of logical processors on the system.
963 u32 GetNumberOfCPUs();
964 extern u32 NumberOfCPUsCached;
965 INLINE u32 GetNumberOfCPUsCached() {
966 if (!NumberOfCPUsCached)
967 NumberOfCPUsCached = GetNumberOfCPUs();
968 return NumberOfCPUsCached;
971 } // namespace __sanitizer
973 inline void *operator new(__sanitizer::operator_new_size_type size,
974 __sanitizer::LowLevelAllocator &alloc) {
975 return alloc.Allocate(size);
978 #endif // SANITIZER_COMMON_H