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