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"
26 #if defined(_MSC_VER) && !defined(__clang__)
27 extern "C" void _ReadWriteBarrier();
28 #pragma intrinsic(_ReadWriteBarrier)
31 namespace __sanitizer {
34 struct BufferedStackTrace;
39 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
40 const uptr kWordSizeInBits = 8 * kWordSize;
42 #if defined(__powerpc__) || defined(__powerpc64__)
43 const uptr kCacheLineSize = 128;
45 const uptr kCacheLineSize = 64;
48 const uptr kMaxPathLength = 4096;
50 const uptr kMaxThreadStackSize = 1 << 30; // 1Gb
52 static const uptr kErrorMessageBufferSize = 1 << 16;
54 // Denotes fake PC values that come from JIT/JAVA/etc.
55 // For such PC values __tsan_symbolize_external() will be called.
56 const u64 kExternalPCBit = 1ULL << 60;
58 extern const char *SanitizerToolName; // Can be changed by the tool.
60 extern atomic_uint32_t current_verbosity;
61 INLINE void SetVerbosity(int verbosity) {
62 atomic_store(¤t_verbosity, verbosity, memory_order_relaxed);
64 INLINE int Verbosity() {
65 return atomic_load(¤t_verbosity, memory_order_relaxed);
69 extern uptr PageSizeCached;
70 INLINE uptr GetPageSizeCached() {
72 PageSizeCached = GetPageSize();
73 return PageSizeCached;
75 uptr GetMmapGranularity();
76 uptr GetMaxVirtualAddress();
77 uptr GetMaxUserVirtualAddress();
81 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
83 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
84 uptr *tls_addr, uptr *tls_size);
87 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report = false);
88 INLINE void *MmapOrDieQuietly(uptr size, const char *mem_type) {
89 return MmapOrDie(size, mem_type, /*raw_report*/ true);
91 void UnmapOrDie(void *addr, uptr size);
92 // Behaves just like MmapOrDie, but tolerates out of memory condition, in that
93 // case returns nullptr.
94 void *MmapOrDieOnFatalError(uptr size, const char *mem_type);
95 void *MmapFixedNoReserve(uptr fixed_addr, uptr size,
96 const char *name = nullptr);
97 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
98 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
99 // Behaves just like MmapFixedOrDie, but tolerates out of memory condition, in
100 // that case returns nullptr.
101 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size);
102 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name = nullptr);
103 void *MmapNoAccess(uptr size);
104 // Map aligned chunk of address space; size and alignment are powers of two.
105 // Dies on all but out of memory errors, in the latter case returns nullptr.
106 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
107 const char *mem_type);
108 // Disallow access to a memory range. Use MmapFixedNoAccess to allocate an
109 // unaccessible memory.
110 bool MprotectNoAccess(uptr addr, uptr size);
111 bool MprotectReadOnly(uptr addr, uptr size);
113 // Find an available address space.
114 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
115 uptr *largest_gap_found);
117 // Used to check if we can map shadow memory to a fixed location.
118 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
119 // Releases memory pages entirely within the [beg, end] address range. Noop if
120 // the provided range does not contain at least one entire page.
121 void ReleaseMemoryPagesToOS(uptr beg, uptr end);
122 void IncreaseTotalMmap(uptr size);
123 void DecreaseTotalMmap(uptr size);
125 void NoHugePagesInRegion(uptr addr, uptr length);
126 void DontDumpShadowMemory(uptr addr, uptr length);
127 // Check if the built VMA size matches the runtime one.
129 void RunMallocHooks(const void *ptr, uptr size);
130 void RunFreeHooks(const void *ptr);
132 class ReservedAddressRange {
134 uptr Init(uptr size, const char *name = nullptr, uptr fixed_addr = 0);
135 uptr Map(uptr fixed_addr, uptr size);
136 uptr MapOrDie(uptr fixed_addr, uptr size);
137 void Unmap(uptr addr, uptr size);
138 void *base() const { return base_; }
139 uptr size() const { return size_; }
148 typedef void (*fill_profile_f)(uptr start, uptr rss, bool file,
149 /*out*/uptr *stats, uptr stats_size);
151 // Parse the contents of /proc/self/smaps and generate a memory profile.
152 // |cb| is a tool-specific callback that fills the |stats| array containing
153 // |stats_size| elements.
154 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size);
156 // InternalScopedBuffer can be used instead of large stack arrays to
157 // keep frame size low.
158 // FIXME: use InternalAlloc instead of MmapOrDie once
159 // InternalAlloc is made libc-free.
160 template <typename T>
161 class InternalScopedBuffer {
163 explicit InternalScopedBuffer(uptr cnt) {
165 ptr_ = (T *)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
167 ~InternalScopedBuffer() { UnmapOrDie(ptr_, cnt_ * sizeof(T)); }
168 T &operator[](uptr i) { return ptr_[i]; }
169 T *data() { return ptr_; }
170 uptr size() { return cnt_ * sizeof(T); }
175 // Disallow copies and moves.
176 InternalScopedBuffer(const InternalScopedBuffer &) = delete;
177 InternalScopedBuffer &operator=(const InternalScopedBuffer &) = delete;
178 InternalScopedBuffer(InternalScopedBuffer &&) = delete;
179 InternalScopedBuffer &operator=(InternalScopedBuffer &&) = delete;
182 class InternalScopedString : public InternalScopedBuffer<char> {
184 explicit InternalScopedString(uptr max_length)
185 : InternalScopedBuffer<char>(max_length), length_(0) {
188 uptr length() { return length_; }
193 void append(const char *format, ...);
199 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
200 // constructor, so all instances of LowLevelAllocator should be
201 // linker initialized.
202 class LowLevelAllocator {
204 // Requires an external lock.
205 void *Allocate(uptr size);
207 char *allocated_end_;
208 char *allocated_current_;
210 // Set the min alignment of LowLevelAllocator to at least alignment.
211 void SetLowLevelAllocateMinAlignment(uptr alignment);
212 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
213 // Allows to register tool-specific callbacks for LowLevelAllocator.
214 // Passing NULL removes the callback.
215 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
218 void CatastrophicErrorWrite(const char *buffer, uptr length);
219 void RawWrite(const char *buffer);
220 bool ColorizeReports();
221 void RemoveANSIEscapeSequencesFromString(char *buffer);
222 void Printf(const char *format, ...);
223 void Report(const char *format, ...);
224 void SetPrintfAndReportCallback(void (*callback)(const char *));
225 #define VReport(level, ...) \
227 if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
229 #define VPrintf(level, ...) \
231 if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
234 // Lock sanitizer error reporting and protects against nested errors.
235 class ScopedErrorReportLock {
237 ScopedErrorReportLock();
238 ~ScopedErrorReportLock();
240 static void CheckLocked();
243 extern uptr stoptheworld_tracer_pid;
244 extern uptr stoptheworld_tracer_ppid;
246 // Opens the file 'file_name" and reads up to 'max_len' bytes.
247 // The resulting buffer is mmaped and stored in '*buff'.
248 // The size of the mmaped region is stored in '*buff_size'.
249 // The total number of read bytes is stored in '*read_len'.
250 // Returns true if file was successfully opened and read.
251 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
252 uptr *read_len, uptr max_len = 1 << 26,
253 error_t *errno_p = nullptr);
255 bool IsAccessibleMemoryRange(uptr beg, uptr size);
257 // Error report formatting.
258 const char *StripPathPrefix(const char *filepath,
259 const char *strip_file_prefix);
260 // Strip the directories from the module name.
261 const char *StripModuleName(const char *module);
264 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
265 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
266 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len);
267 const char *GetProcessName();
268 void UpdateProcessName();
269 void CacheBinaryName();
270 void DisableCoreDumperIfNecessary();
271 void DumpProcessMap();
272 void PrintModuleMap();
273 const char *GetEnv(const char *name);
274 bool SetEnv(const char *name, const char *value);
280 bool StackSizeIsUnlimited();
281 uptr GetStackSizeLimitInBytes();
282 void SetStackSizeLimitInBytes(uptr limit);
283 bool AddressSpaceIsUnlimited();
284 void SetAddressSpaceUnlimited();
285 void AdjustStackSize(void *attr);
286 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args);
287 void SetSandboxingCallback(void (*f)());
289 void InitializeCoverage(bool enabled, const char *coverage_dir);
295 void SleepForSeconds(int seconds);
296 void SleepForMillis(int millis);
298 u64 MonotonicNanoTime();
299 int Atexit(void (*function)(void));
300 void SortArray(uptr *array, uptr size);
301 void SortArray(u32 *array, uptr size);
302 bool TemplateMatch(const char *templ, const char *str);
305 void NORETURN Abort();
308 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
309 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
310 const char *mmap_type, error_t err,
311 bool raw_report = false);
313 // Set the name of the current thread to 'name', return true on succees.
314 // The name may be truncated to a system-dependent limit.
315 bool SanitizerSetThreadName(const char *name);
316 // Get the name of the current thread (no more than max_len bytes),
317 // return true on succees. name should have space for at least max_len+1 bytes.
318 bool SanitizerGetThreadName(char *name, int max_len);
320 // Specific tools may override behavior of "Die" and "CheckFailed" functions
321 // to do tool-specific job.
322 typedef void (*DieCallbackType)(void);
324 // It's possible to add several callbacks that would be run when "Die" is
325 // called. The callbacks will be run in the opposite order. The tools are
326 // strongly recommended to setup all callbacks during initialization, when there
327 // is only a single thread.
328 bool AddDieCallback(DieCallbackType callback);
329 bool RemoveDieCallback(DieCallbackType callback);
331 void SetUserDieCallback(DieCallbackType callback);
333 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
335 void SetCheckFailedCallback(CheckFailedCallbackType callback);
337 // Callback will be called if soft_rss_limit_mb is given and the limit is
338 // exceeded (exceeded==true) or if rss went down below the limit
339 // (exceeded==false).
340 // The callback should be registered once at the tool init time.
341 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
343 // Functions related to signal handling.
344 typedef void (*SignalHandlerType)(int, void *, void *);
345 HandleSignalMode GetHandleSignalMode(int signum);
346 void InstallDeadlySignalHandlers(SignalHandlerType handler);
349 // Each sanitizer uses slightly different implementation of stack unwinding.
350 typedef void (*UnwindSignalStackCallbackType)(const SignalContext &sig,
351 const void *callback_context,
352 BufferedStackTrace *stack);
353 // Print deadly signal report and die.
354 void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
355 UnwindSignalStackCallbackType unwind,
356 const void *unwind_context);
358 // Part of HandleDeadlySignal, exposed for asan.
359 void StartReportDeadlySignal();
360 // Part of HandleDeadlySignal, exposed for asan.
361 void ReportDeadlySignal(const SignalContext &sig, u32 tid,
362 UnwindSignalStackCallbackType unwind,
363 const void *unwind_context);
365 // Alternative signal stack (POSIX-only).
366 void SetAlternateSignalStack();
367 void UnsetAlternateSignalStack();
369 // We don't want a summary too long.
370 const int kMaxSummaryLength = 1024;
371 // Construct a one-line string:
372 // SUMMARY: SanitizerToolName: error_message
373 // and pass it to __sanitizer_report_error_summary.
374 // If alt_tool_name is provided, it's used in place of SanitizerToolName.
375 void ReportErrorSummary(const char *error_message,
376 const char *alt_tool_name = nullptr);
377 // Same as above, but construct error_message as:
378 // error_type file:line[:column][ function]
379 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
380 const char *alt_tool_name = nullptr);
381 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
382 void ReportErrorSummary(const char *error_type, const StackTrace *trace,
383 const char *alt_tool_name = nullptr);
386 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
388 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
389 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
391 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
392 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
397 INLINE uptr MostSignificantSetBitIndex(uptr x) {
399 unsigned long up; // NOLINT
400 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
402 up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
404 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
406 #elif defined(_WIN64)
407 _BitScanReverse64(&up, x);
409 _BitScanReverse(&up, x);
414 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
416 unsigned long up; // NOLINT
417 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
419 up = __builtin_ctzll(x);
421 up = __builtin_ctzl(x);
423 #elif defined(_WIN64)
424 _BitScanForward64(&up, x);
426 _BitScanForward(&up, x);
431 INLINE bool IsPowerOfTwo(uptr x) {
432 return (x & (x - 1)) == 0;
435 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
437 if (IsPowerOfTwo(size)) return size;
439 uptr up = MostSignificantSetBitIndex(size);
440 CHECK_LT(size, (1ULL << (up + 1)));
441 CHECK_GT(size, (1ULL << up));
442 return 1ULL << (up + 1);
445 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
446 RAW_CHECK(IsPowerOfTwo(boundary));
447 return (size + boundary - 1) & ~(boundary - 1);
450 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
451 return x & ~(boundary - 1);
454 INLINE bool IsAligned(uptr a, uptr alignment) {
455 return (a & (alignment - 1)) == 0;
458 INLINE uptr Log2(uptr x) {
459 CHECK(IsPowerOfTwo(x));
460 return LeastSignificantSetBitIndex(x);
463 // Don't use std::min, std::max or std::swap, to minimize dependency
465 template<class T> T Min(T a, T b) { return a < b ? a : b; }
466 template<class T> T Max(T a, T b) { return a > b ? a : b; }
467 template<class T> void Swap(T& a, T& b) {
474 INLINE bool IsSpace(int c) {
475 return (c == ' ') || (c == '\n') || (c == '\t') ||
476 (c == '\f') || (c == '\r') || (c == '\v');
478 INLINE bool IsDigit(int c) {
479 return (c >= '0') && (c <= '9');
481 INLINE int ToLower(int c) {
482 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
485 // A low-level vector based on mmap. May incur a significant memory overhead for
487 // WARNING: The current implementation supports only POD types.
489 class InternalMmapVectorNoCtor {
491 void Initialize(uptr initial_capacity) {
492 capacity_ = Max(initial_capacity, (uptr)1);
494 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
497 UnmapOrDie(data_, capacity_ * sizeof(T));
499 T &operator[](uptr i) {
503 const T &operator[](uptr i) const {
507 void push_back(const T &element) {
508 CHECK_LE(size_, capacity_);
509 if (size_ == capacity_) {
510 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
511 Resize(new_capacity);
513 internal_memcpy(&data_[size_++], &element, sizeof(T));
517 return data_[size_ - 1];
526 const T *data() const {
532 uptr capacity() const {
535 void resize(uptr new_size) {
537 if (new_size > size_) {
538 internal_memset(&data_[size_], 0, sizeof(T) * (new_size - size_));
543 void clear() { size_ = 0; }
544 bool empty() const { return size() == 0; }
546 const T *begin() const {
552 const T *end() const {
553 return data() + size();
556 return data() + size();
560 void Resize(uptr new_capacity) {
561 CHECK_GT(new_capacity, 0);
562 CHECK_LE(size_, new_capacity);
563 T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
564 "InternalMmapVector");
565 internal_memcpy(new_data, data_, size_ * sizeof(T));
568 UnmapOrDie(old_data, capacity_ * sizeof(T));
569 capacity_ = new_capacity;
578 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
580 explicit InternalMmapVector(uptr initial_capacity) {
581 InternalMmapVectorNoCtor<T>::Initialize(initial_capacity);
583 ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
584 // Disallow evil constructors.
585 InternalMmapVector(const InternalMmapVector&);
586 void operator=(const InternalMmapVector&);
589 // HeapSort for arrays and InternalMmapVector.
590 template<class Container, class Compare>
591 void InternalSort(Container *v, uptr size, Compare comp) {
594 // Stage 1: insert elements to the heap.
595 for (uptr i = 1; i < size; i++) {
597 for (j = i; j > 0; j = p) {
599 if (comp((*v)[p], (*v)[j]))
600 Swap((*v)[j], (*v)[p]);
605 // Stage 2: swap largest element with the last one,
606 // and sink the new top.
607 for (uptr i = size - 1; i > 0; i--) {
608 Swap((*v)[0], (*v)[i]);
610 for (j = 0; j < i; j = max_ind) {
611 uptr left = 2 * j + 1;
612 uptr right = 2 * j + 2;
614 if (left < i && comp((*v)[max_ind], (*v)[left]))
616 if (right < i && comp((*v)[max_ind], (*v)[right]))
619 Swap((*v)[j], (*v)[max_ind]);
626 // Works like std::lower_bound: finds the first element that is not less
628 template <class Container, class Value, class Compare>
629 uptr InternalLowerBound(const Container &v, uptr first, uptr last,
630 const Value &val, Compare comp) {
631 while (last > first) {
632 uptr mid = (first + last) / 2;
633 if (comp(v[mid], val))
653 // When adding a new architecture, don't forget to also update
654 // script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cc.
655 inline const char *ModuleArchToString(ModuleArch arch) {
657 case kModuleArchUnknown:
659 case kModuleArchI386:
661 case kModuleArchX86_64:
663 case kModuleArchX86_64H:
665 case kModuleArchARMV6:
667 case kModuleArchARMV7:
669 case kModuleArchARMV7S:
671 case kModuleArchARMV7K:
673 case kModuleArchARM64:
676 CHECK(0 && "Invalid module arch");
680 const uptr kModuleUUIDSize = 16;
681 const uptr kMaxSegName = 16;
683 // Represents a binary loaded into virtual memory (e.g. this can be an
684 // executable or a shared object).
688 : full_name_(nullptr),
690 max_executable_address_(0),
691 arch_(kModuleArchUnknown),
692 instrumented_(false) {
693 internal_memset(uuid_, 0, kModuleUUIDSize);
696 void set(const char *module_name, uptr base_address);
697 void set(const char *module_name, uptr base_address, ModuleArch arch,
698 u8 uuid[kModuleUUIDSize], bool instrumented);
700 void addAddressRange(uptr beg, uptr end, bool executable, bool writable,
701 const char *name = nullptr);
702 bool containsAddress(uptr address) const;
704 const char *full_name() const { return full_name_; }
705 uptr base_address() const { return base_address_; }
706 uptr max_executable_address() const { return max_executable_address_; }
707 ModuleArch arch() const { return arch_; }
708 const u8 *uuid() const { return uuid_; }
709 bool instrumented() const { return instrumented_; }
711 struct AddressRange {
717 char name[kMaxSegName];
719 AddressRange(uptr beg, uptr end, bool executable, bool writable,
724 executable(executable),
726 internal_strncpy(this->name, (name ? name : ""), ARRAY_SIZE(this->name));
730 const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
733 char *full_name_; // Owned.
735 uptr max_executable_address_;
737 u8 uuid_[kModuleUUIDSize];
739 IntrusiveList<AddressRange> ranges_;
742 // List of LoadedModules. OS-dependent implementation is responsible for
743 // filling this information.
744 class ListOfModules {
746 ListOfModules() : initialized(false) {}
747 ~ListOfModules() { clear(); }
749 void fallbackInit(); // Uses fallback init if available, otherwise clears
750 const LoadedModule *begin() const { return modules_.begin(); }
751 LoadedModule *begin() { return modules_.begin(); }
752 const LoadedModule *end() const { return modules_.end(); }
753 LoadedModule *end() { return modules_.end(); }
754 uptr size() const { return modules_.size(); }
755 const LoadedModule &operator[](uptr i) const {
756 CHECK_LT(i, modules_.size());
762 for (auto &module : modules_) module.clear();
766 initialized ? clear() : modules_.Initialize(kInitialCapacity);
770 InternalMmapVectorNoCtor<LoadedModule> modules_;
771 // We rarely have more than 16K loaded modules.
772 static const uptr kInitialCapacity = 1 << 14;
776 // Callback type for iterating over a set of memory ranges.
777 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
779 enum AndroidApiLevel {
780 ANDROID_NOT_ANDROID = 0,
782 ANDROID_LOLLIPOP_MR1 = 22,
783 ANDROID_POST_LOLLIPOP = 23
786 void WriteToSyslog(const char *buffer);
789 void LogFullErrorReport(const char *buffer);
791 INLINE void LogFullErrorReport(const char *buffer) {}
794 #if SANITIZER_LINUX || SANITIZER_MAC
795 void WriteOneLineToSyslog(const char *s);
796 void LogMessageOnPrintf(const char *str);
798 INLINE void WriteOneLineToSyslog(const char *s) {}
799 INLINE void LogMessageOnPrintf(const char *str) {}
803 // Initialize Android logging. Any writes before this are silently lost.
804 void AndroidLogInit();
805 void SetAbortMessage(const char *);
807 INLINE void AndroidLogInit() {}
808 // FIXME: MacOS implementation could use CRSetCrashLogMessage.
809 INLINE void SetAbortMessage(const char *) {}
812 #if SANITIZER_ANDROID
813 void SanitizerInitializeUnwinder();
814 AndroidApiLevel AndroidGetApiLevel();
816 INLINE void AndroidLogWrite(const char *buffer_unused) {}
817 INLINE void SanitizerInitializeUnwinder() {}
818 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
821 INLINE uptr GetPthreadDestructorIterations() {
822 #if SANITIZER_ANDROID
823 return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
824 #elif SANITIZER_POSIX
827 // Unused on Windows.
832 void *internal_start_thread(void(*func)(void*), void *arg);
833 void internal_join_thread(void *th);
834 void MaybeStartBackgroudThread();
836 // Make the compiler think that something is going on there.
837 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
838 // compiler from recognising it and turning it into an actual call to
839 // memset/memcpy/etc.
840 static inline void SanitizerBreakOptimization(void *arg) {
841 #if defined(_MSC_VER) && !defined(__clang__)
844 __asm__ __volatile__("" : : "r" (arg) : "memory");
848 struct SignalContext {
855 bool is_memory_access;
856 enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
858 // VS2013 doesn't implement unrestricted unions, so we need a trivial default
860 SignalContext() = default;
862 // Creates signal context in a platform-specific manner.
863 // SignalContext is going to keep pointers to siginfo and context without
865 SignalContext(void *siginfo, void *context)
869 is_memory_access(IsMemoryAccess()),
870 write_flag(GetWriteFlag()) {
874 static void DumpAllRegisters(void *context);
876 // Type of signal e.g. SIGSEGV or EXCEPTION_ACCESS_VIOLATION.
879 // String description of the signal.
880 const char *Describe() const;
882 // Returns true if signal is stack overflow.
883 bool IsStackOverflow() const;
886 // Platform specific initialization.
888 uptr GetAddress() const;
889 WriteFlag GetWriteFlag() const;
890 bool IsMemoryAccess() const;
895 template <typename Fn>
896 class RunOnDestruction {
898 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
899 ~RunOnDestruction() { fn_(); }
905 // A simple scope guard. Usage:
906 // auto cleanup = at_scope_exit([]{ do_cleanup; });
907 template <typename Fn>
908 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
909 return RunOnDestruction<Fn>(fn);
912 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
913 // if a process uses virtual memory over 4TB (as many sanitizers like
914 // to do). This function will abort the process if running on a kernel
915 // that looks vulnerable.
916 #if SANITIZER_LINUX && SANITIZER_S390_64
917 void AvoidCVE_2016_2143();
919 INLINE void AvoidCVE_2016_2143() {}
922 struct StackDepotStats {
927 // The default value for allocator_release_to_os_interval_ms common flag to
928 // indicate that sanitizer allocator should not attempt to release memory to OS.
929 const s32 kReleaseToOSIntervalNever = -1;
931 void CheckNoDeepBind(const char *filename, int flag);
933 // Returns the requested amount of random data (up to 256 bytes) that can then
934 // be used to seed a PRNG. Defaults to blocking like the underlying syscall.
935 bool GetRandom(void *buffer, uptr length, bool blocking = true);
937 // Returns the number of logical processors on the system.
938 u32 GetNumberOfCPUs();
939 extern u32 NumberOfCPUsCached;
940 INLINE u32 GetNumberOfCPUsCached() {
941 if (!NumberOfCPUsCached)
942 NumberOfCPUsCached = GetNumberOfCPUs();
943 return NumberOfCPUsCached;
946 } // namespace __sanitizer
948 inline void *operator new(__sanitizer::operator_new_size_type size,
949 __sanitizer::LowLevelAllocator &alloc) {
950 return alloc.Allocate(size);
953 #endif // SANITIZER_COMMON_H