Home | History | Annotate | Line # | Download | only in sanitizer_common
      1 //===-- sanitizer_common.h --------------------------------------*- C++ -*-===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 // This file is shared between run-time libraries of sanitizers.
     10 //
     11 // It declares common functions and classes that are used in both runtimes.
     12 // Implementation of some functions are provided in sanitizer_common, while
     13 // others must be defined by run-time library itself.
     14 //===----------------------------------------------------------------------===//
     15 #ifndef SANITIZER_COMMON_H
     16 #define SANITIZER_COMMON_H
     17 
     18 #include "sanitizer_flags.h"
     19 #include "sanitizer_internal_defs.h"
     20 #include "sanitizer_libc.h"
     21 #include "sanitizer_list.h"
     22 #include "sanitizer_mutex.h"
     23 
     24 #if defined(_MSC_VER) && !defined(__clang__)
     25 extern "C" void _ReadWriteBarrier();
     26 #pragma intrinsic(_ReadWriteBarrier)
     27 #endif
     28 
     29 namespace __sanitizer {
     30 
     31 struct AddressInfo;
     32 struct BufferedStackTrace;
     33 struct SignalContext;
     34 struct StackTrace;
     35 
     36 // Constants.
     37 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
     38 const uptr kWordSizeInBits = 8 * kWordSize;
     39 
     40 const uptr kCacheLineSize = SANITIZER_CACHE_LINE_SIZE;
     41 
     42 const uptr kMaxPathLength = 4096;
     43 
     44 const uptr kMaxThreadStackSize = 1 << 30;  // 1Gb
     45 
     46 const uptr kErrorMessageBufferSize = 1 << 16;
     47 
     48 // Denotes fake PC values that come from JIT/JAVA/etc.
     49 // For such PC values __tsan_symbolize_external_ex() will be called.
     50 const u64 kExternalPCBit = 1ULL << 60;
     51 
     52 extern const char *SanitizerToolName;  // Can be changed by the tool.
     53 
     54 extern atomic_uint32_t current_verbosity;
     55 inline void SetVerbosity(int verbosity) {
     56   atomic_store(&current_verbosity, verbosity, memory_order_relaxed);
     57 }
     58 inline int Verbosity() {
     59   return atomic_load(&current_verbosity, memory_order_relaxed);
     60 }
     61 
     62 #if SANITIZER_ANDROID
     63 inline uptr GetPageSize() {
     64 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
     65   return 4096;
     66 }
     67 inline uptr GetPageSizeCached() {
     68   return 4096;
     69 }
     70 #else
     71 uptr GetPageSize();
     72 extern uptr PageSizeCached;
     73 inline uptr GetPageSizeCached() {
     74   if (!PageSizeCached)
     75     PageSizeCached = GetPageSize();
     76   return PageSizeCached;
     77 }
     78 #endif
     79 uptr GetMmapGranularity();
     80 uptr GetMaxVirtualAddress();
     81 uptr GetMaxUserVirtualAddress();
     82 // Threads
     83 tid_t GetTid();
     84 int TgKill(pid_t pid, tid_t tid, int sig);
     85 uptr GetThreadSelf();
     86 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
     87                                 uptr *stack_bottom);
     88 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
     89                           uptr *tls_addr, uptr *tls_size);
     90 
     91 // Memory management
     92 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report = false);
     93 inline void *MmapOrDieQuietly(uptr size, const char *mem_type) {
     94   return MmapOrDie(size, mem_type, /*raw_report*/ true);
     95 }
     96 void UnmapOrDie(void *addr, uptr size);
     97 // Behaves just like MmapOrDie, but tolerates out of memory condition, in that
     98 // case returns nullptr.
     99 void *MmapOrDieOnFatalError(uptr size, const char *mem_type);
    100 bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name = nullptr)
    101      WARN_UNUSED_RESULT;
    102 bool MmapFixedSuperNoReserve(uptr fixed_addr, uptr size,
    103                              const char *name = nullptr) WARN_UNUSED_RESULT;
    104 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
    105 void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name = nullptr);
    106 // Behaves just like MmapFixedOrDie, but tolerates out of memory condition, in
    107 // that case returns nullptr.
    108 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size,
    109                                  const char *name = nullptr);
    110 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name = nullptr);
    111 void *MmapNoAccess(uptr size);
    112 // Map aligned chunk of address space; size and alignment are powers of two.
    113 // Dies on all but out of memory errors, in the latter case returns nullptr.
    114 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
    115                                    const char *mem_type);
    116 // Disallow access to a memory range.  Use MmapFixedNoAccess to allocate an
    117 // unaccessible memory.
    118 bool MprotectNoAccess(uptr addr, uptr size);
    119 bool MprotectReadOnly(uptr addr, uptr size);
    120 bool MprotectReadWrite(uptr addr, uptr size);
    121 
    122 void MprotectMallocZones(void *addr, int prot);
    123 
    124 #if SANITIZER_WINDOWS
    125 // Zero previously mmap'd memory. Currently used only on Windows.
    126 bool ZeroMmapFixedRegion(uptr fixed_addr, uptr size) WARN_UNUSED_RESULT;
    127 #endif
    128 
    129 #if SANITIZER_LINUX
    130 // Unmap memory. Currently only used on Linux.
    131 void UnmapFromTo(uptr from, uptr to);
    132 #endif
    133 
    134 // Maps shadow_size_bytes of shadow memory and returns shadow address. It will
    135 // be aligned to the mmap granularity * 2^shadow_scale, or to
    136 // 2^min_shadow_base_alignment if that is larger. The returned address will
    137 // have max(2^min_shadow_base_alignment, mmap granularity) on the left, and
    138 // shadow_size_bytes bytes on the right, which on linux is mapped no access.
    139 // The high_mem_end may be updated if the original shadow size doesn't fit.
    140 uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
    141                       uptr min_shadow_base_alignment, uptr &high_mem_end);
    142 
    143 // Let S = max(shadow_size, num_aliases * alias_size, ring_buffer_size).
    144 // Reserves 2*S bytes of address space to the right of the returned address and
    145 // ring_buffer_size bytes to the left.  The returned address is aligned to 2*S.
    146 // Also creates num_aliases regions of accessible memory starting at offset S
    147 // from the returned address.  Each region has size alias_size and is backed by
    148 // the same physical memory.
    149 uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
    150                                 uptr num_aliases, uptr ring_buffer_size);
    151 
    152 // Reserve memory range [beg, end]. If madvise_shadow is true then apply
    153 // madvise (e.g. hugepages, core dumping) requested by options.
    154 void ReserveShadowMemoryRange(uptr beg, uptr end, const char *name,
    155                               bool madvise_shadow = true);
    156 
    157 // Protect size bytes of memory starting at addr. Also try to protect
    158 // several pages at the start of the address space as specified by
    159 // zero_base_shadow_start, at most up to the size or zero_base_max_shadow_start.
    160 void ProtectGap(uptr addr, uptr size, uptr zero_base_shadow_start,
    161                 uptr zero_base_max_shadow_start);
    162 
    163 // Find an available address space.
    164 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
    165                               uptr *largest_gap_found, uptr *max_occupied_addr);
    166 
    167 // Used to check if we can map shadow memory to a fixed location.
    168 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
    169 // Releases memory pages entirely within the [beg, end] address range. Noop if
    170 // the provided range does not contain at least one entire page.
    171 void ReleaseMemoryPagesToOS(uptr beg, uptr end);
    172 void IncreaseTotalMmap(uptr size);
    173 void DecreaseTotalMmap(uptr size);
    174 uptr GetRSS();
    175 void SetShadowRegionHugePageMode(uptr addr, uptr length);
    176 bool DontDumpShadowMemory(uptr addr, uptr length);
    177 // Check if the built VMA size matches the runtime one.
    178 void CheckVMASize();
    179 void RunMallocHooks(void *ptr, uptr size);
    180 void RunFreeHooks(void *ptr);
    181 
    182 class ReservedAddressRange {
    183  public:
    184   uptr Init(uptr size, const char *name = nullptr, uptr fixed_addr = 0);
    185   uptr InitAligned(uptr size, uptr align, const char *name = nullptr);
    186   uptr Map(uptr fixed_addr, uptr size, const char *name = nullptr);
    187   uptr MapOrDie(uptr fixed_addr, uptr size, const char *name = nullptr);
    188   void Unmap(uptr addr, uptr size);
    189   void *base() const { return base_; }
    190   uptr size() const { return size_; }
    191 
    192  private:
    193   void* base_;
    194   uptr size_;
    195   const char* name_;
    196   uptr os_handle_;
    197 };
    198 
    199 typedef void (*fill_profile_f)(uptr start, uptr rss, bool file,
    200                                /*out*/ uptr *stats);
    201 
    202 // Parse the contents of /proc/self/smaps and generate a memory profile.
    203 // |cb| is a tool-specific callback that fills the |stats| array.
    204 void GetMemoryProfile(fill_profile_f cb, uptr *stats);
    205 void ParseUnixMemoryProfile(fill_profile_f cb, uptr *stats, char *smaps,
    206                             uptr smaps_len);
    207 
    208 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
    209 // constructor, so all instances of LowLevelAllocator should be
    210 // linker initialized.
    211 //
    212 // NOTE: Users should instead use the singleton provided via
    213 // `GetGlobalLowLevelAllocator()` rather than create a new one. This way, the
    214 // number of mmap fragments can be reduced and use the same contiguous mmap
    215 // provided by this singleton.
    216 class LowLevelAllocator {
    217  public:
    218   // Requires an external lock.
    219   void *Allocate(uptr size);
    220 
    221  private:
    222   char *allocated_end_;
    223   char *allocated_current_;
    224 };
    225 // Set the min alignment of LowLevelAllocator to at least alignment.
    226 void SetLowLevelAllocateMinAlignment(uptr alignment);
    227 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
    228 // Allows to register tool-specific callbacks for LowLevelAllocator.
    229 // Passing NULL removes the callback.
    230 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
    231 
    232 LowLevelAllocator &GetGlobalLowLevelAllocator();
    233 
    234 // IO
    235 void CatastrophicErrorWrite(const char *buffer, uptr length);
    236 void RawWrite(const char *buffer);
    237 bool ColorizeReports();
    238 void RemoveANSIEscapeSequencesFromString(char *buffer);
    239 void Printf(const char *format, ...) FORMAT(1, 2);
    240 void Report(const char *format, ...) FORMAT(1, 2);
    241 void SetPrintfAndReportCallback(void (*callback)(const char *));
    242 #define VReport(level, ...)                                              \
    243   do {                                                                   \
    244     if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
    245   } while (0)
    246 #define VPrintf(level, ...)                                              \
    247   do {                                                                   \
    248     if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
    249   } while (0)
    250 
    251 // Lock sanitizer error reporting and protects against nested errors.
    252 class ScopedErrorReportLock {
    253  public:
    254   ScopedErrorReportLock() SANITIZER_ACQUIRE(mutex_) { Lock(); }
    255   ~ScopedErrorReportLock() SANITIZER_RELEASE(mutex_) { Unlock(); }
    256 
    257   static void Lock() SANITIZER_ACQUIRE(mutex_);
    258   static void Unlock() SANITIZER_RELEASE(mutex_);
    259   static void CheckLocked() SANITIZER_CHECK_LOCKED(mutex_);
    260 
    261  private:
    262   static atomic_uintptr_t reporting_thread_;
    263   static StaticSpinMutex mutex_;
    264 };
    265 
    266 extern uptr stoptheworld_tracer_pid;
    267 extern uptr stoptheworld_tracer_ppid;
    268 
    269 bool IsAccessibleMemoryRange(uptr beg, uptr size);
    270 
    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);
    276 
    277 // OS
    278 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
    279 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
    280 uptr ReadBinaryDir(/*out*/ char *buf, uptr buf_len);
    281 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len);
    282 const char *GetProcessName();
    283 void UpdateProcessName();
    284 void CacheBinaryName();
    285 void DisableCoreDumperIfNecessary();
    286 void DumpProcessMap();
    287 const char *GetEnv(const char *name);
    288 bool SetEnv(const char *name, const char *value);
    289 
    290 u32 GetUid();
    291 void ReExec();
    292 void CheckASLR();
    293 void CheckMPROTECT();
    294 char **GetArgv();
    295 char **GetEnviron();
    296 void PrintCmdline();
    297 bool StackSizeIsUnlimited();
    298 void SetStackSizeLimitInBytes(uptr limit);
    299 bool AddressSpaceIsUnlimited();
    300 void SetAddressSpaceUnlimited();
    301 void AdjustStackSize(void *attr);
    302 void PlatformPrepareForSandboxing(void *args);
    303 void SetSandboxingCallback(void (*f)());
    304 
    305 void InitializeCoverage(bool enabled, const char *coverage_dir);
    306 
    307 void InitTlsSize();
    308 uptr GetTlsSize();
    309 
    310 // Other
    311 void WaitForDebugger(unsigned seconds, const char *label);
    312 void SleepForSeconds(unsigned seconds);
    313 void SleepForMillis(unsigned millis);
    314 u64 NanoTime();
    315 u64 MonotonicNanoTime();
    316 int Atexit(void (*function)(void));
    317 bool TemplateMatch(const char *templ, const char *str);
    318 
    319 // Exit
    320 void NORETURN Abort();
    321 void NORETURN Die();
    322 void NORETURN
    323 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
    324 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
    325                                       const char *mmap_type, error_t err,
    326                                       bool raw_report = false);
    327 void NORETURN ReportMunmapFailureAndDie(void *ptr, uptr size, error_t err,
    328                                         bool raw_report = false);
    329 
    330 // Returns true if the platform-specific error reported is an OOM error.
    331 bool ErrorIsOOM(error_t err);
    332 
    333 // This reports an error in the form:
    334 //
    335 //   `ERROR: {{SanitizerToolName}}: out of memory: {{err_msg}}`
    336 //
    337 // Downstream tools that read sanitizer output will know that errors starting
    338 // in this format are specifically OOM errors.
    339 #define ERROR_OOM(err_msg, ...) \
    340   Report("ERROR: %s: out of memory: " err_msg, SanitizerToolName, __VA_ARGS__)
    341 
    342 // Specific tools may override behavior of "Die" function to do tool-specific
    343 // job.
    344 typedef void (*DieCallbackType)(void);
    345 
    346 // It's possible to add several callbacks that would be run when "Die" is
    347 // called. The callbacks will be run in the opposite order. The tools are
    348 // strongly recommended to setup all callbacks during initialization, when there
    349 // is only a single thread.
    350 bool AddDieCallback(DieCallbackType callback);
    351 bool RemoveDieCallback(DieCallbackType callback);
    352 
    353 void SetUserDieCallback(DieCallbackType callback);
    354 
    355 void SetCheckUnwindCallback(void (*callback)());
    356 
    357 // Functions related to signal handling.
    358 typedef void (*SignalHandlerType)(int, void *, void *);
    359 HandleSignalMode GetHandleSignalMode(int signum);
    360 void InstallDeadlySignalHandlers(SignalHandlerType handler);
    361 
    362 // Signal reporting.
    363 // Each sanitizer uses slightly different implementation of stack unwinding.
    364 typedef void (*UnwindSignalStackCallbackType)(const SignalContext &sig,
    365                                               const void *callback_context,
    366                                               BufferedStackTrace *stack);
    367 // Print deadly signal report and die.
    368 void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
    369                         UnwindSignalStackCallbackType unwind,
    370                         const void *unwind_context);
    371 
    372 // Part of HandleDeadlySignal, exposed for asan.
    373 void StartReportDeadlySignal();
    374 // Part of HandleDeadlySignal, exposed for asan.
    375 void ReportDeadlySignal(const SignalContext &sig, u32 tid,
    376                         UnwindSignalStackCallbackType unwind,
    377                         const void *unwind_context);
    378 
    379 // Alternative signal stack (POSIX-only).
    380 void SetAlternateSignalStack();
    381 void UnsetAlternateSignalStack();
    382 
    383 // Construct a one-line string:
    384 //   SUMMARY: SanitizerToolName: error_message
    385 // and pass it to __sanitizer_report_error_summary.
    386 // If alt_tool_name is provided, it's used in place of SanitizerToolName.
    387 void ReportErrorSummary(const char *error_message,
    388                         const char *alt_tool_name = nullptr);
    389 // Same as above, but construct error_message as:
    390 //   error_type file:line[:column][ function]
    391 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
    392                         const char *alt_tool_name = nullptr);
    393 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
    394 void ReportErrorSummary(const char *error_type, const StackTrace *trace,
    395                         const char *alt_tool_name = nullptr);
    396 
    397 void ReportMmapWriteExec(int prot, int mflags);
    398 
    399 // Math
    400 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
    401 extern "C" {
    402 unsigned char _BitScanForward(unsigned long *index, unsigned long mask);
    403 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);
    404 #if defined(_WIN64)
    405 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask);
    406 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask);
    407 #endif
    408 }
    409 #endif
    410 
    411 inline uptr MostSignificantSetBitIndex(uptr x) {
    412   CHECK_NE(x, 0U);
    413   unsigned long up;
    414 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
    415 # ifdef _WIN64
    416   up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
    417 # else
    418   up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
    419 # endif
    420 #elif defined(_WIN64)
    421   _BitScanReverse64(&up, x);
    422 #else
    423   _BitScanReverse(&up, x);
    424 #endif
    425   return up;
    426 }
    427 
    428 inline uptr LeastSignificantSetBitIndex(uptr x) {
    429   CHECK_NE(x, 0U);
    430   unsigned long up;
    431 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
    432 # ifdef _WIN64
    433   up = __builtin_ctzll(x);
    434 # else
    435   up = __builtin_ctzl(x);
    436 # endif
    437 #elif defined(_WIN64)
    438   _BitScanForward64(&up, x);
    439 #else
    440   _BitScanForward(&up, x);
    441 #endif
    442   return up;
    443 }
    444 
    445 inline constexpr bool IsPowerOfTwo(uptr x) { return (x & (x - 1)) == 0; }
    446 
    447 inline uptr RoundUpToPowerOfTwo(uptr size) {
    448   CHECK(size);
    449   if (IsPowerOfTwo(size)) return size;
    450 
    451   uptr up = MostSignificantSetBitIndex(size);
    452   CHECK_LT(size, (1ULL << (up + 1)));
    453   CHECK_GT(size, (1ULL << up));
    454   return 1ULL << (up + 1);
    455 }
    456 
    457 inline constexpr uptr RoundUpTo(uptr size, uptr boundary) {
    458   RAW_CHECK(IsPowerOfTwo(boundary));
    459   return (size + boundary - 1) & ~(boundary - 1);
    460 }
    461 
    462 inline constexpr uptr RoundDownTo(uptr x, uptr boundary) {
    463   return x & ~(boundary - 1);
    464 }
    465 
    466 inline constexpr bool IsAligned(uptr a, uptr alignment) {
    467   return (a & (alignment - 1)) == 0;
    468 }
    469 
    470 inline uptr Log2(uptr x) {
    471   CHECK(IsPowerOfTwo(x));
    472   return LeastSignificantSetBitIndex(x);
    473 }
    474 
    475 // Don't use std::min, std::max or std::swap, to minimize dependency
    476 // on libstdc++.
    477 template <class T>
    478 constexpr T Min(T a, T b) {
    479   return a < b ? a : b;
    480 }
    481 template <class T>
    482 constexpr T Max(T a, T b) {
    483   return a > b ? a : b;
    484 }
    485 template <class T>
    486 constexpr T Abs(T a) {
    487   return a < 0 ? -a : a;
    488 }
    489 template<class T> void Swap(T& a, T& b) {
    490   T tmp = a;
    491   a = b;
    492   b = tmp;
    493 }
    494 
    495 // Char handling
    496 inline bool IsSpace(int c) {
    497   return (c == ' ') || (c == '\n') || (c == '\t') ||
    498          (c == '\f') || (c == '\r') || (c == '\v');
    499 }
    500 inline bool IsDigit(int c) {
    501   return (c >= '0') && (c <= '9');
    502 }
    503 inline int ToLower(int c) {
    504   return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
    505 }
    506 
    507 // A low-level vector based on mmap. May incur a significant memory overhead for
    508 // small vectors.
    509 // WARNING: The current implementation supports only POD types.
    510 template<typename T>
    511 class InternalMmapVectorNoCtor {
    512  public:
    513   using value_type = T;
    514   void Initialize(uptr initial_capacity) {
    515     capacity_bytes_ = 0;
    516     size_ = 0;
    517     data_ = 0;
    518     reserve(initial_capacity);
    519   }
    520   void Destroy() { UnmapOrDie(data_, capacity_bytes_); }
    521   T &operator[](uptr i) {
    522     CHECK_LT(i, size_);
    523     return data_[i];
    524   }
    525   const T &operator[](uptr i) const {
    526     CHECK_LT(i, size_);
    527     return data_[i];
    528   }
    529   void push_back(const T &element) {
    530     if (UNLIKELY(size_ >= capacity())) {
    531       CHECK_EQ(size_, capacity());
    532       uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
    533       Realloc(new_capacity);
    534     }
    535     internal_memcpy(&data_[size_++], &element, sizeof(T));
    536   }
    537   T &back() {
    538     CHECK_GT(size_, 0);
    539     return data_[size_ - 1];
    540   }
    541   void pop_back() {
    542     CHECK_GT(size_, 0);
    543     size_--;
    544   }
    545   uptr size() const {
    546     return size_;
    547   }
    548   const T *data() const {
    549     return data_;
    550   }
    551   T *data() {
    552     return data_;
    553   }
    554   uptr capacity() const { return capacity_bytes_ / sizeof(T); }
    555   void reserve(uptr new_size) {
    556     // Never downsize internal buffer.
    557     if (new_size > capacity())
    558       Realloc(new_size);
    559   }
    560   void resize(uptr new_size) {
    561     if (new_size > size_) {
    562       reserve(new_size);
    563       internal_memset(&data_[size_], 0, sizeof(T) * (new_size - size_));
    564     }
    565     size_ = new_size;
    566   }
    567 
    568   void clear() { size_ = 0; }
    569   bool empty() const { return size() == 0; }
    570 
    571   const T *begin() const {
    572     return data();
    573   }
    574   T *begin() {
    575     return data();
    576   }
    577   const T *end() const {
    578     return data() + size();
    579   }
    580   T *end() {
    581     return data() + size();
    582   }
    583 
    584   void swap(InternalMmapVectorNoCtor &other) {
    585     Swap(data_, other.data_);
    586     Swap(capacity_bytes_, other.capacity_bytes_);
    587     Swap(size_, other.size_);
    588   }
    589 
    590  private:
    591   NOINLINE void Realloc(uptr new_capacity) {
    592     CHECK_GT(new_capacity, 0);
    593     CHECK_LE(size_, new_capacity);
    594     uptr new_capacity_bytes =
    595         RoundUpTo(new_capacity * sizeof(T), GetPageSizeCached());
    596     T *new_data = (T *)MmapOrDie(new_capacity_bytes, "InternalMmapVector");
    597     internal_memcpy(new_data, data_, size_ * sizeof(T));
    598     UnmapOrDie(data_, capacity_bytes_);
    599     data_ = new_data;
    600     capacity_bytes_ = new_capacity_bytes;
    601   }
    602 
    603   T *data_;
    604   uptr capacity_bytes_;
    605   uptr size_;
    606 };
    607 
    608 template <typename T>
    609 bool operator==(const InternalMmapVectorNoCtor<T> &lhs,
    610                 const InternalMmapVectorNoCtor<T> &rhs) {
    611   if (lhs.size() != rhs.size()) return false;
    612   return internal_memcmp(lhs.data(), rhs.data(), lhs.size() * sizeof(T)) == 0;
    613 }
    614 
    615 template <typename T>
    616 bool operator!=(const InternalMmapVectorNoCtor<T> &lhs,
    617                 const InternalMmapVectorNoCtor<T> &rhs) {
    618   return !(lhs == rhs);
    619 }
    620 
    621 template<typename T>
    622 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
    623  public:
    624   InternalMmapVector() { InternalMmapVectorNoCtor<T>::Initialize(0); }
    625   explicit InternalMmapVector(uptr cnt) {
    626     InternalMmapVectorNoCtor<T>::Initialize(cnt);
    627     this->resize(cnt);
    628   }
    629   ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
    630   // Disallow copies and moves.
    631   InternalMmapVector(const InternalMmapVector &) = delete;
    632   InternalMmapVector &operator=(const InternalMmapVector &) = delete;
    633   InternalMmapVector(InternalMmapVector &&) = delete;
    634   InternalMmapVector &operator=(InternalMmapVector &&) = delete;
    635 };
    636 
    637 class InternalScopedString {
    638  public:
    639   InternalScopedString() : buffer_(1) { buffer_[0] = '\0'; }
    640 
    641   uptr length() const { return buffer_.size() - 1; }
    642   void clear() {
    643     buffer_.resize(1);
    644     buffer_[0] = '\0';
    645   }
    646   void Append(const char *str);
    647   void AppendF(const char *format, ...) FORMAT(2, 3);
    648   const char *data() const { return buffer_.data(); }
    649   char *data() { return buffer_.data(); }
    650 
    651  private:
    652   InternalMmapVector<char> buffer_;
    653 };
    654 
    655 template <class T>
    656 struct CompareLess {
    657   bool operator()(const T &a, const T &b) const { return a < b; }
    658 };
    659 
    660 // HeapSort for arrays and InternalMmapVector.
    661 template <class T, class Compare = CompareLess<T>>
    662 void Sort(T *v, uptr size, Compare comp = {}) {
    663   if (size < 2)
    664     return;
    665   // Stage 1: insert elements to the heap.
    666   for (uptr i = 1; i < size; i++) {
    667     uptr j, p;
    668     for (j = i; j > 0; j = p) {
    669       p = (j - 1) / 2;
    670       if (comp(v[p], v[j]))
    671         Swap(v[j], v[p]);
    672       else
    673         break;
    674     }
    675   }
    676   // Stage 2: swap largest element with the last one,
    677   // and sink the new top.
    678   for (uptr i = size - 1; i > 0; i--) {
    679     Swap(v[0], v[i]);
    680     uptr j, max_ind;
    681     for (j = 0; j < i; j = max_ind) {
    682       uptr left = 2 * j + 1;
    683       uptr right = 2 * j + 2;
    684       max_ind = j;
    685       if (left < i && comp(v[max_ind], v[left]))
    686         max_ind = left;
    687       if (right < i && comp(v[max_ind], v[right]))
    688         max_ind = right;
    689       if (max_ind != j)
    690         Swap(v[j], v[max_ind]);
    691       else
    692         break;
    693     }
    694   }
    695 }
    696 
    697 // Works like std::lower_bound: finds the first element that is not less
    698 // than the val.
    699 template <class Container, class T,
    700           class Compare = CompareLess<typename Container::value_type>>
    701 uptr InternalLowerBound(const Container &v, const T &val, Compare comp = {}) {
    702   uptr first = 0;
    703   uptr last = v.size();
    704   while (last > first) {
    705     uptr mid = (first + last) / 2;
    706     if (comp(v[mid], val))
    707       first = mid + 1;
    708     else
    709       last = mid;
    710   }
    711   return first;
    712 }
    713 
    714 enum ModuleArch {
    715   kModuleArchUnknown,
    716   kModuleArchI386,
    717   kModuleArchX86_64,
    718   kModuleArchX86_64H,
    719   kModuleArchARMV6,
    720   kModuleArchARMV7,
    721   kModuleArchARMV7S,
    722   kModuleArchARMV7K,
    723   kModuleArchARM64,
    724   kModuleArchLoongArch64,
    725   kModuleArchRISCV64,
    726   kModuleArchHexagon
    727 };
    728 
    729 // Sorts and removes duplicates from the container.
    730 template <class Container,
    731           class Compare = CompareLess<typename Container::value_type>>
    732 void SortAndDedup(Container &v, Compare comp = {}) {
    733   Sort(v.data(), v.size(), comp);
    734   uptr size = v.size();
    735   if (size < 2)
    736     return;
    737   uptr last = 0;
    738   for (uptr i = 1; i < size; ++i) {
    739     if (comp(v[last], v[i])) {
    740       ++last;
    741       if (last != i)
    742         v[last] = v[i];
    743     } else {
    744       CHECK(!comp(v[i], v[last]));
    745     }
    746   }
    747   v.resize(last + 1);
    748 }
    749 
    750 constexpr uptr kDefaultFileMaxSize = FIRST_32_SECOND_64(1 << 26, 1 << 28);
    751 
    752 // Opens the file 'file_name" and reads up to 'max_len' bytes.
    753 // The resulting buffer is mmaped and stored in '*buff'.
    754 // Returns true if file was successfully opened and read.
    755 bool ReadFileToVector(const char *file_name,
    756                       InternalMmapVectorNoCtor<char> *buff,
    757                       uptr max_len = kDefaultFileMaxSize,
    758                       error_t *errno_p = nullptr);
    759 
    760 // Opens the file 'file_name" and reads up to 'max_len' bytes.
    761 // This function is less I/O efficient than ReadFileToVector as it may reread
    762 // file multiple times to avoid mmap during read attempts. It's used to read
    763 // procmap, so short reads with mmap in between can produce inconsistent result.
    764 // The resulting buffer is mmaped and stored in '*buff'.
    765 // The size of the mmaped region is stored in '*buff_size'.
    766 // The total number of read bytes is stored in '*read_len'.
    767 // Returns true if file was successfully opened and read.
    768 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
    769                       uptr *read_len, uptr max_len = kDefaultFileMaxSize,
    770                       error_t *errno_p = nullptr);
    771 
    772 int GetModuleAndOffsetForPc(uptr pc, char *module_name, uptr module_name_len,
    773                             uptr *pc_offset);
    774 
    775 // When adding a new architecture, don't forget to also update
    776 // script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cpp.
    777 inline const char *ModuleArchToString(ModuleArch arch) {
    778   switch (arch) {
    779     case kModuleArchUnknown:
    780       return "";
    781     case kModuleArchI386:
    782       return "i386";
    783     case kModuleArchX86_64:
    784       return "x86_64";
    785     case kModuleArchX86_64H:
    786       return "x86_64h";
    787     case kModuleArchARMV6:
    788       return "armv6";
    789     case kModuleArchARMV7:
    790       return "armv7";
    791     case kModuleArchARMV7S:
    792       return "armv7s";
    793     case kModuleArchARMV7K:
    794       return "armv7k";
    795     case kModuleArchARM64:
    796       return "arm64";
    797     case kModuleArchLoongArch64:
    798       return "loongarch64";
    799     case kModuleArchRISCV64:
    800       return "riscv64";
    801     case kModuleArchHexagon:
    802       return "hexagon";
    803   }
    804   CHECK(0 && "Invalid module arch");
    805   return "";
    806 }
    807 
    808 #if SANITIZER_APPLE
    809 const uptr kModuleUUIDSize = 16;
    810 #else
    811 const uptr kModuleUUIDSize = 32;
    812 #endif
    813 const uptr kMaxSegName = 16;
    814 
    815 // Represents a binary loaded into virtual memory (e.g. this can be an
    816 // executable or a shared object).
    817 class LoadedModule {
    818  public:
    819   LoadedModule()
    820       : full_name_(nullptr),
    821         base_address_(0),
    822         max_address_(0),
    823         arch_(kModuleArchUnknown),
    824         uuid_size_(0),
    825         instrumented_(false) {
    826     internal_memset(uuid_, 0, kModuleUUIDSize);
    827     ranges_.clear();
    828   }
    829   void set(const char *module_name, uptr base_address);
    830   void set(const char *module_name, uptr base_address, ModuleArch arch,
    831            u8 uuid[kModuleUUIDSize], bool instrumented);
    832   void setUuid(const char *uuid, uptr size);
    833   void clear();
    834   void addAddressRange(uptr beg, uptr end, bool executable, bool writable,
    835                        const char *name = nullptr);
    836   bool containsAddress(uptr address) const;
    837 
    838   const char *full_name() const { return full_name_; }
    839   uptr base_address() const { return base_address_; }
    840   uptr max_address() const { return max_address_; }
    841   ModuleArch arch() const { return arch_; }
    842   const u8 *uuid() const { return uuid_; }
    843   uptr uuid_size() const { return uuid_size_; }
    844   bool instrumented() const { return instrumented_; }
    845 
    846   struct AddressRange {
    847     AddressRange *next;
    848     uptr beg;
    849     uptr end;
    850     bool executable;
    851     bool writable;
    852     char name[kMaxSegName];
    853 
    854     AddressRange(uptr beg, uptr end, bool executable, bool writable,
    855                  const char *name)
    856         : next(nullptr),
    857           beg(beg),
    858           end(end),
    859           executable(executable),
    860           writable(writable) {
    861       internal_strncpy(this->name, (name ? name : ""), ARRAY_SIZE(this->name));
    862     }
    863   };
    864 
    865   const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
    866 
    867  private:
    868   char *full_name_;  // Owned.
    869   uptr base_address_;
    870   uptr max_address_;
    871   ModuleArch arch_;
    872   uptr uuid_size_;
    873   u8 uuid_[kModuleUUIDSize];
    874   bool instrumented_;
    875   IntrusiveList<AddressRange> ranges_;
    876 };
    877 
    878 // List of LoadedModules. OS-dependent implementation is responsible for
    879 // filling this information.
    880 class ListOfModules {
    881  public:
    882   ListOfModules() : initialized(false) {}
    883   ~ListOfModules() { clear(); }
    884   void init();
    885   void fallbackInit();  // Uses fallback init if available, otherwise clears
    886   const LoadedModule *begin() const { return modules_.begin(); }
    887   LoadedModule *begin() { return modules_.begin(); }
    888   const LoadedModule *end() const { return modules_.end(); }
    889   LoadedModule *end() { return modules_.end(); }
    890   uptr size() const { return modules_.size(); }
    891   const LoadedModule &operator[](uptr i) const {
    892     CHECK_LT(i, modules_.size());
    893     return modules_[i];
    894   }
    895 
    896  private:
    897   void clear() {
    898     for (auto &module : modules_) module.clear();
    899     modules_.clear();
    900   }
    901   void clearOrInit() {
    902     initialized ? clear() : modules_.Initialize(kInitialCapacity);
    903     initialized = true;
    904   }
    905 
    906   InternalMmapVectorNoCtor<LoadedModule> modules_;
    907   // We rarely have more than 16K loaded modules.
    908   static const uptr kInitialCapacity = 1 << 14;
    909   bool initialized;
    910 };
    911 
    912 // Callback type for iterating over a set of memory ranges.
    913 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
    914 
    915 enum AndroidApiLevel {
    916   ANDROID_NOT_ANDROID = 0,
    917   ANDROID_KITKAT = 19,
    918   ANDROID_LOLLIPOP_MR1 = 22,
    919   ANDROID_POST_LOLLIPOP = 23
    920 };
    921 
    922 void WriteToSyslog(const char *buffer);
    923 
    924 #if defined(SANITIZER_WINDOWS) && defined(_MSC_VER) && !defined(__clang__)
    925 #define SANITIZER_WIN_TRACE 1
    926 #else
    927 #define SANITIZER_WIN_TRACE 0
    928 #endif
    929 
    930 #if SANITIZER_APPLE || SANITIZER_WIN_TRACE
    931 void LogFullErrorReport(const char *buffer);
    932 #else
    933 inline void LogFullErrorReport(const char *buffer) {}
    934 #endif
    935 
    936 #if SANITIZER_LINUX || SANITIZER_APPLE
    937 void WriteOneLineToSyslog(const char *s);
    938 void LogMessageOnPrintf(const char *str);
    939 #else
    940 inline void WriteOneLineToSyslog(const char *s) {}
    941 inline void LogMessageOnPrintf(const char *str) {}
    942 #endif
    943 
    944 #if SANITIZER_LINUX || SANITIZER_WIN_TRACE
    945 // Initialize Android logging. Any writes before this are silently lost.
    946 void AndroidLogInit();
    947 void SetAbortMessage(const char *);
    948 #else
    949 inline void AndroidLogInit() {}
    950 // FIXME: MacOS implementation could use CRSetCrashLogMessage.
    951 inline void SetAbortMessage(const char *) {}
    952 #endif
    953 
    954 #if SANITIZER_ANDROID
    955 void SanitizerInitializeUnwinder();
    956 AndroidApiLevel AndroidGetApiLevel();
    957 #else
    958 inline void AndroidLogWrite(const char *buffer_unused) {}
    959 inline void SanitizerInitializeUnwinder() {}
    960 inline AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
    961 #endif
    962 
    963 inline uptr GetPthreadDestructorIterations() {
    964 #if SANITIZER_ANDROID
    965   return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
    966 #elif SANITIZER_POSIX
    967   return 4;
    968 #else
    969 // Unused on Windows.
    970   return 0;
    971 #endif
    972 }
    973 
    974 void *internal_start_thread(void *(*func)(void*), void *arg);
    975 void internal_join_thread(void *th);
    976 void MaybeStartBackgroudThread();
    977 
    978 // Make the compiler think that something is going on there.
    979 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
    980 // compiler from recognising it and turning it into an actual call to
    981 // memset/memcpy/etc.
    982 static inline void SanitizerBreakOptimization(void *arg) {
    983 #if defined(_MSC_VER) && !defined(__clang__)
    984   _ReadWriteBarrier();
    985 #else
    986   __asm__ __volatile__("" : : "r" (arg) : "memory");
    987 #endif
    988 }
    989 
    990 struct SignalContext {
    991   void *siginfo;
    992   void *context;
    993   uptr addr;
    994   uptr pc;
    995   uptr sp;
    996   uptr bp;
    997   bool is_memory_access;
    998   enum WriteFlag { Unknown, Read, Write } write_flag;
    999 
   1000   // In some cases the kernel cannot provide the true faulting address; `addr`
   1001   // will be zero then.  This field allows to distinguish between these cases
   1002   // and dereferences of null.
   1003   bool is_true_faulting_addr;
   1004 
   1005   // VS2013 doesn't implement unrestricted unions, so we need a trivial default
   1006   // constructor
   1007   SignalContext() = default;
   1008 
   1009   // Creates signal context in a platform-specific manner.
   1010   // SignalContext is going to keep pointers to siginfo and context without
   1011   // owning them.
   1012   SignalContext(void *siginfo, void *context)
   1013       : siginfo(siginfo),
   1014         context(context),
   1015         addr(GetAddress()),
   1016         is_memory_access(IsMemoryAccess()),
   1017         write_flag(GetWriteFlag()),
   1018         is_true_faulting_addr(IsTrueFaultingAddress()) {
   1019     InitPcSpBp();
   1020   }
   1021 
   1022   static void DumpAllRegisters(void *context);
   1023 
   1024   // Type of signal e.g. SIGSEGV or EXCEPTION_ACCESS_VIOLATION.
   1025   int GetType() const;
   1026 
   1027   // String description of the signal.
   1028   const char *Describe() const;
   1029 
   1030   // Returns true if signal is stack overflow.
   1031   bool IsStackOverflow() const;
   1032 
   1033  private:
   1034   // Platform specific initialization.
   1035   void InitPcSpBp();
   1036   uptr GetAddress() const;
   1037   WriteFlag GetWriteFlag() const;
   1038   bool IsMemoryAccess() const;
   1039   bool IsTrueFaultingAddress() const;
   1040 };
   1041 
   1042 void InitializePlatformEarly();
   1043 
   1044 template <typename Fn>
   1045 class RunOnDestruction {
   1046  public:
   1047   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
   1048   ~RunOnDestruction() { fn_(); }
   1049 
   1050  private:
   1051   Fn fn_;
   1052 };
   1053 
   1054 // A simple scope guard. Usage:
   1055 // auto cleanup = at_scope_exit([]{ do_cleanup; });
   1056 template <typename Fn>
   1057 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
   1058   return RunOnDestruction<Fn>(fn);
   1059 }
   1060 
   1061 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
   1062 // if a process uses virtual memory over 4TB (as many sanitizers like
   1063 // to do).  This function will abort the process if running on a kernel
   1064 // that looks vulnerable.
   1065 #if SANITIZER_LINUX && SANITIZER_S390_64
   1066 void AvoidCVE_2016_2143();
   1067 #else
   1068 inline void AvoidCVE_2016_2143() {}
   1069 #endif
   1070 
   1071 struct StackDepotStats {
   1072   uptr n_uniq_ids;
   1073   uptr allocated;
   1074 };
   1075 
   1076 // The default value for allocator_release_to_os_interval_ms common flag to
   1077 // indicate that sanitizer allocator should not attempt to release memory to OS.
   1078 const s32 kReleaseToOSIntervalNever = -1;
   1079 
   1080 void CheckNoDeepBind(const char *filename, int flag);
   1081 
   1082 // Returns the requested amount of random data (up to 256 bytes) that can then
   1083 // be used to seed a PRNG. Defaults to blocking like the underlying syscall.
   1084 bool GetRandom(void *buffer, uptr length, bool blocking = true);
   1085 
   1086 // Returns the number of logical processors on the system.
   1087 u32 GetNumberOfCPUs();
   1088 extern u32 NumberOfCPUsCached;
   1089 inline u32 GetNumberOfCPUsCached() {
   1090   if (!NumberOfCPUsCached)
   1091     NumberOfCPUsCached = GetNumberOfCPUs();
   1092   return NumberOfCPUsCached;
   1093 }
   1094 
   1095 }  // namespace __sanitizer
   1096 
   1097 inline void *operator new(__sanitizer::operator_new_size_type size,
   1098                           __sanitizer::LowLevelAllocator &alloc) {
   1099   return alloc.Allocate(size);
   1100 }
   1101 
   1102 #endif  // SANITIZER_COMMON_H
   1103