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