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 SetSandboxingCallback(void (*f)());
322 void InitializeCoverage(bool enabled, const char *coverage_dir);
328 void SleepForSeconds(int seconds);
329 void SleepForMillis(int millis);
331 int Atexit(void (*function)(void));
332 void SortArray(uptr *array, uptr size);
333 void SortArray(u32 *array, uptr size);
334 bool TemplateMatch(const char *templ, const char *str);
337 void NORETURN Abort();
340 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
341 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
342 const char *mmap_type, error_t err,
343 bool raw_report = false);
345 // Set the name of the current thread to 'name', return true on succees.
346 // The name may be truncated to a system-dependent limit.
347 bool SanitizerSetThreadName(const char *name);
348 // Get the name of the current thread (no more than max_len bytes),
349 // return true on succees. name should have space for at least max_len+1 bytes.
350 bool SanitizerGetThreadName(char *name, int max_len);
352 // Specific tools may override behavior of "Die" and "CheckFailed" functions
353 // to do tool-specific job.
354 typedef void (*DieCallbackType)(void);
356 // It's possible to add several callbacks that would be run when "Die" is
357 // called. The callbacks will be run in the opposite order. The tools are
358 // strongly recommended to setup all callbacks during initialization, when there
359 // is only a single thread.
360 bool AddDieCallback(DieCallbackType callback);
361 bool RemoveDieCallback(DieCallbackType callback);
363 void SetUserDieCallback(DieCallbackType callback);
365 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
367 void SetCheckFailedCallback(CheckFailedCallbackType callback);
369 // Callback will be called if soft_rss_limit_mb is given and the limit is
370 // exceeded (exceeded==true) or if rss went down below the limit
371 // (exceeded==false).
372 // The callback should be registered once at the tool init time.
373 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
375 // Functions related to signal handling.
376 typedef void (*SignalHandlerType)(int, void *, void *);
377 HandleSignalMode GetHandleSignalMode(int signum);
378 void InstallDeadlySignalHandlers(SignalHandlerType handler);
379 const char *DescribeSignalOrException(int signo);
380 // Alternative signal stack (POSIX-only).
381 void SetAlternateSignalStack();
382 void UnsetAlternateSignalStack();
384 // We don't want a summary too long.
385 const int kMaxSummaryLength = 1024;
386 // Construct a one-line string:
387 // SUMMARY: SanitizerToolName: error_message
388 // and pass it to __sanitizer_report_error_summary.
389 // If alt_tool_name is provided, it's used in place of SanitizerToolName.
390 void ReportErrorSummary(const char *error_message,
391 const char *alt_tool_name = nullptr);
392 // Same as above, but construct error_message as:
393 // error_type file:line[:column][ function]
394 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
395 const char *alt_tool_name = nullptr);
396 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
397 void ReportErrorSummary(const char *error_type, const StackTrace *trace,
398 const char *alt_tool_name = nullptr);
401 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
403 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
404 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
406 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
407 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
412 INLINE uptr MostSignificantSetBitIndex(uptr x) {
414 unsigned long up; // NOLINT
415 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
417 up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
419 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
421 #elif defined(_WIN64)
422 _BitScanReverse64(&up, x);
424 _BitScanReverse(&up, x);
429 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
431 unsigned long up; // NOLINT
432 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
434 up = __builtin_ctzll(x);
436 up = __builtin_ctzl(x);
438 #elif defined(_WIN64)
439 _BitScanForward64(&up, x);
441 _BitScanForward(&up, x);
446 INLINE bool IsPowerOfTwo(uptr x) {
447 return (x & (x - 1)) == 0;
450 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
452 if (IsPowerOfTwo(size)) return size;
454 uptr up = MostSignificantSetBitIndex(size);
455 CHECK_LT(size, (1ULL << (up + 1)));
456 CHECK_GT(size, (1ULL << up));
457 return 1ULL << (up + 1);
460 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
461 RAW_CHECK(IsPowerOfTwo(boundary));
462 return (size + boundary - 1) & ~(boundary - 1);
465 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
466 return x & ~(boundary - 1);
469 INLINE bool IsAligned(uptr a, uptr alignment) {
470 return (a & (alignment - 1)) == 0;
473 INLINE uptr Log2(uptr x) {
474 CHECK(IsPowerOfTwo(x));
475 return LeastSignificantSetBitIndex(x);
478 // Don't use std::min, std::max or std::swap, to minimize dependency
480 template<class T> T Min(T a, T b) { return a < b ? a : b; }
481 template<class T> T Max(T a, T b) { return a > b ? a : b; }
482 template<class T> void Swap(T& a, T& b) {
489 INLINE bool IsSpace(int c) {
490 return (c == ' ') || (c == '\n') || (c == '\t') ||
491 (c == '\f') || (c == '\r') || (c == '\v');
493 INLINE bool IsDigit(int c) {
494 return (c >= '0') && (c <= '9');
496 INLINE int ToLower(int c) {
497 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
500 // A low-level vector based on mmap. May incur a significant memory overhead for
502 // WARNING: The current implementation supports only POD types.
504 class InternalMmapVectorNoCtor {
506 void Initialize(uptr initial_capacity) {
507 capacity_ = Max(initial_capacity, (uptr)1);
509 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
512 UnmapOrDie(data_, capacity_ * sizeof(T));
514 T &operator[](uptr i) {
518 const T &operator[](uptr i) const {
522 void push_back(const T &element) {
523 CHECK_LE(size_, capacity_);
524 if (size_ == capacity_) {
525 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
526 Resize(new_capacity);
528 internal_memcpy(&data_[size_++], &element, sizeof(T));
532 return data_[size_ - 1];
541 const T *data() const {
547 uptr capacity() const {
550 void resize(uptr new_size) {
552 if (new_size > size_) {
553 internal_memset(&data_[size_], 0, sizeof(T) * (new_size - size_));
558 void clear() { size_ = 0; }
559 bool empty() const { return size() == 0; }
561 const T *begin() const {
567 const T *end() const {
568 return data() + size();
571 return data() + size();
575 void Resize(uptr new_capacity) {
576 CHECK_GT(new_capacity, 0);
577 CHECK_LE(size_, new_capacity);
578 T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
579 "InternalMmapVector");
580 internal_memcpy(new_data, data_, size_ * sizeof(T));
583 UnmapOrDie(old_data, capacity_ * sizeof(T));
584 capacity_ = new_capacity;
593 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
595 explicit InternalMmapVector(uptr initial_capacity) {
596 InternalMmapVectorNoCtor<T>::Initialize(initial_capacity);
598 ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
599 // Disallow evil constructors.
600 InternalMmapVector(const InternalMmapVector&);
601 void operator=(const InternalMmapVector&);
604 // HeapSort for arrays and InternalMmapVector.
605 template<class Container, class Compare>
606 void InternalSort(Container *v, uptr size, Compare comp) {
609 // Stage 1: insert elements to the heap.
610 for (uptr i = 1; i < size; i++) {
612 for (j = i; j > 0; j = p) {
614 if (comp((*v)[p], (*v)[j]))
615 Swap((*v)[j], (*v)[p]);
620 // Stage 2: swap largest element with the last one,
621 // and sink the new top.
622 for (uptr i = size - 1; i > 0; i--) {
623 Swap((*v)[0], (*v)[i]);
625 for (j = 0; j < i; j = max_ind) {
626 uptr left = 2 * j + 1;
627 uptr right = 2 * j + 2;
629 if (left < i && comp((*v)[max_ind], (*v)[left]))
631 if (right < i && comp((*v)[max_ind], (*v)[right]))
634 Swap((*v)[j], (*v)[max_ind]);
641 // Works like std::lower_bound: finds the first element that is not less
643 template <class Container, class Value, class Compare>
644 uptr InternalLowerBound(const Container &v, uptr first, uptr last,
645 const Value &val, Compare comp) {
646 while (last > first) {
647 uptr mid = (first + last) / 2;
648 if (comp(v[mid], val))
668 // When adding a new architecture, don't forget to also update
669 // script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cc.
670 inline const char *ModuleArchToString(ModuleArch arch) {
672 case kModuleArchUnknown:
674 case kModuleArchI386:
676 case kModuleArchX86_64:
678 case kModuleArchX86_64H:
680 case kModuleArchARMV6:
682 case kModuleArchARMV7:
684 case kModuleArchARMV7S:
686 case kModuleArchARMV7K:
688 case kModuleArchARM64:
691 CHECK(0 && "Invalid module arch");
695 const uptr kModuleUUIDSize = 16;
697 // Represents a binary loaded into virtual memory (e.g. this can be an
698 // executable or a shared object).
702 : full_name_(nullptr),
704 max_executable_address_(0),
705 arch_(kModuleArchUnknown),
706 instrumented_(false) {
707 internal_memset(uuid_, 0, kModuleUUIDSize);
710 void set(const char *module_name, uptr base_address);
711 void set(const char *module_name, uptr base_address, ModuleArch arch,
712 u8 uuid[kModuleUUIDSize], bool instrumented);
714 void addAddressRange(uptr beg, uptr end, bool executable, bool writable);
715 bool containsAddress(uptr address) const;
717 const char *full_name() const { return full_name_; }
718 uptr base_address() const { return base_address_; }
719 uptr max_executable_address() const { return max_executable_address_; }
720 ModuleArch arch() const { return arch_; }
721 const u8 *uuid() const { return uuid_; }
722 bool instrumented() const { return instrumented_; }
724 struct AddressRange {
731 AddressRange(uptr beg, uptr end, bool executable, bool writable)
735 executable(executable),
736 writable(writable) {}
739 const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
742 char *full_name_; // Owned.
744 uptr max_executable_address_;
746 u8 uuid_[kModuleUUIDSize];
748 IntrusiveList<AddressRange> ranges_;
751 // List of LoadedModules. OS-dependent implementation is responsible for
752 // filling this information.
753 class ListOfModules {
755 ListOfModules() : modules_(kInitialCapacity) {}
756 ~ListOfModules() { clear(); }
758 const LoadedModule *begin() const { return modules_.begin(); }
759 LoadedModule *begin() { return modules_.begin(); }
760 const LoadedModule *end() const { return modules_.end(); }
761 LoadedModule *end() { return modules_.end(); }
762 uptr size() const { return modules_.size(); }
763 const LoadedModule &operator[](uptr i) const {
764 CHECK_LT(i, modules_.size());
770 for (auto &module : modules_) module.clear();
774 InternalMmapVector<LoadedModule> modules_;
775 // We rarely have more than 16K loaded modules.
776 static const uptr kInitialCapacity = 1 << 14;
779 // Callback type for iterating over a set of memory ranges.
780 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
782 enum AndroidApiLevel {
783 ANDROID_NOT_ANDROID = 0,
785 ANDROID_LOLLIPOP_MR1 = 22,
786 ANDROID_POST_LOLLIPOP = 23
789 void WriteToSyslog(const char *buffer);
792 void LogFullErrorReport(const char *buffer);
794 INLINE void LogFullErrorReport(const char *buffer) {}
797 #if SANITIZER_LINUX || SANITIZER_MAC
798 void WriteOneLineToSyslog(const char *s);
799 void LogMessageOnPrintf(const char *str);
801 INLINE void WriteOneLineToSyslog(const char *s) {}
802 INLINE void LogMessageOnPrintf(const char *str) {}
806 // Initialize Android logging. Any writes before this are silently lost.
807 void AndroidLogInit();
809 INLINE void AndroidLogInit() {}
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 {
854 bool is_memory_access;
856 enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
858 SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp,
859 bool is_memory_access, WriteFlag write_flag)
865 is_memory_access(is_memory_access),
866 write_flag(write_flag) {}
868 static void DumpAllRegisters(void *context);
870 // Creates signal context in a platform-specific manner.
871 static SignalContext Create(void *siginfo, void *context);
873 // Returns true if the "context" indicates a memory write.
874 static WriteFlag GetWriteFlag(void *context);
877 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
881 template <typename Fn>
882 class RunOnDestruction {
884 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
885 ~RunOnDestruction() { fn_(); }
891 // A simple scope guard. Usage:
892 // auto cleanup = at_scope_exit([]{ do_cleanup; });
893 template <typename Fn>
894 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
895 return RunOnDestruction<Fn>(fn);
898 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
899 // if a process uses virtual memory over 4TB (as many sanitizers like
900 // to do). This function will abort the process if running on a kernel
901 // that looks vulnerable.
902 #if SANITIZER_LINUX && SANITIZER_S390_64
903 void AvoidCVE_2016_2143();
905 INLINE void AvoidCVE_2016_2143() {}
908 struct StackDepotStats {
913 // The default value for allocator_release_to_os_interval_ms common flag to
914 // indicate that sanitizer allocator should not attempt to release memory to OS.
915 const s32 kReleaseToOSIntervalNever = -1;
917 void CheckNoDeepBind(const char *filename, int flag);
919 } // namespace __sanitizer
921 inline void *operator new(__sanitizer::operator_new_size_type size,
922 __sanitizer::LowLevelAllocator &alloc) {
923 return alloc.Allocate(size);
926 #endif // SANITIZER_COMMON_H