592c5fcc37a5b001c03ed771b335c4ca9c515044
[platform/upstream/linaro-gcc.git] / libsanitizer / sanitizer_common / sanitizer_common.h
1 //===-- sanitizer_common.h --------------------------------------*- C++ -*-===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is shared between run-time libraries of sanitizers.
9 //
10 // It declares common functions and classes that are used in both runtimes.
11 // Implementation of some functions are provided in sanitizer_common, while
12 // others must be defined by run-time library itself.
13 //===----------------------------------------------------------------------===//
14 #ifndef SANITIZER_COMMON_H
15 #define SANITIZER_COMMON_H
16
17 #include "sanitizer_flags.h"
18 #include "sanitizer_interface_internal.h"
19 #include "sanitizer_internal_defs.h"
20 #include "sanitizer_libc.h"
21 #include "sanitizer_list.h"
22 #include "sanitizer_mutex.h"
23
24 #if defined(_MSC_VER) && !defined(__clang__)
25 extern "C" void _ReadWriteBarrier();
26 #pragma intrinsic(_ReadWriteBarrier)
27 #endif
28
29 namespace __sanitizer {
30 struct StackTrace;
31 struct AddressInfo;
32
33 // Constants.
34 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
35 const uptr kWordSizeInBits = 8 * kWordSize;
36
37 #if defined(__powerpc__) || defined(__powerpc64__)
38   const uptr kCacheLineSize = 128;
39 #else
40   const uptr kCacheLineSize = 64;
41 #endif
42
43 const uptr kMaxPathLength = 4096;
44
45 const uptr kMaxThreadStackSize = 1 << 30;  // 1Gb
46
47 static const uptr kErrorMessageBufferSize = 1 << 16;
48
49 // Denotes fake PC values that come from JIT/JAVA/etc.
50 // For such PC values __tsan_symbolize_external() will be called.
51 const u64 kExternalPCBit = 1ULL << 60;
52
53 extern const char *SanitizerToolName;  // Can be changed by the tool.
54
55 extern atomic_uint32_t current_verbosity;
56 INLINE void SetVerbosity(int verbosity) {
57   atomic_store(&current_verbosity, verbosity, memory_order_relaxed);
58 }
59 INLINE int Verbosity() {
60   return atomic_load(&current_verbosity, memory_order_relaxed);
61 }
62
63 uptr GetPageSize();
64 extern uptr PageSizeCached;
65 INLINE uptr GetPageSizeCached() {
66   if (!PageSizeCached)
67     PageSizeCached = GetPageSize();
68   return PageSizeCached;
69 }
70 uptr GetMmapGranularity();
71 uptr GetMaxVirtualAddress();
72 // Threads
73 uptr GetTid();
74 uptr GetThreadSelf();
75 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
76                                 uptr *stack_bottom);
77 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
78                           uptr *tls_addr, uptr *tls_size);
79
80 // Memory management
81 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report = false);
82 INLINE void *MmapOrDieQuietly(uptr size, const char *mem_type) {
83   return MmapOrDie(size, mem_type, /*raw_report*/ true);
84 }
85 void UnmapOrDie(void *addr, uptr size);
86 // Behaves just like MmapOrDie, but tolerates out of memory condition, in that
87 // case returns nullptr.
88 void *MmapOrDieOnFatalError(uptr size, const char *mem_type);
89 void *MmapFixedNoReserve(uptr fixed_addr, uptr size,
90                          const char *name = nullptr);
91 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
92 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
93 // Behaves just like MmapFixedOrDie, but tolerates out of memory condition, in
94 // that case returns nullptr.
95 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size);
96 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name = nullptr);
97 void *MmapNoAccess(uptr size);
98 // Map aligned chunk of address space; size and alignment are powers of two.
99 // Dies on all but out of memory errors, in the latter case returns nullptr.
100 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
101                                    const char *mem_type);
102 // Disallow access to a memory range.  Use MmapFixedNoAccess to allocate an
103 // unaccessible memory.
104 bool MprotectNoAccess(uptr addr, uptr size);
105 bool MprotectReadOnly(uptr addr, uptr size);
106
107 // Find an available address space.
108 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding);
109
110 // Used to check if we can map shadow memory to a fixed location.
111 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
112 void ReleaseMemoryToOS(uptr addr, uptr size);
113 void IncreaseTotalMmap(uptr size);
114 void DecreaseTotalMmap(uptr size);
115 uptr GetRSS();
116 void NoHugePagesInRegion(uptr addr, uptr length);
117 void DontDumpShadowMemory(uptr addr, uptr length);
118 // Check if the built VMA size matches the runtime one.
119 void CheckVMASize();
120 void RunMallocHooks(const void *ptr, uptr size);
121 void RunFreeHooks(const void *ptr);
122
123 // InternalScopedBuffer can be used instead of large stack arrays to
124 // keep frame size low.
125 // FIXME: use InternalAlloc instead of MmapOrDie once
126 // InternalAlloc is made libc-free.
127 template <typename T>
128 class InternalScopedBuffer {
129  public:
130   explicit InternalScopedBuffer(uptr cnt) {
131     cnt_ = cnt;
132     ptr_ = (T *)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
133   }
134   ~InternalScopedBuffer() { UnmapOrDie(ptr_, cnt_ * sizeof(T)); }
135   T &operator[](uptr i) { return ptr_[i]; }
136   T *data() { return ptr_; }
137   uptr size() { return cnt_ * sizeof(T); }
138
139  private:
140   T *ptr_;
141   uptr cnt_;
142   // Disallow copies and moves.
143   InternalScopedBuffer(const InternalScopedBuffer &) = delete;
144   InternalScopedBuffer &operator=(const InternalScopedBuffer &) = delete;
145   InternalScopedBuffer(InternalScopedBuffer &&) = delete;
146   InternalScopedBuffer &operator=(InternalScopedBuffer &&) = delete;
147 };
148
149 class InternalScopedString : public InternalScopedBuffer<char> {
150  public:
151   explicit InternalScopedString(uptr max_length)
152       : InternalScopedBuffer<char>(max_length), length_(0) {
153     (*this)[0] = '\0';
154   }
155   uptr length() { return length_; }
156   void clear() {
157     (*this)[0] = '\0';
158     length_ = 0;
159   }
160   void append(const char *format, ...);
161
162  private:
163   uptr length_;
164 };
165
166 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
167 // constructor, so all instances of LowLevelAllocator should be
168 // linker initialized.
169 class LowLevelAllocator {
170  public:
171   // Requires an external lock.
172   void *Allocate(uptr size);
173  private:
174   char *allocated_end_;
175   char *allocated_current_;
176 };
177 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
178 // Allows to register tool-specific callbacks for LowLevelAllocator.
179 // Passing NULL removes the callback.
180 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
181
182 // IO
183 void RawWrite(const char *buffer);
184 bool ColorizeReports();
185 void RemoveANSIEscapeSequencesFromString(char *buffer);
186 void Printf(const char *format, ...);
187 void Report(const char *format, ...);
188 void SetPrintfAndReportCallback(void (*callback)(const char *));
189 #define VReport(level, ...)                                              \
190   do {                                                                   \
191     if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
192   } while (0)
193 #define VPrintf(level, ...)                                              \
194   do {                                                                   \
195     if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
196   } while (0)
197
198 // Can be used to prevent mixing error reports from different sanitizers.
199 extern StaticSpinMutex CommonSanitizerReportMutex;
200
201 struct ReportFile {
202   void Write(const char *buffer, uptr length);
203   bool SupportsColors();
204   void SetReportPath(const char *path);
205
206   // Don't use fields directly. They are only declared public to allow
207   // aggregate initialization.
208
209   // Protects fields below.
210   StaticSpinMutex *mu;
211   // Opened file descriptor. Defaults to stderr. It may be equal to
212   // kInvalidFd, in which case new file will be opened when necessary.
213   fd_t fd;
214   // Path prefix of report file, set via __sanitizer_set_report_path.
215   char path_prefix[kMaxPathLength];
216   // Full path to report, obtained as <path_prefix>.PID
217   char full_path[kMaxPathLength];
218   // PID of the process that opened fd. If a fork() occurs,
219   // the PID of child will be different from fd_pid.
220   uptr fd_pid;
221
222  private:
223   void ReopenIfNecessary();
224 };
225 extern ReportFile report_file;
226
227 extern uptr stoptheworld_tracer_pid;
228 extern uptr stoptheworld_tracer_ppid;
229
230 enum FileAccessMode {
231   RdOnly,
232   WrOnly,
233   RdWr
234 };
235
236 // Returns kInvalidFd on error.
237 fd_t OpenFile(const char *filename, FileAccessMode mode,
238               error_t *errno_p = nullptr);
239 void CloseFile(fd_t);
240
241 // Return true on success, false on error.
242 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size,
243                   uptr *bytes_read = nullptr, error_t *error_p = nullptr);
244 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size,
245                  uptr *bytes_written = nullptr, error_t *error_p = nullptr);
246
247 bool RenameFile(const char *oldpath, const char *newpath,
248                 error_t *error_p = nullptr);
249
250 // Scoped file handle closer.
251 struct FileCloser {
252   explicit FileCloser(fd_t fd) : fd(fd) {}
253   ~FileCloser() { CloseFile(fd); }
254   fd_t fd;
255 };
256
257 bool SupportsColoredOutput(fd_t fd);
258
259 // Opens the file 'file_name" and reads up to 'max_len' bytes.
260 // The resulting buffer is mmaped and stored in '*buff'.
261 // The size of the mmaped region is stored in '*buff_size'.
262 // The total number of read bytes is stored in '*read_len'.
263 // Returns true if file was successfully opened and read.
264 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
265                       uptr *read_len, uptr max_len = 1 << 26,
266                       error_t *errno_p = nullptr);
267 // Maps given file to virtual memory, and returns pointer to it
268 // (or NULL if mapping fails). Stores the size of mmaped region
269 // in '*buff_size'.
270 void *MapFileToMemory(const char *file_name, uptr *buff_size);
271 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset);
272
273 bool IsAccessibleMemoryRange(uptr beg, uptr size);
274
275 // Error report formatting.
276 const char *StripPathPrefix(const char *filepath,
277                             const char *strip_file_prefix);
278 // Strip the directories from the module name.
279 const char *StripModuleName(const char *module);
280
281 // OS
282 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
283 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
284 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len);
285 const char *GetProcessName();
286 void UpdateProcessName();
287 void CacheBinaryName();
288 void DisableCoreDumperIfNecessary();
289 void DumpProcessMap();
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 CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args);
324 void SetSandboxingCallback(void (*f)());
325
326 void CoverageUpdateMapping();
327 void CovBeforeFork();
328 void CovAfterFork(int child_pid);
329
330 void InitializeCoverage(bool enabled, const char *coverage_dir);
331 void ReInitializeCoverage(bool enabled, const char *coverage_dir);
332
333 void InitTlsSize();
334 uptr GetTlsSize();
335
336 // Other
337 void SleepForSeconds(int seconds);
338 void SleepForMillis(int millis);
339 u64 NanoTime();
340 int Atexit(void (*function)(void));
341 void SortArray(uptr *array, uptr size);
342 void SortArray(u32 *array, uptr size);
343 bool TemplateMatch(const char *templ, const char *str);
344
345 // Exit
346 void NORETURN Abort();
347 void NORETURN Die();
348 void NORETURN
349 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
350 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
351                                       const char *mmap_type, error_t err,
352                                       bool raw_report = false);
353
354 // Set the name of the current thread to 'name', return true on succees.
355 // The name may be truncated to a system-dependent limit.
356 bool SanitizerSetThreadName(const char *name);
357 // Get the name of the current thread (no more than max_len bytes),
358 // return true on succees. name should have space for at least max_len+1 bytes.
359 bool SanitizerGetThreadName(char *name, int max_len);
360
361 // Specific tools may override behavior of "Die" and "CheckFailed" functions
362 // to do tool-specific job.
363 typedef void (*DieCallbackType)(void);
364
365 // It's possible to add several callbacks that would be run when "Die" is
366 // called. The callbacks will be run in the opposite order. The tools are
367 // strongly recommended to setup all callbacks during initialization, when there
368 // is only a single thread.
369 bool AddDieCallback(DieCallbackType callback);
370 bool RemoveDieCallback(DieCallbackType callback);
371
372 void SetUserDieCallback(DieCallbackType callback);
373
374 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
375                                        u64, u64);
376 void SetCheckFailedCallback(CheckFailedCallbackType callback);
377
378 // Callback will be called if soft_rss_limit_mb is given and the limit is
379 // exceeded (exceeded==true) or if rss went down below the limit
380 // (exceeded==false).
381 // The callback should be registered once at the tool init time.
382 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
383
384 // Callback to be called when we want to try releasing unused allocator memory
385 // back to the OS.
386 typedef void (*AllocatorReleaseToOSCallback)();
387 // The callback should be registered once at the tool init time.
388 void SetAllocatorReleaseToOSCallback(AllocatorReleaseToOSCallback Callback);
389
390 // Functions related to signal handling.
391 typedef void (*SignalHandlerType)(int, void *, void *);
392 bool IsHandledDeadlySignal(int signum);
393 void InstallDeadlySignalHandlers(SignalHandlerType handler);
394 // Alternative signal stack (POSIX-only).
395 void SetAlternateSignalStack();
396 void UnsetAlternateSignalStack();
397
398 // We don't want a summary too long.
399 const int kMaxSummaryLength = 1024;
400 // Construct a one-line string:
401 //   SUMMARY: SanitizerToolName: error_message
402 // and pass it to __sanitizer_report_error_summary.
403 void ReportErrorSummary(const char *error_message);
404 // Same as above, but construct error_message as:
405 //   error_type file:line[:column][ function]
406 void ReportErrorSummary(const char *error_type, const AddressInfo &info);
407 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
408 void ReportErrorSummary(const char *error_type, const StackTrace *trace);
409
410 // Math
411 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
412 extern "C" {
413 unsigned char _BitScanForward(unsigned long *index, unsigned long mask);  // NOLINT
414 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);  // NOLINT
415 #if defined(_WIN64)
416 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask);  // NOLINT
417 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask);  // NOLINT
418 #endif
419 }
420 #endif
421
422 INLINE uptr MostSignificantSetBitIndex(uptr x) {
423   CHECK_NE(x, 0U);
424   unsigned long up;  // NOLINT
425 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
426 # ifdef _WIN64
427   up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
428 # else
429   up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
430 # endif
431 #elif defined(_WIN64)
432   _BitScanReverse64(&up, x);
433 #else
434   _BitScanReverse(&up, x);
435 #endif
436   return up;
437 }
438
439 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
440   CHECK_NE(x, 0U);
441   unsigned long up;  // NOLINT
442 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
443 # ifdef _WIN64
444   up = __builtin_ctzll(x);
445 # else
446   up = __builtin_ctzl(x);
447 # endif
448 #elif defined(_WIN64)
449   _BitScanForward64(&up, x);
450 #else
451   _BitScanForward(&up, x);
452 #endif
453   return up;
454 }
455
456 INLINE bool IsPowerOfTwo(uptr x) {
457   return (x & (x - 1)) == 0;
458 }
459
460 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
461   CHECK(size);
462   if (IsPowerOfTwo(size)) return size;
463
464   uptr up = MostSignificantSetBitIndex(size);
465   CHECK_LT(size, (1ULL << (up + 1)));
466   CHECK_GT(size, (1ULL << up));
467   return 1ULL << (up + 1);
468 }
469
470 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
471   RAW_CHECK(IsPowerOfTwo(boundary));
472   return (size + boundary - 1) & ~(boundary - 1);
473 }
474
475 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
476   return x & ~(boundary - 1);
477 }
478
479 INLINE bool IsAligned(uptr a, uptr alignment) {
480   return (a & (alignment - 1)) == 0;
481 }
482
483 INLINE uptr Log2(uptr x) {
484   CHECK(IsPowerOfTwo(x));
485   return LeastSignificantSetBitIndex(x);
486 }
487
488 // Don't use std::min, std::max or std::swap, to minimize dependency
489 // on libstdc++.
490 template<class T> T Min(T a, T b) { return a < b ? a : b; }
491 template<class T> T Max(T a, T b) { return a > b ? a : b; }
492 template<class T> void Swap(T& a, T& b) {
493   T tmp = a;
494   a = b;
495   b = tmp;
496 }
497
498 // Char handling
499 INLINE bool IsSpace(int c) {
500   return (c == ' ') || (c == '\n') || (c == '\t') ||
501          (c == '\f') || (c == '\r') || (c == '\v');
502 }
503 INLINE bool IsDigit(int c) {
504   return (c >= '0') && (c <= '9');
505 }
506 INLINE int ToLower(int c) {
507   return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
508 }
509
510 // A low-level vector based on mmap. May incur a significant memory overhead for
511 // small vectors.
512 // WARNING: The current implementation supports only POD types.
513 template<typename T>
514 class InternalMmapVectorNoCtor {
515  public:
516   void Initialize(uptr initial_capacity) {
517     capacity_ = Max(initial_capacity, (uptr)1);
518     size_ = 0;
519     data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
520   }
521   void Destroy() {
522     UnmapOrDie(data_, capacity_ * sizeof(T));
523   }
524   T &operator[](uptr i) {
525     CHECK_LT(i, size_);
526     return data_[i];
527   }
528   const T &operator[](uptr i) const {
529     CHECK_LT(i, size_);
530     return data_[i];
531   }
532   void push_back(const T &element) {
533     CHECK_LE(size_, capacity_);
534     if (size_ == capacity_) {
535       uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
536       Resize(new_capacity);
537     }
538     internal_memcpy(&data_[size_++], &element, sizeof(T));
539   }
540   T &back() {
541     CHECK_GT(size_, 0);
542     return data_[size_ - 1];
543   }
544   void pop_back() {
545     CHECK_GT(size_, 0);
546     size_--;
547   }
548   uptr size() const {
549     return size_;
550   }
551   const T *data() const {
552     return data_;
553   }
554   T *data() {
555     return data_;
556   }
557   uptr capacity() const {
558     return capacity_;
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 template<class Container, class Value, class Compare>
645 uptr InternalBinarySearch(const Container &v, uptr first, uptr last,
646                           const Value &val, Compare comp) {
647   uptr not_found = last + 1;
648   while (last >= first) {
649     uptr mid = (first + last) / 2;
650     if (comp(v[mid], val))
651       first = mid + 1;
652     else if (comp(val, v[mid]))
653       last = mid - 1;
654     else
655       return mid;
656   }
657   return not_found;
658 }
659
660 // Represents a binary loaded into virtual memory (e.g. this can be an
661 // executable or a shared object).
662 class LoadedModule {
663  public:
664   LoadedModule() : full_name_(nullptr), base_address_(0) { ranges_.clear(); }
665   void set(const char *module_name, uptr base_address);
666   void clear();
667   void addAddressRange(uptr beg, uptr end, bool executable);
668   bool containsAddress(uptr address) const;
669
670   const char *full_name() const { return full_name_; }
671   uptr base_address() const { return base_address_; }
672
673   struct AddressRange {
674     AddressRange *next;
675     uptr beg;
676     uptr end;
677     bool executable;
678
679     AddressRange(uptr beg, uptr end, bool executable)
680         : next(nullptr), beg(beg), end(end), executable(executable) {}
681   };
682
683   const IntrusiveList<AddressRange> &ranges() const { return ranges_; }
684
685  private:
686   char *full_name_;  // Owned.
687   uptr base_address_;
688   IntrusiveList<AddressRange> ranges_;
689 };
690
691 // List of LoadedModules. OS-dependent implementation is responsible for
692 // filling this information.
693 class ListOfModules {
694  public:
695   ListOfModules() : modules_(kInitialCapacity) {}
696   ~ListOfModules() { clear(); }
697   void init();
698   const LoadedModule *begin() const { return modules_.begin(); }
699   LoadedModule *begin() { return modules_.begin(); }
700   const LoadedModule *end() const { return modules_.end(); }
701   LoadedModule *end() { return modules_.end(); }
702   uptr size() const { return modules_.size(); }
703   const LoadedModule &operator[](uptr i) const {
704     CHECK_LT(i, modules_.size());
705     return modules_[i];
706   }
707
708  private:
709   void clear() {
710     for (auto &module : modules_) module.clear();
711     modules_.clear();
712   }
713
714   InternalMmapVector<LoadedModule> modules_;
715   // We rarely have more than 16K loaded modules.
716   static const uptr kInitialCapacity = 1 << 14;
717 };
718
719 // Callback type for iterating over a set of memory ranges.
720 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
721
722 enum AndroidApiLevel {
723   ANDROID_NOT_ANDROID = 0,
724   ANDROID_KITKAT = 19,
725   ANDROID_LOLLIPOP_MR1 = 22,
726   ANDROID_POST_LOLLIPOP = 23
727 };
728
729 void WriteToSyslog(const char *buffer);
730
731 #if SANITIZER_MAC
732 void LogFullErrorReport(const char *buffer);
733 #else
734 INLINE void LogFullErrorReport(const char *buffer) {}
735 #endif
736
737 #if SANITIZER_LINUX || SANITIZER_MAC
738 void WriteOneLineToSyslog(const char *s);
739 void LogMessageOnPrintf(const char *str);
740 #else
741 INLINE void WriteOneLineToSyslog(const char *s) {}
742 INLINE void LogMessageOnPrintf(const char *str) {}
743 #endif
744
745 #if SANITIZER_LINUX
746 // Initialize Android logging. Any writes before this are silently lost.
747 void AndroidLogInit();
748 #else
749 INLINE void AndroidLogInit() {}
750 #endif
751
752 #if SANITIZER_ANDROID
753 void SanitizerInitializeUnwinder();
754 AndroidApiLevel AndroidGetApiLevel();
755 #else
756 INLINE void AndroidLogWrite(const char *buffer_unused) {}
757 INLINE void SanitizerInitializeUnwinder() {}
758 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
759 #endif
760
761 INLINE uptr GetPthreadDestructorIterations() {
762 #if SANITIZER_ANDROID
763   return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
764 #elif SANITIZER_POSIX
765   return 4;
766 #else
767 // Unused on Windows.
768   return 0;
769 #endif
770 }
771
772 void *internal_start_thread(void(*func)(void*), void *arg);
773 void internal_join_thread(void *th);
774 void MaybeStartBackgroudThread();
775
776 // Make the compiler think that something is going on there.
777 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
778 // compiler from recognising it and turning it into an actual call to
779 // memset/memcpy/etc.
780 static inline void SanitizerBreakOptimization(void *arg) {
781 #if defined(_MSC_VER) && !defined(__clang__)
782   _ReadWriteBarrier();
783 #else
784   __asm__ __volatile__("" : : "r" (arg) : "memory");
785 #endif
786 }
787
788 struct SignalContext {
789   void *context;
790   uptr addr;
791   uptr pc;
792   uptr sp;
793   uptr bp;
794   bool is_memory_access;
795
796   enum WriteFlag { UNKNOWN, READ, WRITE } write_flag;
797
798   SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp,
799                 bool is_memory_access, WriteFlag write_flag)
800       : context(context),
801         addr(addr),
802         pc(pc),
803         sp(sp),
804         bp(bp),
805         is_memory_access(is_memory_access),
806         write_flag(write_flag) {}
807
808   // Creates signal context in a platform-specific manner.
809   static SignalContext Create(void *siginfo, void *context);
810
811   // Returns true if the "context" indicates a memory write.
812   static WriteFlag GetWriteFlag(void *context);
813 };
814
815 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
816
817 const char *GetRuntimeOptions(const char *env_option, const char *filename,
818                               int *mmaped);
819
820 void MaybeReexec();
821
822 template <typename Fn>
823 class RunOnDestruction {
824  public:
825   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
826   ~RunOnDestruction() { fn_(); }
827
828  private:
829   Fn fn_;
830 };
831
832 // A simple scope guard. Usage:
833 // auto cleanup = at_scope_exit([]{ do_cleanup; });
834 template <typename Fn>
835 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
836   return RunOnDestruction<Fn>(fn);
837 }
838
839 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
840 // if a process uses virtual memory over 4TB (as many sanitizers like
841 // to do).  This function will abort the process if running on a kernel
842 // that looks vulnerable.
843 #if SANITIZER_LINUX && SANITIZER_S390_64
844 void AvoidCVE_2016_2143();
845 #else
846 INLINE void AvoidCVE_2016_2143() {}
847 #endif
848
849 struct StackDepotStats {
850   uptr n_uniq_ids;
851   uptr allocated;
852 };
853
854 }  // namespace __sanitizer
855
856 inline void *operator new(__sanitizer::operator_new_size_type size,
857                           __sanitizer::LowLevelAllocator &alloc) {
858   return alloc.Allocate(size);
859 }
860
861 #endif  // SANITIZER_COMMON_H