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 {
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 const uptr kMaxThreadStackSize = 1 << 30; // 1Gb
49 static const uptr kErrorMessageBufferSize = 1 << 16;
51 // Denotes fake PC values that come from JIT/JAVA/etc.
52 // For such PC values __tsan_symbolize_external() will be called.
53 const u64 kExternalPCBit = 1ULL << 60;
55 extern const char *SanitizerToolName; // Can be changed by the tool.
57 extern atomic_uint32_t current_verbosity;
58 INLINE void SetVerbosity(int verbosity) {
59 atomic_store(¤t_verbosity, verbosity, memory_order_relaxed);
61 INLINE int Verbosity() {
62 return atomic_load(¤t_verbosity, memory_order_relaxed);
66 extern uptr PageSizeCached;
67 INLINE uptr GetPageSizeCached() {
69 PageSizeCached = GetPageSize();
70 return PageSizeCached;
72 uptr GetMmapGranularity();
73 uptr GetMaxVirtualAddress();
77 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
79 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
80 uptr *tls_addr, uptr *tls_size);
83 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report = false);
84 INLINE void *MmapOrDieQuietly(uptr size, const char *mem_type) {
85 return MmapOrDie(size, mem_type, /*raw_report*/ true);
87 void UnmapOrDie(void *addr, uptr size);
88 // Behaves just like MmapOrDie, but tolerates out of memory condition, in that
89 // case returns nullptr.
90 void *MmapOrDieOnFatalError(uptr size, const char *mem_type);
91 void *MmapFixedNoReserve(uptr fixed_addr, uptr size,
92 const char *name = nullptr);
93 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
94 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
95 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name = nullptr);
96 void *MmapNoAccess(uptr size);
97 // Map aligned chunk of address space; size and alignment are powers of two.
98 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
99 // Disallow access to a memory range. Use MmapFixedNoAccess to allocate an
100 // unaccessible memory.
101 bool MprotectNoAccess(uptr addr, uptr size);
102 bool MprotectReadOnly(uptr addr, uptr size);
104 // Find an available address space.
105 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding);
107 // Used to check if we can map shadow memory to a fixed location.
108 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
109 // Releases memory pages entirely within the [beg, end] address range. Noop if
110 // the provided range does not contain at least one entire page.
111 void ReleaseMemoryPagesToOS(uptr beg, uptr end);
112 void IncreaseTotalMmap(uptr size);
113 void DecreaseTotalMmap(uptr size);
115 void NoHugePagesInRegion(uptr addr, uptr length);
116 void DontDumpShadowMemory(uptr addr, uptr length);
117 // Check if the built VMA size matches the runtime one.
119 void RunMallocHooks(const void *ptr, uptr size);
120 void RunFreeHooks(const void *ptr);
122 // InternalScopedBuffer can be used instead of large stack arrays to
123 // keep frame size low.
124 // FIXME: use InternalAlloc instead of MmapOrDie once
125 // InternalAlloc is made libc-free.
126 template <typename T>
127 class InternalScopedBuffer {
129 explicit InternalScopedBuffer(uptr cnt) {
131 ptr_ = (T *)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
133 ~InternalScopedBuffer() { UnmapOrDie(ptr_, cnt_ * sizeof(T)); }
134 T &operator[](uptr i) { return ptr_[i]; }
135 T *data() { return ptr_; }
136 uptr size() { return cnt_ * sizeof(T); }
141 // Disallow copies and moves.
142 InternalScopedBuffer(const InternalScopedBuffer &) = delete;
143 InternalScopedBuffer &operator=(const InternalScopedBuffer &) = delete;
144 InternalScopedBuffer(InternalScopedBuffer &&) = delete;
145 InternalScopedBuffer &operator=(InternalScopedBuffer &&) = delete;
148 class InternalScopedString : public InternalScopedBuffer<char> {
150 explicit InternalScopedString(uptr max_length)
151 : InternalScopedBuffer<char>(max_length), length_(0) {
154 uptr length() { return length_; }
159 void append(const char *format, ...);
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 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
177 // Allows to register tool-specific callbacks for LowLevelAllocator.
178 // Passing NULL removes the callback.
179 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
182 void RawWrite(const char *buffer);
183 bool ColorizeReports();
184 void RemoveANSIEscapeSequencesFromString(char *buffer);
185 void Printf(const char *format, ...);
186 void Report(const char *format, ...);
187 void SetPrintfAndReportCallback(void (*callback)(const char *));
188 #define VReport(level, ...) \
190 if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
192 #define VPrintf(level, ...) \
194 if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
197 // Can be used to prevent mixing error reports from different sanitizers.
198 extern StaticSpinMutex CommonSanitizerReportMutex;
201 void Write(const char *buffer, uptr length);
202 bool SupportsColors();
203 void SetReportPath(const char *path);
205 // Don't use fields directly. They are only declared public to allow
206 // aggregate initialization.
208 // Protects fields below.
210 // Opened file descriptor. Defaults to stderr. It may be equal to
211 // kInvalidFd, in which case new file will be opened when necessary.
213 // Path prefix of report file, set via __sanitizer_set_report_path.
214 char path_prefix[kMaxPathLength];
215 // Full path to report, obtained as <path_prefix>.PID
216 char full_path[kMaxPathLength];
217 // PID of the process that opened fd. If a fork() occurs,
218 // the PID of child will be different from fd_pid.
222 void ReopenIfNecessary();
224 extern ReportFile report_file;
226 extern uptr stoptheworld_tracer_pid;
227 extern uptr stoptheworld_tracer_ppid;
229 enum FileAccessMode {
235 // Returns kInvalidFd on error.
236 fd_t OpenFile(const char *filename, FileAccessMode mode,
237 error_t *errno_p = nullptr);
238 void CloseFile(fd_t);
240 // Return true on success, false on error.
241 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size,
242 uptr *bytes_read = nullptr, error_t *error_p = nullptr);
243 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size,
244 uptr *bytes_written = nullptr, error_t *error_p = nullptr);
246 bool RenameFile(const char *oldpath, const char *newpath,
247 error_t *error_p = nullptr);
249 // Scoped file handle closer.
251 explicit FileCloser(fd_t fd) : fd(fd) {}
252 ~FileCloser() { CloseFile(fd); }
256 bool SupportsColoredOutput(fd_t fd);
258 // Opens the file 'file_name" and reads up to 'max_len' bytes.
259 // The resulting buffer is mmaped and stored in '*buff'.
260 // The size of the mmaped region is stored in '*buff_size'.
261 // The total number of read bytes is stored in '*read_len'.
262 // Returns true if file was successfully opened and read.
263 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
264 uptr *read_len, uptr max_len = 1 << 26,
265 error_t *errno_p = nullptr);
266 // Maps given file to virtual memory, and returns pointer to it
267 // (or NULL if mapping fails). Stores the size of mmaped region
269 void *MapFileToMemory(const char *file_name, uptr *buff_size);
270 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset);
272 bool IsAccessibleMemoryRange(uptr beg, uptr size);
274 // Error report formatting.
275 const char *StripPathPrefix(const char *filepath,
276 const char *strip_file_prefix);
277 // Strip the directories from the module name.
278 const char *StripModuleName(const char *module);
281 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
282 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
283 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len);
284 const char *GetProcessName();
285 void UpdateProcessName();
286 void CacheBinaryName();
287 void DisableCoreDumperIfNecessary();
288 void DumpProcessMap();
289 void PrintModuleMap();
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 SetSandboxingCallback(void (*f)());
325 void InitializeCoverage(bool enabled, const char *coverage_dir);
331 void SleepForSeconds(int seconds);
332 void SleepForMillis(int millis);
334 int Atexit(void (*function)(void));
335 void SortArray(uptr *array, uptr size);
336 void SortArray(u32 *array, uptr size);
337 bool TemplateMatch(const char *templ, const char *str);
340 void NORETURN Abort();
343 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
344 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
345 const char *mmap_type, error_t err,
346 bool raw_report = false);
348 // Set the name of the current thread to 'name', return true on succees.
349 // The name may be truncated to a system-dependent limit.
350 bool SanitizerSetThreadName(const char *name);
351 // Get the name of the current thread (no more than max_len bytes),
352 // return true on succees. name should have space for at least max_len+1 bytes.
353 bool SanitizerGetThreadName(char *name, int max_len);
355 // Specific tools may override behavior of "Die" and "CheckFailed" functions
356 // to do tool-specific job.
357 typedef void (*DieCallbackType)(void);
359 // It's possible to add several callbacks that would be run when "Die" is
360 // called. The callbacks will be run in the opposite order. The tools are
361 // strongly recommended to setup all callbacks during initialization, when there
362 // is only a single thread.
363 bool AddDieCallback(DieCallbackType callback);
364 bool RemoveDieCallback(DieCallbackType callback);
366 void SetUserDieCallback(DieCallbackType callback);
368 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
370 void SetCheckFailedCallback(CheckFailedCallbackType callback);
372 // Callback will be called if soft_rss_limit_mb is given and the limit is
373 // exceeded (exceeded==true) or if rss went down below the limit
374 // (exceeded==false).
375 // The callback should be registered once at the tool init time.
376 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
378 // Functions related to signal handling.
379 typedef void (*SignalHandlerType)(int, void *, void *);
380 HandleSignalMode GetHandleSignalMode(int signum);
381 void InstallDeadlySignalHandlers(SignalHandlerType handler);
382 const char *DescribeSignalOrException(int signo);
383 // Alternative signal stack (POSIX-only).
384 void SetAlternateSignalStack();
385 void UnsetAlternateSignalStack();
387 // We don't want a summary too long.
388 const int kMaxSummaryLength = 1024;
389 // Construct a one-line string:
390 // SUMMARY: SanitizerToolName: error_message
391 // and pass it to __sanitizer_report_error_summary.
392 // If alt_tool_name is provided, it's used in place of SanitizerToolName.
393 void ReportErrorSummary(const char *error_message,
394 const char *alt_tool_name = nullptr);
395 // Same as above, but construct error_message as:
396 // error_type file:line[:column][ function]
397 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
398 const char *alt_tool_name = nullptr);
399 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
400 void ReportErrorSummary(const char *error_type, const StackTrace *trace,
401 const char *alt_tool_name = nullptr);
404 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
406 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
407 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
409 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
410 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
415 INLINE uptr MostSignificantSetBitIndex(uptr x) {
417 unsigned long up; // NOLINT
418 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
420 up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
422 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
424 #elif defined(_WIN64)
425 _BitScanReverse64(&up, x);
427 _BitScanReverse(&up, x);
432 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
434 unsigned long up; // NOLINT
435 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
437 up = __builtin_ctzll(x);
439 up = __builtin_ctzl(x);
441 #elif defined(_WIN64)
442 _BitScanForward64(&up, x);
444 _BitScanForward(&up, x);
449 INLINE bool IsPowerOfTwo(uptr x) {
450 return (x & (x - 1)) == 0;
453 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
455 if (IsPowerOfTwo(size)) return size;
457 uptr up = MostSignificantSetBitIndex(size);
458 CHECK_LT(size, (1ULL << (up + 1)));
459 CHECK_GT(size, (1ULL << up));
460 return 1ULL << (up + 1);
463 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
464 RAW_CHECK(IsPowerOfTwo(boundary));
465 return (size + boundary - 1) & ~(boundary - 1);
468 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
469 return x & ~(boundary - 1);
472 INLINE bool IsAligned(uptr a, uptr alignment) {
473 return (a & (alignment - 1)) == 0;
476 INLINE uptr Log2(uptr x) {
477 CHECK(IsPowerOfTwo(x));
478 return LeastSignificantSetBitIndex(x);
481 // Don't use std::min, std::max or std::swap, to minimize dependency
483 template<class T> T Min(T a, T b) { return a < b ? a : b; }
484 template<class T> T Max(T a, T b) { return a > b ? a : b; }
485 template<class T> void Swap(T& a, T& b) {
492 INLINE bool IsSpace(int c) {
493 return (c == ' ') || (c == '\n') || (c == '\t') ||
494 (c == '\f') || (c == '\r') || (c == '\v');
496 INLINE bool IsDigit(int c) {
497 return (c >= '0') && (c <= '9');
499 INLINE int ToLower(int c) {
500 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
503 // A low-level vector based on mmap. May incur a significant memory overhead for
505 // WARNING: The current implementation supports only POD types.
507 class InternalMmapVectorNoCtor {
509 void Initialize(uptr initial_capacity) {
510 capacity_ = Max(initial_capacity, (uptr)1);
512 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
515 UnmapOrDie(data_, capacity_ * sizeof(T));
517 T &operator[](uptr i) {
521 const T &operator[](uptr i) const {
525 void push_back(const T &element) {
526 CHECK_LE(size_, capacity_);
527 if (size_ == capacity_) {
528 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
529 Resize(new_capacity);
531 internal_memcpy(&data_[size_++], &element, sizeof(T));
535 return data_[size_ - 1];
544 const T *data() const {
550 uptr capacity() const {
553 void resize(uptr new_size) {
555 if (new_size > size_) {
556 internal_memset(&data_[size_], 0, sizeof(T) * (new_size - size_));
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 // Works like std::lower_bound: finds the first element that is not less
646 template <class Container, class Value, class Compare>
647 uptr InternalLowerBound(const Container &v, uptr first, uptr last,
648 const Value &val, Compare comp) {
649 while (last > first) {
650 uptr mid = (first + last) / 2;
651 if (comp(v[mid], val))
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;
700 // Represents a binary loaded into virtual memory (e.g. this can be an
701 // executable or a shared object).
705 : full_name_(nullptr),
707 max_executable_address_(0),
708 arch_(kModuleArchUnknown),
709 instrumented_(false) {
710 internal_memset(uuid_, 0, kModuleUUIDSize);
713 void set(const char *module_name, uptr base_address);
714 void set(const char *module_name, uptr base_address, ModuleArch arch,
715 u8 uuid[kModuleUUIDSize], bool instrumented);
717 void addAddressRange(uptr beg, uptr end, bool executable, bool writable);
718 bool containsAddress(uptr address) const;
720 const char *full_name() const { return full_name_; }
721 uptr base_address() const { return base_address_; }
722 uptr max_executable_address() const { return max_executable_address_; }
723 ModuleArch arch() const { return arch_; }
724 const u8 *uuid() const { return uuid_; }
725 bool instrumented() const { return instrumented_; }
727 struct AddressRange {
734 AddressRange(uptr beg, uptr end, bool executable, bool writable)
738 executable(executable),
739 writable(writable) {}
742 const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
745 char *full_name_; // Owned.
747 uptr max_executable_address_;
749 u8 uuid_[kModuleUUIDSize];
751 IntrusiveList<AddressRange> ranges_;
754 // List of LoadedModules. OS-dependent implementation is responsible for
755 // filling this information.
756 class ListOfModules {
758 ListOfModules() : modules_(kInitialCapacity) {}
759 ~ListOfModules() { clear(); }
761 const LoadedModule *begin() const { return modules_.begin(); }
762 LoadedModule *begin() { return modules_.begin(); }
763 const LoadedModule *end() const { return modules_.end(); }
764 LoadedModule *end() { return modules_.end(); }
765 uptr size() const { return modules_.size(); }
766 const LoadedModule &operator[](uptr i) const {
767 CHECK_LT(i, modules_.size());
773 for (auto &module : modules_) module.clear();
777 InternalMmapVector<LoadedModule> modules_;
778 // We rarely have more than 16K loaded modules.
779 static const uptr kInitialCapacity = 1 << 14;
782 // Callback type for iterating over a set of memory ranges.
783 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
785 enum AndroidApiLevel {
786 ANDROID_NOT_ANDROID = 0,
788 ANDROID_LOLLIPOP_MR1 = 22,
789 ANDROID_POST_LOLLIPOP = 23
792 void WriteToSyslog(const char *buffer);
795 void LogFullErrorReport(const char *buffer);
797 INLINE void LogFullErrorReport(const char *buffer) {}
800 #if SANITIZER_LINUX || SANITIZER_MAC
801 void WriteOneLineToSyslog(const char *s);
802 void LogMessageOnPrintf(const char *str);
804 INLINE void WriteOneLineToSyslog(const char *s) {}
805 INLINE void LogMessageOnPrintf(const char *str) {}
809 // Initialize Android logging. Any writes before this are silently lost.
810 void AndroidLogInit();
812 INLINE void AndroidLogInit() {}
815 #if SANITIZER_ANDROID
816 void SanitizerInitializeUnwinder();
817 AndroidApiLevel AndroidGetApiLevel();
819 INLINE void AndroidLogWrite(const char *buffer_unused) {}
820 INLINE void SanitizerInitializeUnwinder() {}
821 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
824 INLINE uptr GetPthreadDestructorIterations() {
825 #if SANITIZER_ANDROID
826 return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
827 #elif SANITIZER_POSIX
830 // Unused on Windows.
835 void *internal_start_thread(void(*func)(void*), void *arg);
836 void internal_join_thread(void *th);
837 void MaybeStartBackgroudThread();
839 // Make the compiler think that something is going on there.
840 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
841 // compiler from recognising it and turning it into an actual call to
842 // memset/memcpy/etc.
843 static inline void SanitizerBreakOptimization(void *arg) {
844 #if defined(_MSC_VER) && !defined(__clang__)
847 __asm__ __volatile__("" : : "r" (arg) : "memory");
851 struct SignalContext {
857 bool is_memory_access;
859 enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
861 SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp,
862 bool is_memory_access, WriteFlag write_flag)
868 is_memory_access(is_memory_access),
869 write_flag(write_flag) {}
871 static void DumpAllRegisters(void *context);
873 // Creates signal context in a platform-specific manner.
874 static SignalContext Create(void *siginfo, void *context);
876 // Returns true if the "context" indicates a memory write.
877 static WriteFlag GetWriteFlag(void *context);
880 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
884 template <typename Fn>
885 class RunOnDestruction {
887 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
888 ~RunOnDestruction() { fn_(); }
894 // A simple scope guard. Usage:
895 // auto cleanup = at_scope_exit([]{ do_cleanup; });
896 template <typename Fn>
897 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
898 return RunOnDestruction<Fn>(fn);
901 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
902 // if a process uses virtual memory over 4TB (as many sanitizers like
903 // to do). This function will abort the process if running on a kernel
904 // that looks vulnerable.
905 #if SANITIZER_LINUX && SANITIZER_S390_64
906 void AvoidCVE_2016_2143();
908 INLINE void AvoidCVE_2016_2143() {}
911 struct StackDepotStats {
916 // The default value for allocator_release_to_os_interval_ms common flag to
917 // indicate that sanitizer allocator should not attempt to release memory to OS.
918 const s32 kReleaseToOSIntervalNever = -1;
920 void CheckNoDeepBind(const char *filename, int flag);
922 } // namespace __sanitizer
924 inline void *operator new(__sanitizer::operator_new_size_type size,
925 __sanitizer::LowLevelAllocator &alloc) {
926 return alloc.Allocate(size);
929 #endif // SANITIZER_COMMON_H