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