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