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