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 void *MmapFixedNoReserve(uptr fixed_addr, uptr size,
89 const char *name = nullptr);
90 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
91 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
92 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name = nullptr);
93 void *MmapNoAccess(uptr size);
94 // Map aligned chunk of address space; size and alignment are powers of two.
95 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
96 // Disallow access to a memory range. Use MmapFixedNoAccess to allocate an
97 // unaccessible memory.
98 bool MprotectNoAccess(uptr addr, uptr size);
99 bool MprotectReadOnly(uptr addr, uptr size);
101 // Find an available address space.
102 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding);
104 // Used to check if we can map shadow memory to a fixed location.
105 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
106 // Releases memory pages entirely within the [beg, end] address range. Noop if
107 // the provided range does not contain at least one entire page.
108 void ReleaseMemoryPagesToOS(uptr beg, uptr end);
109 void IncreaseTotalMmap(uptr size);
110 void DecreaseTotalMmap(uptr size);
112 void NoHugePagesInRegion(uptr addr, uptr length);
113 void DontDumpShadowMemory(uptr addr, uptr length);
114 // Check if the built VMA size matches the runtime one.
116 void RunMallocHooks(const void *ptr, uptr size);
117 void RunFreeHooks(const void *ptr);
119 // InternalScopedBuffer can be used instead of large stack arrays to
120 // keep frame size low.
121 // FIXME: use InternalAlloc instead of MmapOrDie once
122 // InternalAlloc is made libc-free.
123 template <typename T>
124 class InternalScopedBuffer {
126 explicit InternalScopedBuffer(uptr cnt) {
128 ptr_ = (T *)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
130 ~InternalScopedBuffer() { UnmapOrDie(ptr_, cnt_ * sizeof(T)); }
131 T &operator[](uptr i) { return ptr_[i]; }
132 T *data() { return ptr_; }
133 uptr size() { return cnt_ * sizeof(T); }
138 // Disallow copies and moves.
139 InternalScopedBuffer(const InternalScopedBuffer &) = delete;
140 InternalScopedBuffer &operator=(const InternalScopedBuffer &) = delete;
141 InternalScopedBuffer(InternalScopedBuffer &&) = delete;
142 InternalScopedBuffer &operator=(InternalScopedBuffer &&) = delete;
145 class InternalScopedString : public InternalScopedBuffer<char> {
147 explicit InternalScopedString(uptr max_length)
148 : InternalScopedBuffer<char>(max_length), length_(0) {
151 uptr length() { return length_; }
156 void append(const char *format, ...);
162 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
163 // constructor, so all instances of LowLevelAllocator should be
164 // linker initialized.
165 class LowLevelAllocator {
167 // Requires an external lock.
168 void *Allocate(uptr size);
170 char *allocated_end_;
171 char *allocated_current_;
173 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
174 // Allows to register tool-specific callbacks for LowLevelAllocator.
175 // Passing NULL removes the callback.
176 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
179 void RawWrite(const char *buffer);
180 bool ColorizeReports();
181 void RemoveANSIEscapeSequencesFromString(char *buffer);
182 void Printf(const char *format, ...);
183 void Report(const char *format, ...);
184 void SetPrintfAndReportCallback(void (*callback)(const char *));
185 #define VReport(level, ...) \
187 if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
189 #define VPrintf(level, ...) \
191 if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
194 // Can be used to prevent mixing error reports from different sanitizers.
195 extern StaticSpinMutex CommonSanitizerReportMutex;
198 void Write(const char *buffer, uptr length);
199 bool SupportsColors();
200 void SetReportPath(const char *path);
202 // Don't use fields directly. They are only declared public to allow
203 // aggregate initialization.
205 // Protects fields below.
207 // Opened file descriptor. Defaults to stderr. It may be equal to
208 // kInvalidFd, in which case new file will be opened when necessary.
210 // Path prefix of report file, set via __sanitizer_set_report_path.
211 char path_prefix[kMaxPathLength];
212 // Full path to report, obtained as <path_prefix>.PID
213 char full_path[kMaxPathLength];
214 // PID of the process that opened fd. If a fork() occurs,
215 // the PID of child will be different from fd_pid.
219 void ReopenIfNecessary();
221 extern ReportFile report_file;
223 extern uptr stoptheworld_tracer_pid;
224 extern uptr stoptheworld_tracer_ppid;
226 enum FileAccessMode {
232 // Returns kInvalidFd on error.
233 fd_t OpenFile(const char *filename, FileAccessMode mode,
234 error_t *errno_p = nullptr);
235 void CloseFile(fd_t);
237 // Return true on success, false on error.
238 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size,
239 uptr *bytes_read = nullptr, error_t *error_p = nullptr);
240 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size,
241 uptr *bytes_written = nullptr, error_t *error_p = nullptr);
243 bool RenameFile(const char *oldpath, const char *newpath,
244 error_t *error_p = nullptr);
246 // Scoped file handle closer.
248 explicit FileCloser(fd_t fd) : fd(fd) {}
249 ~FileCloser() { CloseFile(fd); }
253 bool SupportsColoredOutput(fd_t fd);
255 // Opens the file 'file_name" and reads up to 'max_len' bytes.
256 // The resulting buffer is mmaped and stored in '*buff'.
257 // The size of the mmaped region is stored in '*buff_size'.
258 // The total number of read bytes is stored in '*read_len'.
259 // Returns true if file was successfully opened and read.
260 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
261 uptr *read_len, uptr max_len = 1 << 26,
262 error_t *errno_p = nullptr);
263 // Maps given file to virtual memory, and returns pointer to it
264 // (or NULL if mapping fails). Stores the size of mmaped region
266 void *MapFileToMemory(const char *file_name, uptr *buff_size);
267 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset);
269 bool IsAccessibleMemoryRange(uptr beg, uptr size);
271 // Error report formatting.
272 const char *StripPathPrefix(const char *filepath,
273 const char *strip_file_prefix);
274 // Strip the directories from the module name.
275 const char *StripModuleName(const char *module);
278 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
279 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
280 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len);
281 const char *GetProcessName();
282 void UpdateProcessName();
283 void CacheBinaryName();
284 void DisableCoreDumperIfNecessary();
285 void DumpProcessMap();
286 void PrintModuleMap();
287 bool FileExists(const char *filename);
288 const char *GetEnv(const char *name);
289 bool SetEnv(const char *name, const char *value);
290 const char *GetPwd();
291 char *FindPathToBinary(const char *name);
292 bool IsPathSeparator(const char c);
293 bool IsAbsolutePath(const char *path);
294 // Starts a subprocess and returs its pid.
295 // If *_fd parameters are not kInvalidFd their corresponding input/output
296 // streams will be redirect to the file. The files will always be closed
297 // in parent process even in case of an error.
298 // The child process will close all fds after STDERR_FILENO
299 // before passing control to a program.
300 pid_t StartSubprocess(const char *filename, const char *const argv[],
301 fd_t stdin_fd = kInvalidFd, fd_t stdout_fd = kInvalidFd,
302 fd_t stderr_fd = kInvalidFd);
303 // Checks if specified process is still running
304 bool IsProcessRunning(pid_t pid);
305 // Waits for the process to finish and returns its exit code.
306 // Returns -1 in case of an error.
307 int WaitForProcess(pid_t pid);
313 bool StackSizeIsUnlimited();
314 uptr GetStackSizeLimitInBytes();
315 void SetStackSizeLimitInBytes(uptr limit);
316 bool AddressSpaceIsUnlimited();
317 void SetAddressSpaceUnlimited();
318 void AdjustStackSize(void *attr);
319 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args);
320 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args);
321 void SetSandboxingCallback(void (*f)());
323 void CoverageUpdateMapping();
324 void CovBeforeFork();
325 void CovAfterFork(int child_pid);
327 void InitializeCoverage(bool enabled, const char *coverage_dir);
328 void ReInitializeCoverage(bool enabled, const char *coverage_dir);
334 void SleepForSeconds(int seconds);
335 void SleepForMillis(int millis);
337 int Atexit(void (*function)(void));
338 void SortArray(uptr *array, uptr size);
339 void SortArray(u32 *array, uptr size);
340 bool TemplateMatch(const char *templ, const char *str);
343 void NORETURN Abort();
346 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
347 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
348 const char *mmap_type, error_t err,
349 bool raw_report = false);
351 // Set the name of the current thread to 'name', return true on succees.
352 // The name may be truncated to a system-dependent limit.
353 bool SanitizerSetThreadName(const char *name);
354 // Get the name of the current thread (no more than max_len bytes),
355 // return true on succees. name should have space for at least max_len+1 bytes.
356 bool SanitizerGetThreadName(char *name, int max_len);
358 // Specific tools may override behavior of "Die" and "CheckFailed" functions
359 // to do tool-specific job.
360 typedef void (*DieCallbackType)(void);
362 // It's possible to add several callbacks that would be run when "Die" is
363 // called. The callbacks will be run in the opposite order. The tools are
364 // strongly recommended to setup all callbacks during initialization, when there
365 // is only a single thread.
366 bool AddDieCallback(DieCallbackType callback);
367 bool RemoveDieCallback(DieCallbackType callback);
369 void SetUserDieCallback(DieCallbackType callback);
371 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
373 void SetCheckFailedCallback(CheckFailedCallbackType callback);
375 // Callback will be called if soft_rss_limit_mb is given and the limit is
376 // exceeded (exceeded==true) or if rss went down below the limit
377 // (exceeded==false).
378 // The callback should be registered once at the tool init time.
379 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
381 // Functions related to signal handling.
382 typedef void (*SignalHandlerType)(int, void *, void *);
383 bool IsHandledDeadlySignal(int signum);
384 void InstallDeadlySignalHandlers(SignalHandlerType handler);
385 // Alternative signal stack (POSIX-only).
386 void SetAlternateSignalStack();
387 void UnsetAlternateSignalStack();
389 // We don't want a summary too long.
390 const int kMaxSummaryLength = 1024;
391 // Construct a one-line string:
392 // SUMMARY: SanitizerToolName: error_message
393 // and pass it to __sanitizer_report_error_summary.
394 void ReportErrorSummary(const char *error_message);
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 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
399 void ReportErrorSummary(const char *error_type, const StackTrace *trace);
402 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
404 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
405 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
407 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
408 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
413 INLINE uptr MostSignificantSetBitIndex(uptr x) {
415 unsigned long up; // NOLINT
416 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
418 up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
420 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
422 #elif defined(_WIN64)
423 _BitScanReverse64(&up, x);
425 _BitScanReverse(&up, x);
430 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
432 unsigned long up; // NOLINT
433 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
435 up = __builtin_ctzll(x);
437 up = __builtin_ctzl(x);
439 #elif defined(_WIN64)
440 _BitScanForward64(&up, x);
442 _BitScanForward(&up, x);
447 INLINE bool IsPowerOfTwo(uptr x) {
448 return (x & (x - 1)) == 0;
451 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
453 if (IsPowerOfTwo(size)) return size;
455 uptr up = MostSignificantSetBitIndex(size);
456 CHECK_LT(size, (1ULL << (up + 1)));
457 CHECK_GT(size, (1ULL << up));
458 return 1ULL << (up + 1);
461 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
462 RAW_CHECK(IsPowerOfTwo(boundary));
463 return (size + boundary - 1) & ~(boundary - 1);
466 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
467 return x & ~(boundary - 1);
470 INLINE bool IsAligned(uptr a, uptr alignment) {
471 return (a & (alignment - 1)) == 0;
474 INLINE uptr Log2(uptr x) {
475 CHECK(IsPowerOfTwo(x));
476 return LeastSignificantSetBitIndex(x);
479 // Don't use std::min, std::max or std::swap, to minimize dependency
481 template<class T> T Min(T a, T b) { return a < b ? a : b; }
482 template<class T> T Max(T a, T b) { return a > b ? a : b; }
483 template<class T> void Swap(T& a, T& b) {
490 INLINE bool IsSpace(int c) {
491 return (c == ' ') || (c == '\n') || (c == '\t') ||
492 (c == '\f') || (c == '\r') || (c == '\v');
494 INLINE bool IsDigit(int c) {
495 return (c >= '0') && (c <= '9');
497 INLINE int ToLower(int c) {
498 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
501 // A low-level vector based on mmap. May incur a significant memory overhead for
503 // WARNING: The current implementation supports only POD types.
505 class InternalMmapVectorNoCtor {
507 void Initialize(uptr initial_capacity) {
508 capacity_ = Max(initial_capacity, (uptr)1);
510 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
513 UnmapOrDie(data_, capacity_ * sizeof(T));
515 T &operator[](uptr i) {
519 const T &operator[](uptr i) const {
523 void push_back(const T &element) {
524 CHECK_LE(size_, capacity_);
525 if (size_ == capacity_) {
526 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
527 Resize(new_capacity);
529 internal_memcpy(&data_[size_++], &element, sizeof(T));
533 return data_[size_ - 1];
542 const T *data() const {
548 uptr capacity() const {
551 void resize(uptr new_size) {
553 if (new_size > size_) {
554 internal_memset(&data_[size_], 0, sizeof(T) * (new_size - size_));
559 void clear() { size_ = 0; }
560 bool empty() const { return size() == 0; }
562 const T *begin() const {
568 const T *end() const {
569 return data() + size();
572 return data() + size();
576 void Resize(uptr new_capacity) {
577 CHECK_GT(new_capacity, 0);
578 CHECK_LE(size_, new_capacity);
579 T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
580 "InternalMmapVector");
581 internal_memcpy(new_data, data_, size_ * sizeof(T));
584 UnmapOrDie(old_data, capacity_ * sizeof(T));
585 capacity_ = new_capacity;
594 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
596 explicit InternalMmapVector(uptr initial_capacity) {
597 InternalMmapVectorNoCtor<T>::Initialize(initial_capacity);
599 ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
600 // Disallow evil constructors.
601 InternalMmapVector(const InternalMmapVector&);
602 void operator=(const InternalMmapVector&);
605 // HeapSort for arrays and InternalMmapVector.
606 template<class Container, class Compare>
607 void InternalSort(Container *v, uptr size, Compare comp) {
610 // Stage 1: insert elements to the heap.
611 for (uptr i = 1; i < size; i++) {
613 for (j = i; j > 0; j = p) {
615 if (comp((*v)[p], (*v)[j]))
616 Swap((*v)[j], (*v)[p]);
621 // Stage 2: swap largest element with the last one,
622 // and sink the new top.
623 for (uptr i = size - 1; i > 0; i--) {
624 Swap((*v)[0], (*v)[i]);
626 for (j = 0; j < i; j = max_ind) {
627 uptr left = 2 * j + 1;
628 uptr right = 2 * j + 2;
630 if (left < i && comp((*v)[max_ind], (*v)[left]))
632 if (right < i && comp((*v)[max_ind], (*v)[right]))
635 Swap((*v)[j], (*v)[max_ind]);
642 // Works like std::lower_bound: finds the first element that is not less
644 template <class Container, class Value, class Compare>
645 uptr InternalLowerBound(const Container &v, uptr first, uptr last,
646 const Value &val, Compare comp) {
647 while (last > first) {
648 uptr mid = (first + last) / 2;
649 if (comp(v[mid], val))
669 // When adding a new architecture, don't forget to also update
670 // script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cc.
671 inline const char *ModuleArchToString(ModuleArch arch) {
673 case kModuleArchUnknown:
675 case kModuleArchI386:
677 case kModuleArchX86_64:
679 case kModuleArchX86_64H:
681 case kModuleArchARMV6:
683 case kModuleArchARMV7:
685 case kModuleArchARMV7S:
687 case kModuleArchARMV7K:
689 case kModuleArchARM64:
692 CHECK(0 && "Invalid module arch");
696 const uptr kModuleUUIDSize = 16;
698 // Represents a binary loaded into virtual memory (e.g. this can be an
699 // executable or a shared object).
703 : full_name_(nullptr),
705 max_executable_address_(0),
706 arch_(kModuleArchUnknown),
707 instrumented_(false) {
708 internal_memset(uuid_, 0, kModuleUUIDSize);
711 void set(const char *module_name, uptr base_address);
712 void set(const char *module_name, uptr base_address, ModuleArch arch,
713 u8 uuid[kModuleUUIDSize], bool instrumented);
715 void addAddressRange(uptr beg, uptr end, bool executable);
716 bool containsAddress(uptr address) const;
718 const char *full_name() const { return full_name_; }
719 uptr base_address() const { return base_address_; }
720 uptr max_executable_address() const { return max_executable_address_; }
721 ModuleArch arch() const { return arch_; }
722 const u8 *uuid() const { return uuid_; }
723 bool instrumented() const { return instrumented_; }
725 struct AddressRange {
731 AddressRange(uptr beg, uptr end, bool executable)
732 : next(nullptr), beg(beg), end(end), executable(executable) {}
735 const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
738 char *full_name_; // Owned.
740 uptr max_executable_address_;
742 u8 uuid_[kModuleUUIDSize];
744 IntrusiveList<AddressRange> ranges_;
747 // List of LoadedModules. OS-dependent implementation is responsible for
748 // filling this information.
749 class ListOfModules {
751 ListOfModules() : modules_(kInitialCapacity) {}
752 ~ListOfModules() { clear(); }
754 const LoadedModule *begin() const { return modules_.begin(); }
755 LoadedModule *begin() { return modules_.begin(); }
756 const LoadedModule *end() const { return modules_.end(); }
757 LoadedModule *end() { return modules_.end(); }
758 uptr size() const { return modules_.size(); }
759 const LoadedModule &operator[](uptr i) const {
760 CHECK_LT(i, modules_.size());
766 for (auto &module : modules_) module.clear();
770 InternalMmapVector<LoadedModule> modules_;
771 // We rarely have more than 16K loaded modules.
772 static const uptr kInitialCapacity = 1 << 14;
775 // Callback type for iterating over a set of memory ranges.
776 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
778 enum AndroidApiLevel {
779 ANDROID_NOT_ANDROID = 0,
781 ANDROID_LOLLIPOP_MR1 = 22,
782 ANDROID_POST_LOLLIPOP = 23
785 void WriteToSyslog(const char *buffer);
788 void LogFullErrorReport(const char *buffer);
790 INLINE void LogFullErrorReport(const char *buffer) {}
793 #if SANITIZER_LINUX || SANITIZER_MAC
794 void WriteOneLineToSyslog(const char *s);
795 void LogMessageOnPrintf(const char *str);
797 INLINE void WriteOneLineToSyslog(const char *s) {}
798 INLINE void LogMessageOnPrintf(const char *str) {}
802 // Initialize Android logging. Any writes before this are silently lost.
803 void AndroidLogInit();
805 INLINE void AndroidLogInit() {}
808 #if SANITIZER_ANDROID
809 void SanitizerInitializeUnwinder();
810 AndroidApiLevel AndroidGetApiLevel();
812 INLINE void AndroidLogWrite(const char *buffer_unused) {}
813 INLINE void SanitizerInitializeUnwinder() {}
814 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
817 INLINE uptr GetPthreadDestructorIterations() {
818 #if SANITIZER_ANDROID
819 return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
820 #elif SANITIZER_POSIX
823 // Unused on Windows.
828 void *internal_start_thread(void(*func)(void*), void *arg);
829 void internal_join_thread(void *th);
830 void MaybeStartBackgroudThread();
832 // Make the compiler think that something is going on there.
833 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
834 // compiler from recognising it and turning it into an actual call to
835 // memset/memcpy/etc.
836 static inline void SanitizerBreakOptimization(void *arg) {
837 #if defined(_MSC_VER) && !defined(__clang__)
840 __asm__ __volatile__("" : : "r" (arg) : "memory");
844 struct SignalContext {
850 bool is_memory_access;
852 enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
854 SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp,
855 bool is_memory_access, WriteFlag write_flag)
861 is_memory_access(is_memory_access),
862 write_flag(write_flag) {}
864 static void DumpAllRegisters(void *context);
866 // Creates signal context in a platform-specific manner.
867 static SignalContext Create(void *siginfo, void *context);
869 // Returns true if the "context" indicates a memory write.
870 static WriteFlag GetWriteFlag(void *context);
873 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
877 template <typename Fn>
878 class RunOnDestruction {
880 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
881 ~RunOnDestruction() { fn_(); }
887 // A simple scope guard. Usage:
888 // auto cleanup = at_scope_exit([]{ do_cleanup; });
889 template <typename Fn>
890 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
891 return RunOnDestruction<Fn>(fn);
894 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
895 // if a process uses virtual memory over 4TB (as many sanitizers like
896 // to do). This function will abort the process if running on a kernel
897 // that looks vulnerable.
898 #if SANITIZER_LINUX && SANITIZER_S390_64
899 void AvoidCVE_2016_2143();
901 INLINE void AvoidCVE_2016_2143() {}
904 struct StackDepotStats {
909 // The default value for allocator_release_to_os_interval_ms common flag to
910 // indicate that sanitizer allocator should not attempt to release memory to OS.
911 const s32 kReleaseToOSIntervalNever = -1;
913 } // namespace __sanitizer
915 inline void *operator new(__sanitizer::operator_new_size_type size,
916 __sanitizer::LowLevelAllocator &alloc) {
917 return alloc.Allocate(size);
920 #endif // SANITIZER_COMMON_H