Home | History | Annotate | Download | only in sanitizer_common
      1 //===-- sanitizer_common.h --------------------------------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file is shared between run-time libraries of sanitizers.
     11 //
     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
     18 
     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"
     25 
     26 namespace __sanitizer {
     27 struct StackTrace;
     28 struct AddressInfo;
     29 
     30 // Constants.
     31 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
     32 const uptr kWordSizeInBits = 8 * kWordSize;
     33 
     34 #if defined(__powerpc__) || defined(__powerpc64__)
     35   const uptr kCacheLineSize = 128;
     36 #else
     37   const uptr kCacheLineSize = 64;
     38 #endif
     39 
     40 const uptr kMaxPathLength = 4096;
     41 
     42 // 16K loaded modules should be enough for everyone.
     43 static const uptr kMaxNumberOfModules = 1 << 14;
     44 
     45 const uptr kMaxThreadStackSize = 1 << 30;  // 1Gb
     46 
     47 extern const char *SanitizerToolName;  // Can be changed by the tool.
     48 
     49 extern atomic_uint32_t current_verbosity;
     50 INLINE void SetVerbosity(int verbosity) {
     51   atomic_store(&current_verbosity, verbosity, memory_order_relaxed);
     52 }
     53 INLINE int Verbosity() {
     54   return atomic_load(&current_verbosity, memory_order_relaxed);
     55 }
     56 
     57 uptr GetPageSize();
     58 uptr GetPageSizeCached();
     59 uptr GetMmapGranularity();
     60 uptr GetMaxVirtualAddress();
     61 // Threads
     62 uptr GetTid();
     63 uptr GetThreadSelf();
     64 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
     65                                 uptr *stack_bottom);
     66 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
     67                           uptr *tls_addr, uptr *tls_size);
     68 
     69 // Memory management
     70 void *MmapOrDie(uptr size, const char *mem_type);
     71 void UnmapOrDie(void *addr, uptr size);
     72 void *MmapFixedNoReserve(uptr fixed_addr, uptr size);
     73 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
     74 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
     75 void *MmapNoAccess(uptr fixed_addr, uptr size);
     76 // Map aligned chunk of address space; size and alignment are powers of two.
     77 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
     78 // Disallow access to a memory range.  Use MmapNoAccess to allocate an
     79 // unaccessible memory.
     80 bool MprotectNoAccess(uptr addr, uptr size);
     81 
     82 // Used to check if we can map shadow memory to a fixed location.
     83 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
     84 void FlushUnneededShadowMemory(uptr addr, uptr size);
     85 void IncreaseTotalMmap(uptr size);
     86 void DecreaseTotalMmap(uptr size);
     87 uptr GetRSS();
     88 void NoHugePagesInRegion(uptr addr, uptr length);
     89 void DontDumpShadowMemory(uptr addr, uptr length);
     90 
     91 // InternalScopedBuffer can be used instead of large stack arrays to
     92 // keep frame size low.
     93 // FIXME: use InternalAlloc instead of MmapOrDie once
     94 // InternalAlloc is made libc-free.
     95 template<typename T>
     96 class InternalScopedBuffer {
     97  public:
     98   explicit InternalScopedBuffer(uptr cnt) {
     99     cnt_ = cnt;
    100     ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
    101   }
    102   ~InternalScopedBuffer() {
    103     UnmapOrDie(ptr_, cnt_ * sizeof(T));
    104   }
    105   T &operator[](uptr i) { return ptr_[i]; }
    106   T *data() { return ptr_; }
    107   uptr size() { return cnt_ * sizeof(T); }
    108 
    109  private:
    110   T *ptr_;
    111   uptr cnt_;
    112   // Disallow evil constructors.
    113   InternalScopedBuffer(const InternalScopedBuffer&);
    114   void operator=(const InternalScopedBuffer&);
    115 };
    116 
    117 class InternalScopedString : public InternalScopedBuffer<char> {
    118  public:
    119   explicit InternalScopedString(uptr max_length)
    120       : InternalScopedBuffer<char>(max_length), length_(0) {
    121     (*this)[0] = '\0';
    122   }
    123   uptr length() { return length_; }
    124   void clear() {
    125     (*this)[0] = '\0';
    126     length_ = 0;
    127   }
    128   void append(const char *format, ...);
    129 
    130  private:
    131   uptr length_;
    132 };
    133 
    134 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
    135 // constructor, so all instances of LowLevelAllocator should be
    136 // linker initialized.
    137 class LowLevelAllocator {
    138  public:
    139   // Requires an external lock.
    140   void *Allocate(uptr size);
    141  private:
    142   char *allocated_end_;
    143   char *allocated_current_;
    144 };
    145 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
    146 // Allows to register tool-specific callbacks for LowLevelAllocator.
    147 // Passing NULL removes the callback.
    148 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
    149 
    150 // IO
    151 void RawWrite(const char *buffer);
    152 bool ColorizeReports();
    153 void Printf(const char *format, ...);
    154 void Report(const char *format, ...);
    155 void SetPrintfAndReportCallback(void (*callback)(const char *));
    156 #define VReport(level, ...)                                              \
    157   do {                                                                   \
    158     if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
    159   } while (0)
    160 #define VPrintf(level, ...)                                              \
    161   do {                                                                   \
    162     if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
    163   } while (0)
    164 
    165 // Can be used to prevent mixing error reports from different sanitizers.
    166 extern StaticSpinMutex CommonSanitizerReportMutex;
    167 
    168 struct ReportFile {
    169   void Write(const char *buffer, uptr length);
    170   bool SupportsColors();
    171   void SetReportPath(const char *path);
    172 
    173   // Don't use fields directly. They are only declared public to allow
    174   // aggregate initialization.
    175 
    176   // Protects fields below.
    177   StaticSpinMutex *mu;
    178   // Opened file descriptor. Defaults to stderr. It may be equal to
    179   // kInvalidFd, in which case new file will be opened when necessary.
    180   fd_t fd;
    181   // Path prefix of report file, set via __sanitizer_set_report_path.
    182   char path_prefix[kMaxPathLength];
    183   // Full path to report, obtained as <path_prefix>.PID
    184   char full_path[kMaxPathLength];
    185   // PID of the process that opened fd. If a fork() occurs,
    186   // the PID of child will be different from fd_pid.
    187   uptr fd_pid;
    188 
    189  private:
    190   void ReopenIfNecessary();
    191 };
    192 extern ReportFile report_file;
    193 
    194 extern uptr stoptheworld_tracer_pid;
    195 extern uptr stoptheworld_tracer_ppid;
    196 
    197 enum FileAccessMode {
    198   RdOnly,
    199   WrOnly,
    200   RdWr
    201 };
    202 
    203 // Returns kInvalidFd on error.
    204 fd_t OpenFile(const char *filename, FileAccessMode mode,
    205               error_t *errno_p = nullptr);
    206 void CloseFile(fd_t);
    207 
    208 // Return true on success, false on error.
    209 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size,
    210                   uptr *bytes_read = nullptr, error_t *error_p = nullptr);
    211 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size,
    212                  uptr *bytes_written = nullptr, error_t *error_p = nullptr);
    213 
    214 bool RenameFile(const char *oldpath, const char *newpath,
    215                 error_t *error_p = nullptr);
    216 
    217 bool SupportsColoredOutput(fd_t fd);
    218 
    219 // Opens the file 'file_name" and reads up to 'max_len' bytes.
    220 // The resulting buffer is mmaped and stored in '*buff'.
    221 // The size of the mmaped region is stored in '*buff_size',
    222 // Returns the number of read bytes or 0 if file can not be opened.
    223 uptr ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
    224                       uptr max_len, error_t *errno_p = nullptr);
    225 // Maps given file to virtual memory, and returns pointer to it
    226 // (or NULL if mapping fails). Stores the size of mmaped region
    227 // in '*buff_size'.
    228 void *MapFileToMemory(const char *file_name, uptr *buff_size);
    229 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, uptr offset);
    230 
    231 bool IsAccessibleMemoryRange(uptr beg, uptr size);
    232 
    233 // Error report formatting.
    234 const char *StripPathPrefix(const char *filepath,
    235                             const char *strip_file_prefix);
    236 // Strip the directories from the module name.
    237 const char *StripModuleName(const char *module);
    238 
    239 // OS
    240 void DisableCoreDumperIfNecessary();
    241 void DumpProcessMap();
    242 bool FileExists(const char *filename);
    243 const char *GetEnv(const char *name);
    244 bool SetEnv(const char *name, const char *value);
    245 const char *GetPwd();
    246 char *FindPathToBinary(const char *name);
    247 bool IsPathSeparator(const char c);
    248 bool IsAbsolutePath(const char *path);
    249 
    250 // Returns the path to the main executable.
    251 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
    252 u32 GetUid();
    253 void ReExec();
    254 bool StackSizeIsUnlimited();
    255 void SetStackSizeLimitInBytes(uptr limit);
    256 bool AddressSpaceIsUnlimited();
    257 void SetAddressSpaceUnlimited();
    258 void AdjustStackSize(void *attr);
    259 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args);
    260 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args);
    261 void SetSandboxingCallback(void (*f)());
    262 
    263 void CoverageUpdateMapping();
    264 void CovBeforeFork();
    265 void CovAfterFork(int child_pid);
    266 
    267 void InitializeCoverage(bool enabled, const char *coverage_dir);
    268 void ReInitializeCoverage(bool enabled, const char *coverage_dir);
    269 
    270 void InitTlsSize();
    271 uptr GetTlsSize();
    272 
    273 // Other
    274 void SleepForSeconds(int seconds);
    275 void SleepForMillis(int millis);
    276 u64 NanoTime();
    277 int Atexit(void (*function)(void));
    278 void SortArray(uptr *array, uptr size);
    279 bool TemplateMatch(const char *templ, const char *str);
    280 
    281 // Exit
    282 void NORETURN Abort();
    283 void NORETURN Die();
    284 void NORETURN
    285 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
    286 
    287 // Set the name of the current thread to 'name', return true on succees.
    288 // The name may be truncated to a system-dependent limit.
    289 bool SanitizerSetThreadName(const char *name);
    290 // Get the name of the current thread (no more than max_len bytes),
    291 // return true on succees. name should have space for at least max_len+1 bytes.
    292 bool SanitizerGetThreadName(char *name, int max_len);
    293 
    294 // Specific tools may override behavior of "Die" and "CheckFailed" functions
    295 // to do tool-specific job.
    296 typedef void (*DieCallbackType)(void);
    297 void SetDieCallback(DieCallbackType);
    298 void SetUserDieCallback(DieCallbackType);
    299 DieCallbackType GetDieCallback();
    300 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
    301                                        u64, u64);
    302 void SetCheckFailedCallback(CheckFailedCallbackType callback);
    303 
    304 // Callback will be called if soft_rss_limit_mb is given and the limit is
    305 // exceeded (exceeded==true) or if rss went down below the limit
    306 // (exceeded==false).
    307 // The callback should be registered once at the tool init time.
    308 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
    309 
    310 // Functions related to signal handling.
    311 typedef void (*SignalHandlerType)(int, void *, void *);
    312 bool IsDeadlySignal(int signum);
    313 void InstallDeadlySignalHandlers(SignalHandlerType handler);
    314 // Alternative signal stack (POSIX-only).
    315 void SetAlternateSignalStack();
    316 void UnsetAlternateSignalStack();
    317 
    318 // We don't want a summary too long.
    319 const int kMaxSummaryLength = 1024;
    320 // Construct a one-line string:
    321 //   SUMMARY: SanitizerToolName: error_message
    322 // and pass it to __sanitizer_report_error_summary.
    323 void ReportErrorSummary(const char *error_message);
    324 // Same as above, but construct error_message as:
    325 //   error_type file:line[:column][ function]
    326 void ReportErrorSummary(const char *error_type, const AddressInfo &info);
    327 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
    328 void ReportErrorSummary(const char *error_type, StackTrace *trace);
    329 
    330 // Math
    331 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
    332 extern "C" {
    333 unsigned char _BitScanForward(unsigned long *index, unsigned long mask);  // NOLINT
    334 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);  // NOLINT
    335 #if defined(_WIN64)
    336 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask);  // NOLINT
    337 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask);  // NOLINT
    338 #endif
    339 }
    340 #endif
    341 
    342 INLINE uptr MostSignificantSetBitIndex(uptr x) {
    343   CHECK_NE(x, 0U);
    344   unsigned long up;  // NOLINT
    345 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
    346   up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
    347 #elif defined(_WIN64)
    348   _BitScanReverse64(&up, x);
    349 #else
    350   _BitScanReverse(&up, x);
    351 #endif
    352   return up;
    353 }
    354 
    355 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
    356   CHECK_NE(x, 0U);
    357   unsigned long up;  // NOLINT
    358 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
    359   up = __builtin_ctzl(x);
    360 #elif defined(_WIN64)
    361   _BitScanForward64(&up, x);
    362 #else
    363   _BitScanForward(&up, x);
    364 #endif
    365   return up;
    366 }
    367 
    368 INLINE bool IsPowerOfTwo(uptr x) {
    369   return (x & (x - 1)) == 0;
    370 }
    371 
    372 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
    373   CHECK(size);
    374   if (IsPowerOfTwo(size)) return size;
    375 
    376   uptr up = MostSignificantSetBitIndex(size);
    377   CHECK(size < (1ULL << (up + 1)));
    378   CHECK(size > (1ULL << up));
    379   return 1UL << (up + 1);
    380 }
    381 
    382 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
    383   CHECK(IsPowerOfTwo(boundary));
    384   return (size + boundary - 1) & ~(boundary - 1);
    385 }
    386 
    387 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
    388   return x & ~(boundary - 1);
    389 }
    390 
    391 INLINE bool IsAligned(uptr a, uptr alignment) {
    392   return (a & (alignment - 1)) == 0;
    393 }
    394 
    395 INLINE uptr Log2(uptr x) {
    396   CHECK(IsPowerOfTwo(x));
    397 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
    398   return __builtin_ctzl(x);
    399 #elif defined(_WIN64)
    400   unsigned long ret;  // NOLINT
    401   _BitScanForward64(&ret, x);
    402   return ret;
    403 #else
    404   unsigned long ret;  // NOLINT
    405   _BitScanForward(&ret, x);
    406   return ret;
    407 #endif
    408 }
    409 
    410 // Don't use std::min, std::max or std::swap, to minimize dependency
    411 // on libstdc++.
    412 template<class T> T Min(T a, T b) { return a < b ? a : b; }
    413 template<class T> T Max(T a, T b) { return a > b ? a : b; }
    414 template<class T> void Swap(T& a, T& b) {
    415   T tmp = a;
    416   a = b;
    417   b = tmp;
    418 }
    419 
    420 // Char handling
    421 INLINE bool IsSpace(int c) {
    422   return (c == ' ') || (c == '\n') || (c == '\t') ||
    423          (c == '\f') || (c == '\r') || (c == '\v');
    424 }
    425 INLINE bool IsDigit(int c) {
    426   return (c >= '0') && (c <= '9');
    427 }
    428 INLINE int ToLower(int c) {
    429   return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
    430 }
    431 
    432 // A low-level vector based on mmap. May incur a significant memory overhead for
    433 // small vectors.
    434 // WARNING: The current implementation supports only POD types.
    435 template<typename T>
    436 class InternalMmapVectorNoCtor {
    437  public:
    438   void Initialize(uptr initial_capacity) {
    439     capacity_ = Max(initial_capacity, (uptr)1);
    440     size_ = 0;
    441     data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
    442   }
    443   void Destroy() {
    444     UnmapOrDie(data_, capacity_ * sizeof(T));
    445   }
    446   T &operator[](uptr i) {
    447     CHECK_LT(i, size_);
    448     return data_[i];
    449   }
    450   const T &operator[](uptr i) const {
    451     CHECK_LT(i, size_);
    452     return data_[i];
    453   }
    454   void push_back(const T &element) {
    455     CHECK_LE(size_, capacity_);
    456     if (size_ == capacity_) {
    457       uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
    458       Resize(new_capacity);
    459     }
    460     data_[size_++] = element;
    461   }
    462   T &back() {
    463     CHECK_GT(size_, 0);
    464     return data_[size_ - 1];
    465   }
    466   void pop_back() {
    467     CHECK_GT(size_, 0);
    468     size_--;
    469   }
    470   uptr size() const {
    471     return size_;
    472   }
    473   const T *data() const {
    474     return data_;
    475   }
    476   T *data() {
    477     return data_;
    478   }
    479   uptr capacity() const {
    480     return capacity_;
    481   }
    482 
    483   void clear() { size_ = 0; }
    484   bool empty() const { return size() == 0; }
    485 
    486  private:
    487   void Resize(uptr new_capacity) {
    488     CHECK_GT(new_capacity, 0);
    489     CHECK_LE(size_, new_capacity);
    490     T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
    491                                  "InternalMmapVector");
    492     internal_memcpy(new_data, data_, size_ * sizeof(T));
    493     T *old_data = data_;
    494     data_ = new_data;
    495     UnmapOrDie(old_data, capacity_ * sizeof(T));
    496     capacity_ = new_capacity;
    497   }
    498 
    499   T *data_;
    500   uptr capacity_;
    501   uptr size_;
    502 };
    503 
    504 template<typename T>
    505 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
    506  public:
    507   explicit InternalMmapVector(uptr initial_capacity) {
    508     InternalMmapVectorNoCtor<T>::Initialize(initial_capacity);
    509   }
    510   ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
    511   // Disallow evil constructors.
    512   InternalMmapVector(const InternalMmapVector&);
    513   void operator=(const InternalMmapVector&);
    514 };
    515 
    516 // HeapSort for arrays and InternalMmapVector.
    517 template<class Container, class Compare>
    518 void InternalSort(Container *v, uptr size, Compare comp) {
    519   if (size < 2)
    520     return;
    521   // Stage 1: insert elements to the heap.
    522   for (uptr i = 1; i < size; i++) {
    523     uptr j, p;
    524     for (j = i; j > 0; j = p) {
    525       p = (j - 1) / 2;
    526       if (comp((*v)[p], (*v)[j]))
    527         Swap((*v)[j], (*v)[p]);
    528       else
    529         break;
    530     }
    531   }
    532   // Stage 2: swap largest element with the last one,
    533   // and sink the new top.
    534   for (uptr i = size - 1; i > 0; i--) {
    535     Swap((*v)[0], (*v)[i]);
    536     uptr j, max_ind;
    537     for (j = 0; j < i; j = max_ind) {
    538       uptr left = 2 * j + 1;
    539       uptr right = 2 * j + 2;
    540       max_ind = j;
    541       if (left < i && comp((*v)[max_ind], (*v)[left]))
    542         max_ind = left;
    543       if (right < i && comp((*v)[max_ind], (*v)[right]))
    544         max_ind = right;
    545       if (max_ind != j)
    546         Swap((*v)[j], (*v)[max_ind]);
    547       else
    548         break;
    549     }
    550   }
    551 }
    552 
    553 template<class Container, class Value, class Compare>
    554 uptr InternalBinarySearch(const Container &v, uptr first, uptr last,
    555                           const Value &val, Compare comp) {
    556   uptr not_found = last + 1;
    557   while (last >= first) {
    558     uptr mid = (first + last) / 2;
    559     if (comp(v[mid], val))
    560       first = mid + 1;
    561     else if (comp(val, v[mid]))
    562       last = mid - 1;
    563     else
    564       return mid;
    565   }
    566   return not_found;
    567 }
    568 
    569 // Represents a binary loaded into virtual memory (e.g. this can be an
    570 // executable or a shared object).
    571 class LoadedModule {
    572  public:
    573   LoadedModule() : full_name_(nullptr), base_address_(0) { ranges_.clear(); }
    574   void set(const char *module_name, uptr base_address);
    575   void clear();
    576   void addAddressRange(uptr beg, uptr end, bool executable);
    577   bool containsAddress(uptr address) const;
    578 
    579   const char *full_name() const { return full_name_; }
    580   uptr base_address() const { return base_address_; }
    581 
    582   struct AddressRange {
    583     AddressRange *next;
    584     uptr beg;
    585     uptr end;
    586     bool executable;
    587 
    588     AddressRange(uptr beg, uptr end, bool executable)
    589         : next(nullptr), beg(beg), end(end), executable(executable) {}
    590   };
    591 
    592   typedef IntrusiveList<AddressRange>::ConstIterator Iterator;
    593   Iterator ranges() const { return Iterator(&ranges_); }
    594 
    595  private:
    596   char *full_name_;  // Owned.
    597   uptr base_address_;
    598   IntrusiveList<AddressRange> ranges_;
    599 };
    600 
    601 // OS-dependent function that fills array with descriptions of at most
    602 // "max_modules" currently loaded modules. Returns the number of
    603 // initialized modules. If filter is nonzero, ignores modules for which
    604 // filter(full_name) is false.
    605 typedef bool (*string_predicate_t)(const char *);
    606 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
    607                       string_predicate_t filter);
    608 
    609 #if SANITIZER_POSIX
    610 const uptr kPthreadDestructorIterations = 4;
    611 #else
    612 // Unused on Windows.
    613 const uptr kPthreadDestructorIterations = 0;
    614 #endif
    615 
    616 // Callback type for iterating over a set of memory ranges.
    617 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
    618 
    619 #if SANITIZER_ANDROID
    620 // Initialize Android logging. Any writes before this are silently lost.
    621 void AndroidLogInit();
    622 void AndroidLogWrite(const char *buffer);
    623 void GetExtraActivationFlags(char *buf, uptr size);
    624 void SanitizerInitializeUnwinder();
    625 #else
    626 INLINE void AndroidLogInit() {}
    627 INLINE void AndroidLogWrite(const char *buffer_unused) {}
    628 INLINE void GetExtraActivationFlags(char *buf, uptr size) { *buf = '\0'; }
    629 INLINE void SanitizerInitializeUnwinder() {}
    630 #endif
    631 
    632 void *internal_start_thread(void(*func)(void*), void *arg);
    633 void internal_join_thread(void *th);
    634 void MaybeStartBackgroudThread();
    635 
    636 // Make the compiler think that something is going on there.
    637 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
    638 // compiler from recognising it and turning it into an actual call to
    639 // memset/memcpy/etc.
    640 static inline void SanitizerBreakOptimization(void *arg) {
    641 #if _MSC_VER
    642   // FIXME: make sure this is actually enough.
    643   __asm;
    644 #else
    645   __asm__ __volatile__("" : : "r" (arg) : "memory");
    646 #endif
    647 }
    648 
    649 struct SignalContext {
    650   void *context;
    651   uptr addr;
    652   uptr pc;
    653   uptr sp;
    654   uptr bp;
    655 
    656   SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp) :
    657       context(context), addr(addr), pc(pc), sp(sp), bp(bp) {
    658   }
    659 
    660   // Creates signal context in a platform-specific manner.
    661   static SignalContext Create(void *siginfo, void *context);
    662 };
    663 
    664 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
    665 
    666 }  // namespace __sanitizer
    667 
    668 inline void *operator new(__sanitizer::operator_new_size_type size,
    669                           __sanitizer::LowLevelAllocator &alloc) {
    670   return alloc.Allocate(size);
    671 }
    672 
    673 struct StackDepotStats {
    674   uptr n_uniq_ids;
    675   uptr allocated;
    676 };
    677 
    678 #endif  // SANITIZER_COMMON_H
    679