]> 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++ r303571, 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 CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args);
321 void SetSandboxingCallback(void (*f)());
322
323 void CoverageUpdateMapping();
324 void CovBeforeFork();
325 void CovAfterFork(int child_pid);
326
327 void InitializeCoverage(bool enabled, const char *coverage_dir);
328 void ReInitializeCoverage(bool enabled, const char *coverage_dir);
329
330 void InitTlsSize();
331 uptr GetTlsSize();
332
333 // Other
334 void SleepForSeconds(int seconds);
335 void SleepForMillis(int millis);
336 u64 NanoTime();
337 int Atexit(void (*function)(void));
338 void SortArray(uptr *array, uptr size);
339 void SortArray(u32 *array, uptr size);
340 bool TemplateMatch(const char *templ, const char *str);
341
342 // Exit
343 void NORETURN Abort();
344 void NORETURN Die();
345 void NORETURN
346 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
347 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
348                                       const char *mmap_type, error_t err,
349                                       bool raw_report = false);
350
351 // Set the name of the current thread to 'name', return true on succees.
352 // The name may be truncated to a system-dependent limit.
353 bool SanitizerSetThreadName(const char *name);
354 // Get the name of the current thread (no more than max_len bytes),
355 // return true on succees. name should have space for at least max_len+1 bytes.
356 bool SanitizerGetThreadName(char *name, int max_len);
357
358 // Specific tools may override behavior of "Die" and "CheckFailed" functions
359 // to do tool-specific job.
360 typedef void (*DieCallbackType)(void);
361
362 // It's possible to add several callbacks that would be run when "Die" is
363 // called. The callbacks will be run in the opposite order. The tools are
364 // strongly recommended to setup all callbacks during initialization, when there
365 // is only a single thread.
366 bool AddDieCallback(DieCallbackType callback);
367 bool RemoveDieCallback(DieCallbackType callback);
368
369 void SetUserDieCallback(DieCallbackType callback);
370
371 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
372                                        u64, u64);
373 void SetCheckFailedCallback(CheckFailedCallbackType callback);
374
375 // Callback will be called if soft_rss_limit_mb is given and the limit is
376 // exceeded (exceeded==true) or if rss went down below the limit
377 // (exceeded==false).
378 // The callback should be registered once at the tool init time.
379 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
380
381 // Functions related to signal handling.
382 typedef void (*SignalHandlerType)(int, void *, void *);
383 bool IsHandledDeadlySignal(int signum);
384 void InstallDeadlySignalHandlers(SignalHandlerType handler);
385 const char *DescribeSignalOrException(int signo);
386 // Alternative signal stack (POSIX-only).
387 void SetAlternateSignalStack();
388 void UnsetAlternateSignalStack();
389
390 // We don't want a summary too long.
391 const int kMaxSummaryLength = 1024;
392 // Construct a one-line string:
393 //   SUMMARY: SanitizerToolName: error_message
394 // and pass it to __sanitizer_report_error_summary.
395 // If alt_tool_name is provided, it's used in place of SanitizerToolName.
396 void ReportErrorSummary(const char *error_message,
397                         const char *alt_tool_name = nullptr);
398 // Same as above, but construct error_message as:
399 //   error_type file:line[:column][ function]
400 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
401                         const char *alt_tool_name = nullptr);
402 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
403 void ReportErrorSummary(const char *error_type, const StackTrace *trace,
404                         const char *alt_tool_name = nullptr);
405
406 // Math
407 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
408 extern "C" {
409 unsigned char _BitScanForward(unsigned long *index, unsigned long mask);  // NOLINT
410 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);  // NOLINT
411 #if defined(_WIN64)
412 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask);  // NOLINT
413 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask);  // NOLINT
414 #endif
415 }
416 #endif
417
418 INLINE uptr MostSignificantSetBitIndex(uptr x) {
419   CHECK_NE(x, 0U);
420   unsigned long up;  // NOLINT
421 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
422 # ifdef _WIN64
423   up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
424 # else
425   up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
426 # endif
427 #elif defined(_WIN64)
428   _BitScanReverse64(&up, x);
429 #else
430   _BitScanReverse(&up, x);
431 #endif
432   return up;
433 }
434
435 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
436   CHECK_NE(x, 0U);
437   unsigned long up;  // NOLINT
438 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
439 # ifdef _WIN64
440   up = __builtin_ctzll(x);
441 # else
442   up = __builtin_ctzl(x);
443 # endif
444 #elif defined(_WIN64)
445   _BitScanForward64(&up, x);
446 #else
447   _BitScanForward(&up, x);
448 #endif
449   return up;
450 }
451
452 INLINE bool IsPowerOfTwo(uptr x) {
453   return (x & (x - 1)) == 0;
454 }
455
456 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
457   CHECK(size);
458   if (IsPowerOfTwo(size)) return size;
459
460   uptr up = MostSignificantSetBitIndex(size);
461   CHECK_LT(size, (1ULL << (up + 1)));
462   CHECK_GT(size, (1ULL << up));
463   return 1ULL << (up + 1);
464 }
465
466 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
467   RAW_CHECK(IsPowerOfTwo(boundary));
468   return (size + boundary - 1) & ~(boundary - 1);
469 }
470
471 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
472   return x & ~(boundary - 1);
473 }
474
475 INLINE bool IsAligned(uptr a, uptr alignment) {
476   return (a & (alignment - 1)) == 0;
477 }
478
479 INLINE uptr Log2(uptr x) {
480   CHECK(IsPowerOfTwo(x));
481   return LeastSignificantSetBitIndex(x);
482 }
483
484 // Don't use std::min, std::max or std::swap, to minimize dependency
485 // on libstdc++.
486 template<class T> T Min(T a, T b) { return a < b ? a : b; }
487 template<class T> T Max(T a, T b) { return a > b ? a : b; }
488 template<class T> void Swap(T& a, T& b) {
489   T tmp = a;
490   a = b;
491   b = tmp;
492 }
493
494 // Char handling
495 INLINE bool IsSpace(int c) {
496   return (c == ' ') || (c == '\n') || (c == '\t') ||
497          (c == '\f') || (c == '\r') || (c == '\v');
498 }
499 INLINE bool IsDigit(int c) {
500   return (c >= '0') && (c <= '9');
501 }
502 INLINE int ToLower(int c) {
503   return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
504 }
505
506 // A low-level vector based on mmap. May incur a significant memory overhead for
507 // small vectors.
508 // WARNING: The current implementation supports only POD types.
509 template<typename T>
510 class InternalMmapVectorNoCtor {
511  public:
512   void Initialize(uptr initial_capacity) {
513     capacity_ = Max(initial_capacity, (uptr)1);
514     size_ = 0;
515     data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
516   }
517   void Destroy() {
518     UnmapOrDie(data_, capacity_ * sizeof(T));
519   }
520   T &operator[](uptr i) {
521     CHECK_LT(i, size_);
522     return data_[i];
523   }
524   const T &operator[](uptr i) const {
525     CHECK_LT(i, size_);
526     return data_[i];
527   }
528   void push_back(const T &element) {
529     CHECK_LE(size_, capacity_);
530     if (size_ == capacity_) {
531       uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
532       Resize(new_capacity);
533     }
534     internal_memcpy(&data_[size_++], &element, sizeof(T));
535   }
536   T &back() {
537     CHECK_GT(size_, 0);
538     return data_[size_ - 1];
539   }
540   void pop_back() {
541     CHECK_GT(size_, 0);
542     size_--;
543   }
544   uptr size() const {
545     return size_;
546   }
547   const T *data() const {
548     return data_;
549   }
550   T *data() {
551     return data_;
552   }
553   uptr capacity() const {
554     return capacity_;
555   }
556   void resize(uptr new_size) {
557     Resize(new_size);
558     if (new_size > size_) {
559       internal_memset(&data_[size_], 0, sizeof(T) * (new_size - size_));
560     }
561     size_ = new_size;
562   }
563
564   void clear() { size_ = 0; }
565   bool empty() const { return size() == 0; }
566
567   const T *begin() const {
568     return data();
569   }
570   T *begin() {
571     return data();
572   }
573   const T *end() const {
574     return data() + size();
575   }
576   T *end() {
577     return data() + size();
578   }
579
580  private:
581   void Resize(uptr new_capacity) {
582     CHECK_GT(new_capacity, 0);
583     CHECK_LE(size_, new_capacity);
584     T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
585                                  "InternalMmapVector");
586     internal_memcpy(new_data, data_, size_ * sizeof(T));
587     T *old_data = data_;
588     data_ = new_data;
589     UnmapOrDie(old_data, capacity_ * sizeof(T));
590     capacity_ = new_capacity;
591   }
592
593   T *data_;
594   uptr capacity_;
595   uptr size_;
596 };
597
598 template<typename T>
599 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
600  public:
601   explicit InternalMmapVector(uptr initial_capacity) {
602     InternalMmapVectorNoCtor<T>::Initialize(initial_capacity);
603   }
604   ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
605   // Disallow evil constructors.
606   InternalMmapVector(const InternalMmapVector&);
607   void operator=(const InternalMmapVector&);
608 };
609
610 // HeapSort for arrays and InternalMmapVector.
611 template<class Container, class Compare>
612 void InternalSort(Container *v, uptr size, Compare comp) {
613   if (size < 2)
614     return;
615   // Stage 1: insert elements to the heap.
616   for (uptr i = 1; i < size; i++) {
617     uptr j, p;
618     for (j = i; j > 0; j = p) {
619       p = (j - 1) / 2;
620       if (comp((*v)[p], (*v)[j]))
621         Swap((*v)[j], (*v)[p]);
622       else
623         break;
624     }
625   }
626   // Stage 2: swap largest element with the last one,
627   // and sink the new top.
628   for (uptr i = size - 1; i > 0; i--) {
629     Swap((*v)[0], (*v)[i]);
630     uptr j, max_ind;
631     for (j = 0; j < i; j = max_ind) {
632       uptr left = 2 * j + 1;
633       uptr right = 2 * j + 2;
634       max_ind = j;
635       if (left < i && comp((*v)[max_ind], (*v)[left]))
636         max_ind = left;
637       if (right < i && comp((*v)[max_ind], (*v)[right]))
638         max_ind = right;
639       if (max_ind != j)
640         Swap((*v)[j], (*v)[max_ind]);
641       else
642         break;
643     }
644   }
645 }
646
647 // Works like std::lower_bound: finds the first element that is not less
648 // than the val.
649 template <class Container, class Value, class Compare>
650 uptr InternalLowerBound(const Container &v, uptr first, uptr last,
651                         const Value &val, Compare comp) {
652   while (last > first) {
653     uptr mid = (first + last) / 2;
654     if (comp(v[mid], val))
655       first = mid + 1;
656     else
657       last = mid;
658   }
659   return first;
660 }
661
662 enum ModuleArch {
663   kModuleArchUnknown,
664   kModuleArchI386,
665   kModuleArchX86_64,
666   kModuleArchX86_64H,
667   kModuleArchARMV6,
668   kModuleArchARMV7,
669   kModuleArchARMV7S,
670   kModuleArchARMV7K,
671   kModuleArchARM64
672 };
673
674 // When adding a new architecture, don't forget to also update
675 // script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cc.
676 inline const char *ModuleArchToString(ModuleArch arch) {
677   switch (arch) {
678     case kModuleArchUnknown:
679       return "";
680     case kModuleArchI386:
681       return "i386";
682     case kModuleArchX86_64:
683       return "x86_64";
684     case kModuleArchX86_64H:
685       return "x86_64h";
686     case kModuleArchARMV6:
687       return "armv6";
688     case kModuleArchARMV7:
689       return "armv7";
690     case kModuleArchARMV7S:
691       return "armv7s";
692     case kModuleArchARMV7K:
693       return "armv7k";
694     case kModuleArchARM64:
695       return "arm64";
696   }
697   CHECK(0 && "Invalid module arch");
698   return "";
699 }
700
701 const uptr kModuleUUIDSize = 16;
702
703 // Represents a binary loaded into virtual memory (e.g. this can be an
704 // executable or a shared object).
705 class LoadedModule {
706  public:
707   LoadedModule()
708       : full_name_(nullptr),
709         base_address_(0),
710         max_executable_address_(0),
711         arch_(kModuleArchUnknown),
712         instrumented_(false) {
713     internal_memset(uuid_, 0, kModuleUUIDSize);
714     ranges_.clear();
715   }
716   void set(const char *module_name, uptr base_address);
717   void set(const char *module_name, uptr base_address, ModuleArch arch,
718            u8 uuid[kModuleUUIDSize], bool instrumented);
719   void clear();
720   void addAddressRange(uptr beg, uptr end, bool executable, bool writable);
721   bool containsAddress(uptr address) const;
722
723   const char *full_name() const { return full_name_; }
724   uptr base_address() const { return base_address_; }
725   uptr max_executable_address() const { return max_executable_address_; }
726   ModuleArch arch() const { return arch_; }
727   const u8 *uuid() const { return uuid_; }
728   bool instrumented() const { return instrumented_; }
729
730   struct AddressRange {
731     AddressRange *next;
732     uptr beg;
733     uptr end;
734     bool executable;
735     bool writable;
736
737     AddressRange(uptr beg, uptr end, bool executable, bool writable)
738         : next(nullptr),
739           beg(beg),
740           end(end),
741           executable(executable),
742           writable(writable) {}
743   };
744
745   const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
746
747  private:
748   char *full_name_;  // Owned.
749   uptr base_address_;
750   uptr max_executable_address_;
751   ModuleArch arch_;
752   u8 uuid_[kModuleUUIDSize];
753   bool instrumented_;
754   IntrusiveList<AddressRange> ranges_;
755 };
756
757 // List of LoadedModules. OS-dependent implementation is responsible for
758 // filling this information.
759 class ListOfModules {
760  public:
761   ListOfModules() : modules_(kInitialCapacity) {}
762   ~ListOfModules() { clear(); }
763   void init();
764   const LoadedModule *begin() const { return modules_.begin(); }
765   LoadedModule *begin() { return modules_.begin(); }
766   const LoadedModule *end() const { return modules_.end(); }
767   LoadedModule *end() { return modules_.end(); }
768   uptr size() const { return modules_.size(); }
769   const LoadedModule &operator[](uptr i) const {
770     CHECK_LT(i, modules_.size());
771     return modules_[i];
772   }
773
774  private:
775   void clear() {
776     for (auto &module : modules_) module.clear();
777     modules_.clear();
778   }
779
780   InternalMmapVector<LoadedModule> modules_;
781   // We rarely have more than 16K loaded modules.
782   static const uptr kInitialCapacity = 1 << 14;
783 };
784
785 // Callback type for iterating over a set of memory ranges.
786 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
787
788 enum AndroidApiLevel {
789   ANDROID_NOT_ANDROID = 0,
790   ANDROID_KITKAT = 19,
791   ANDROID_LOLLIPOP_MR1 = 22,
792   ANDROID_POST_LOLLIPOP = 23
793 };
794
795 void WriteToSyslog(const char *buffer);
796
797 #if SANITIZER_MAC
798 void LogFullErrorReport(const char *buffer);
799 #else
800 INLINE void LogFullErrorReport(const char *buffer) {}
801 #endif
802
803 #if SANITIZER_LINUX || SANITIZER_MAC
804 void WriteOneLineToSyslog(const char *s);
805 void LogMessageOnPrintf(const char *str);
806 #else
807 INLINE void WriteOneLineToSyslog(const char *s) {}
808 INLINE void LogMessageOnPrintf(const char *str) {}
809 #endif
810
811 #if SANITIZER_LINUX
812 // Initialize Android logging. Any writes before this are silently lost.
813 void AndroidLogInit();
814 #else
815 INLINE void AndroidLogInit() {}
816 #endif
817
818 #if SANITIZER_ANDROID
819 void SanitizerInitializeUnwinder();
820 AndroidApiLevel AndroidGetApiLevel();
821 #else
822 INLINE void AndroidLogWrite(const char *buffer_unused) {}
823 INLINE void SanitizerInitializeUnwinder() {}
824 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
825 #endif
826
827 INLINE uptr GetPthreadDestructorIterations() {
828 #if SANITIZER_ANDROID
829   return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
830 #elif SANITIZER_POSIX
831   return 4;
832 #else
833 // Unused on Windows.
834   return 0;
835 #endif
836 }
837
838 void *internal_start_thread(void(*func)(void*), void *arg);
839 void internal_join_thread(void *th);
840 void MaybeStartBackgroudThread();
841
842 // Make the compiler think that something is going on there.
843 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
844 // compiler from recognising it and turning it into an actual call to
845 // memset/memcpy/etc.
846 static inline void SanitizerBreakOptimization(void *arg) {
847 #if defined(_MSC_VER) && !defined(__clang__)
848   _ReadWriteBarrier();
849 #else
850   __asm__ __volatile__("" : : "r" (arg) : "memory");
851 #endif
852 }
853
854 struct SignalContext {
855   void *context;
856   uptr addr;
857   uptr pc;
858   uptr sp;
859   uptr bp;
860   bool is_memory_access;
861
862   enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
863
864   SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp,
865                 bool is_memory_access, WriteFlag write_flag)
866       : context(context),
867         addr(addr),
868         pc(pc),
869         sp(sp),
870         bp(bp),
871         is_memory_access(is_memory_access),
872         write_flag(write_flag) {}
873
874   static void DumpAllRegisters(void *context);
875
876   // Creates signal context in a platform-specific manner.
877   static SignalContext Create(void *siginfo, void *context);
878
879   // Returns true if the "context" indicates a memory write.
880   static WriteFlag GetWriteFlag(void *context);
881 };
882
883 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
884
885 void MaybeReexec();
886
887 template <typename Fn>
888 class RunOnDestruction {
889  public:
890   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
891   ~RunOnDestruction() { fn_(); }
892
893  private:
894   Fn fn_;
895 };
896
897 // A simple scope guard. Usage:
898 // auto cleanup = at_scope_exit([]{ do_cleanup; });
899 template <typename Fn>
900 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
901   return RunOnDestruction<Fn>(fn);
902 }
903
904 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
905 // if a process uses virtual memory over 4TB (as many sanitizers like
906 // to do).  This function will abort the process if running on a kernel
907 // that looks vulnerable.
908 #if SANITIZER_LINUX && SANITIZER_S390_64
909 void AvoidCVE_2016_2143();
910 #else
911 INLINE void AvoidCVE_2016_2143() {}
912 #endif
913
914 struct StackDepotStats {
915   uptr n_uniq_ids;
916   uptr allocated;
917 };
918
919 // The default value for allocator_release_to_os_interval_ms common flag to
920 // indicate that sanitizer allocator should not attempt to release memory to OS.
921 const s32 kReleaseToOSIntervalNever = -1;
922
923 void CheckNoDeepBind(const char *filename, int flag);
924
925 }  // namespace __sanitizer
926
927 inline void *operator new(__sanitizer::operator_new_size_type size,
928                           __sanitizer::LowLevelAllocator &alloc) {
929   return alloc.Allocate(size);
930 }
931
932 #endif  // SANITIZER_COMMON_H