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