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 const char *DescribeSignalOrException(int signo);
386 // Alternative signal stack (POSIX-only).
387 void SetAlternateSignalStack();
388 void UnsetAlternateSignalStack();
390 // We don't want a summary too long.
391 const int kMaxSummaryLength = 1024;
392 // Construct a one-line string:
393 // SUMMARY: SanitizerToolName: error_message
394 // and pass it to __sanitizer_report_error_summary.
395 // If alt_tool_name is provided, it's used in place of SanitizerToolName.
396 void ReportErrorSummary(const char *error_message,
397 const char *alt_tool_name = nullptr);
398 // Same as above, but construct error_message as:
399 // error_type file:line[:column][ function]
400 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
401 const char *alt_tool_name = nullptr);
402 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
403 void ReportErrorSummary(const char *error_type, const StackTrace *trace,
404 const char *alt_tool_name = nullptr);
407 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
409 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
410 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
412 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
413 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
418 INLINE uptr MostSignificantSetBitIndex(uptr x) {
420 unsigned long up; // NOLINT
421 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
423 up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
425 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
427 #elif defined(_WIN64)
428 _BitScanReverse64(&up, x);
430 _BitScanReverse(&up, x);
435 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
437 unsigned long up; // NOLINT
438 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
440 up = __builtin_ctzll(x);
442 up = __builtin_ctzl(x);
444 #elif defined(_WIN64)
445 _BitScanForward64(&up, x);
447 _BitScanForward(&up, x);
452 INLINE bool IsPowerOfTwo(uptr x) {
453 return (x & (x - 1)) == 0;
456 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
458 if (IsPowerOfTwo(size)) return size;
460 uptr up = MostSignificantSetBitIndex(size);
461 CHECK_LT(size, (1ULL << (up + 1)));
462 CHECK_GT(size, (1ULL << up));
463 return 1ULL << (up + 1);
466 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
467 RAW_CHECK(IsPowerOfTwo(boundary));
468 return (size + boundary - 1) & ~(boundary - 1);
471 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
472 return x & ~(boundary - 1);
475 INLINE bool IsAligned(uptr a, uptr alignment) {
476 return (a & (alignment - 1)) == 0;
479 INLINE uptr Log2(uptr x) {
480 CHECK(IsPowerOfTwo(x));
481 return LeastSignificantSetBitIndex(x);
484 // Don't use std::min, std::max or std::swap, to minimize dependency
486 template<class T> T Min(T a, T b) { return a < b ? a : b; }
487 template<class T> T Max(T a, T b) { return a > b ? a : b; }
488 template<class T> void Swap(T& a, T& b) {
495 INLINE bool IsSpace(int c) {
496 return (c == ' ') || (c == '\n') || (c == '\t') ||
497 (c == '\f') || (c == '\r') || (c == '\v');
499 INLINE bool IsDigit(int c) {
500 return (c >= '0') && (c <= '9');
502 INLINE int ToLower(int c) {
503 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
506 // A low-level vector based on mmap. May incur a significant memory overhead for
508 // WARNING: The current implementation supports only POD types.
510 class InternalMmapVectorNoCtor {
512 void Initialize(uptr initial_capacity) {
513 capacity_ = Max(initial_capacity, (uptr)1);
515 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
518 UnmapOrDie(data_, capacity_ * sizeof(T));
520 T &operator[](uptr i) {
524 const T &operator[](uptr i) const {
528 void push_back(const T &element) {
529 CHECK_LE(size_, capacity_);
530 if (size_ == capacity_) {
531 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
532 Resize(new_capacity);
534 internal_memcpy(&data_[size_++], &element, sizeof(T));
538 return data_[size_ - 1];
547 const T *data() const {
553 uptr capacity() const {
556 void resize(uptr new_size) {
558 if (new_size > size_) {
559 internal_memset(&data_[size_], 0, sizeof(T) * (new_size - size_));
564 void clear() { size_ = 0; }
565 bool empty() const { return size() == 0; }
567 const T *begin() const {
573 const T *end() const {
574 return data() + size();
577 return data() + size();
581 void Resize(uptr new_capacity) {
582 CHECK_GT(new_capacity, 0);
583 CHECK_LE(size_, new_capacity);
584 T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
585 "InternalMmapVector");
586 internal_memcpy(new_data, data_, size_ * sizeof(T));
589 UnmapOrDie(old_data, capacity_ * sizeof(T));
590 capacity_ = new_capacity;
599 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
601 explicit InternalMmapVector(uptr initial_capacity) {
602 InternalMmapVectorNoCtor<T>::Initialize(initial_capacity);
604 ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
605 // Disallow evil constructors.
606 InternalMmapVector(const InternalMmapVector&);
607 void operator=(const InternalMmapVector&);
610 // HeapSort for arrays and InternalMmapVector.
611 template<class Container, class Compare>
612 void InternalSort(Container *v, uptr size, Compare comp) {
615 // Stage 1: insert elements to the heap.
616 for (uptr i = 1; i < size; i++) {
618 for (j = i; j > 0; j = p) {
620 if (comp((*v)[p], (*v)[j]))
621 Swap((*v)[j], (*v)[p]);
626 // Stage 2: swap largest element with the last one,
627 // and sink the new top.
628 for (uptr i = size - 1; i > 0; i--) {
629 Swap((*v)[0], (*v)[i]);
631 for (j = 0; j < i; j = max_ind) {
632 uptr left = 2 * j + 1;
633 uptr right = 2 * j + 2;
635 if (left < i && comp((*v)[max_ind], (*v)[left]))
637 if (right < i && comp((*v)[max_ind], (*v)[right]))
640 Swap((*v)[j], (*v)[max_ind]);
647 // Works like std::lower_bound: finds the first element that is not less
649 template <class Container, class Value, class Compare>
650 uptr InternalLowerBound(const Container &v, uptr first, uptr last,
651 const Value &val, Compare comp) {
652 while (last > first) {
653 uptr mid = (first + last) / 2;
654 if (comp(v[mid], val))
674 // When adding a new architecture, don't forget to also update
675 // script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cc.
676 inline const char *ModuleArchToString(ModuleArch arch) {
678 case kModuleArchUnknown:
680 case kModuleArchI386:
682 case kModuleArchX86_64:
684 case kModuleArchX86_64H:
686 case kModuleArchARMV6:
688 case kModuleArchARMV7:
690 case kModuleArchARMV7S:
692 case kModuleArchARMV7K:
694 case kModuleArchARM64:
697 CHECK(0 && "Invalid module arch");
701 const uptr kModuleUUIDSize = 16;
703 // Represents a binary loaded into virtual memory (e.g. this can be an
704 // executable or a shared object).
708 : full_name_(nullptr),
710 max_executable_address_(0),
711 arch_(kModuleArchUnknown),
712 instrumented_(false) {
713 internal_memset(uuid_, 0, kModuleUUIDSize);
716 void set(const char *module_name, uptr base_address);
717 void set(const char *module_name, uptr base_address, ModuleArch arch,
718 u8 uuid[kModuleUUIDSize], bool instrumented);
720 void addAddressRange(uptr beg, uptr end, bool executable, bool writable);
721 bool containsAddress(uptr address) const;
723 const char *full_name() const { return full_name_; }
724 uptr base_address() const { return base_address_; }
725 uptr max_executable_address() const { return max_executable_address_; }
726 ModuleArch arch() const { return arch_; }
727 const u8 *uuid() const { return uuid_; }
728 bool instrumented() const { return instrumented_; }
730 struct AddressRange {
737 AddressRange(uptr beg, uptr end, bool executable, bool writable)
741 executable(executable),
742 writable(writable) {}
745 const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
748 char *full_name_; // Owned.
750 uptr max_executable_address_;
752 u8 uuid_[kModuleUUIDSize];
754 IntrusiveList<AddressRange> ranges_;
757 // List of LoadedModules. OS-dependent implementation is responsible for
758 // filling this information.
759 class ListOfModules {
761 ListOfModules() : modules_(kInitialCapacity) {}
762 ~ListOfModules() { clear(); }
764 const LoadedModule *begin() const { return modules_.begin(); }
765 LoadedModule *begin() { return modules_.begin(); }
766 const LoadedModule *end() const { return modules_.end(); }
767 LoadedModule *end() { return modules_.end(); }
768 uptr size() const { return modules_.size(); }
769 const LoadedModule &operator[](uptr i) const {
770 CHECK_LT(i, modules_.size());
776 for (auto &module : modules_) module.clear();
780 InternalMmapVector<LoadedModule> modules_;
781 // We rarely have more than 16K loaded modules.
782 static const uptr kInitialCapacity = 1 << 14;
785 // Callback type for iterating over a set of memory ranges.
786 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
788 enum AndroidApiLevel {
789 ANDROID_NOT_ANDROID = 0,
791 ANDROID_LOLLIPOP_MR1 = 22,
792 ANDROID_POST_LOLLIPOP = 23
795 void WriteToSyslog(const char *buffer);
798 void LogFullErrorReport(const char *buffer);
800 INLINE void LogFullErrorReport(const char *buffer) {}
803 #if SANITIZER_LINUX || SANITIZER_MAC
804 void WriteOneLineToSyslog(const char *s);
805 void LogMessageOnPrintf(const char *str);
807 INLINE void WriteOneLineToSyslog(const char *s) {}
808 INLINE void LogMessageOnPrintf(const char *str) {}
812 // Initialize Android logging. Any writes before this are silently lost.
813 void AndroidLogInit();
815 INLINE void AndroidLogInit() {}
818 #if SANITIZER_ANDROID
819 void SanitizerInitializeUnwinder();
820 AndroidApiLevel AndroidGetApiLevel();
822 INLINE void AndroidLogWrite(const char *buffer_unused) {}
823 INLINE void SanitizerInitializeUnwinder() {}
824 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
827 INLINE uptr GetPthreadDestructorIterations() {
828 #if SANITIZER_ANDROID
829 return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
830 #elif SANITIZER_POSIX
833 // Unused on Windows.
838 void *internal_start_thread(void(*func)(void*), void *arg);
839 void internal_join_thread(void *th);
840 void MaybeStartBackgroudThread();
842 // Make the compiler think that something is going on there.
843 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
844 // compiler from recognising it and turning it into an actual call to
845 // memset/memcpy/etc.
846 static inline void SanitizerBreakOptimization(void *arg) {
847 #if defined(_MSC_VER) && !defined(__clang__)
850 __asm__ __volatile__("" : : "r" (arg) : "memory");
854 struct SignalContext {
860 bool is_memory_access;
862 enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
864 SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp,
865 bool is_memory_access, WriteFlag write_flag)
871 is_memory_access(is_memory_access),
872 write_flag(write_flag) {}
874 static void DumpAllRegisters(void *context);
876 // Creates signal context in a platform-specific manner.
877 static SignalContext Create(void *siginfo, void *context);
879 // Returns true if the "context" indicates a memory write.
880 static WriteFlag GetWriteFlag(void *context);
883 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
887 template <typename Fn>
888 class RunOnDestruction {
890 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
891 ~RunOnDestruction() { fn_(); }
897 // A simple scope guard. Usage:
898 // auto cleanup = at_scope_exit([]{ do_cleanup; });
899 template <typename Fn>
900 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
901 return RunOnDestruction<Fn>(fn);
904 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
905 // if a process uses virtual memory over 4TB (as many sanitizers like
906 // to do). This function will abort the process if running on a kernel
907 // that looks vulnerable.
908 #if SANITIZER_LINUX && SANITIZER_S390_64
909 void AvoidCVE_2016_2143();
911 INLINE void AvoidCVE_2016_2143() {}
914 struct StackDepotStats {
919 // The default value for allocator_release_to_os_interval_ms common flag to
920 // indicate that sanitizer allocator should not attempt to release memory to OS.
921 const s32 kReleaseToOSIntervalNever = -1;
923 void CheckNoDeepBind(const char *filename, int flag);
925 } // namespace __sanitizer
927 inline void *operator new(__sanitizer::operator_new_size_type size,
928 __sanitizer::LowLevelAllocator &alloc) {
929 return alloc.Allocate(size);
932 #endif // SANITIZER_COMMON_H