]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_common.h
Update compiler-rt to trunk r224034. This brings a number of new
[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 AddressSanitizer and ThreadSanitizer
11 // run-time libraries.
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_internal_defs.h"
20 #include "sanitizer_libc.h"
21 #include "sanitizer_mutex.h"
22 #include "sanitizer_flags.h"
23
24 namespace __sanitizer {
25 struct StackTrace;
26
27 // Constants.
28 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
29 const uptr kWordSizeInBits = 8 * kWordSize;
30
31 #if defined(__powerpc__) || defined(__powerpc64__)
32   const uptr kCacheLineSize = 128;
33 #else
34   const uptr kCacheLineSize = 64;
35 #endif
36
37 const uptr kMaxPathLength = 4096;
38
39 const uptr kMaxThreadStackSize = 1 << 30;  // 1Gb
40
41 extern const char *SanitizerToolName;  // Can be changed by the tool.
42
43 uptr GetPageSize();
44 uptr GetPageSizeCached();
45 uptr GetMmapGranularity();
46 uptr GetMaxVirtualAddress();
47 // Threads
48 uptr GetTid();
49 uptr GetThreadSelf();
50 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
51                                 uptr *stack_bottom);
52 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
53                           uptr *tls_addr, uptr *tls_size);
54
55 // Memory management
56 void *MmapOrDie(uptr size, const char *mem_type);
57 void UnmapOrDie(void *addr, uptr size);
58 void *MmapFixedNoReserve(uptr fixed_addr, uptr size);
59 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
60 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
61 void *Mprotect(uptr fixed_addr, uptr size);
62 // Map aligned chunk of address space; size and alignment are powers of two.
63 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
64 // Used to check if we can map shadow memory to a fixed location.
65 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
66 void FlushUnneededShadowMemory(uptr addr, uptr size);
67 void IncreaseTotalMmap(uptr size);
68 void DecreaseTotalMmap(uptr size);
69 uptr GetRSS();
70
71 // InternalScopedBuffer can be used instead of large stack arrays to
72 // keep frame size low.
73 // FIXME: use InternalAlloc instead of MmapOrDie once
74 // InternalAlloc is made libc-free.
75 template<typename T>
76 class InternalScopedBuffer {
77  public:
78   explicit InternalScopedBuffer(uptr cnt) {
79     cnt_ = cnt;
80     ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
81   }
82   ~InternalScopedBuffer() {
83     UnmapOrDie(ptr_, cnt_ * sizeof(T));
84   }
85   T &operator[](uptr i) { return ptr_[i]; }
86   T *data() { return ptr_; }
87   uptr size() { return cnt_ * sizeof(T); }
88
89  private:
90   T *ptr_;
91   uptr cnt_;
92   // Disallow evil constructors.
93   InternalScopedBuffer(const InternalScopedBuffer&);
94   void operator=(const InternalScopedBuffer&);
95 };
96
97 class InternalScopedString : public InternalScopedBuffer<char> {
98  public:
99   explicit InternalScopedString(uptr max_length)
100       : InternalScopedBuffer<char>(max_length), length_(0) {
101     (*this)[0] = '\0';
102   }
103   uptr length() { return length_; }
104   void clear() {
105     (*this)[0] = '\0';
106     length_ = 0;
107   }
108   void append(const char *format, ...);
109
110  private:
111   uptr length_;
112 };
113
114 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
115 // constructor, so all instances of LowLevelAllocator should be
116 // linker initialized.
117 class LowLevelAllocator {
118  public:
119   // Requires an external lock.
120   void *Allocate(uptr size);
121  private:
122   char *allocated_end_;
123   char *allocated_current_;
124 };
125 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
126 // Allows to register tool-specific callbacks for LowLevelAllocator.
127 // Passing NULL removes the callback.
128 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
129
130 // IO
131 void RawWrite(const char *buffer);
132 bool ColorizeReports();
133 void Printf(const char *format, ...);
134 void Report(const char *format, ...);
135 void SetPrintfAndReportCallback(void (*callback)(const char *));
136 #define VReport(level, ...)                                              \
137   do {                                                                   \
138     if ((uptr)common_flags()->verbosity >= (level)) Report(__VA_ARGS__); \
139   } while (0)
140 #define VPrintf(level, ...)                                              \
141   do {                                                                   \
142     if ((uptr)common_flags()->verbosity >= (level)) Printf(__VA_ARGS__); \
143   } while (0)
144
145 // Can be used to prevent mixing error reports from different sanitizers.
146 extern StaticSpinMutex CommonSanitizerReportMutex;
147
148 struct ReportFile {
149   void Write(const char *buffer, uptr length);
150   bool PrintsToTty();
151   void SetReportPath(const char *path);
152
153   // Don't use fields directly. They are only declared public to allow
154   // aggregate initialization.
155
156   // Protects fields below.
157   StaticSpinMutex *mu;
158   // Opened file descriptor. Defaults to stderr. It may be equal to
159   // kInvalidFd, in which case new file will be opened when necessary.
160   fd_t fd;
161   // Path prefix of report file, set via __sanitizer_set_report_path.
162   char path_prefix[kMaxPathLength];
163   // Full path to report, obtained as <path_prefix>.PID
164   char full_path[kMaxPathLength];
165   // PID of the process that opened fd. If a fork() occurs,
166   // the PID of child will be different from fd_pid.
167   uptr fd_pid;
168
169  private:
170   void ReopenIfNecessary();
171 };
172 extern ReportFile report_file;
173
174 extern uptr stoptheworld_tracer_pid;
175 extern uptr stoptheworld_tracer_ppid;
176
177 uptr OpenFile(const char *filename, bool write);
178 // Opens the file 'file_name" and reads up to 'max_len' bytes.
179 // The resulting buffer is mmaped and stored in '*buff'.
180 // The size of the mmaped region is stored in '*buff_size',
181 // Returns the number of read bytes or 0 if file can not be opened.
182 uptr ReadFileToBuffer(const char *file_name, char **buff,
183                       uptr *buff_size, uptr max_len);
184 // Maps given file to virtual memory, and returns pointer to it
185 // (or NULL if the mapping failes). Stores the size of mmaped region
186 // in '*buff_size'.
187 void *MapFileToMemory(const char *file_name, uptr *buff_size);
188 void *MapWritableFileToMemory(void *addr, uptr size, uptr fd, uptr offset);
189
190 bool IsAccessibleMemoryRange(uptr beg, uptr size);
191
192 // Error report formatting.
193 const char *StripPathPrefix(const char *filepath,
194                             const char *strip_file_prefix);
195 // Strip the directories from the module name.
196 const char *StripModuleName(const char *module);
197
198 // OS
199 void DisableCoreDumperIfNecessary();
200 void DumpProcessMap();
201 bool FileExists(const char *filename);
202 const char *GetEnv(const char *name);
203 bool SetEnv(const char *name, const char *value);
204 const char *GetPwd();
205 char *FindPathToBinary(const char *name);
206 u32 GetUid();
207 void ReExec();
208 bool StackSizeIsUnlimited();
209 void SetStackSizeLimitInBytes(uptr limit);
210 bool AddressSpaceIsUnlimited();
211 void SetAddressSpaceUnlimited();
212 void AdjustStackSize(void *attr);
213 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args);
214 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args);
215 void SetSandboxingCallback(void (*f)());
216
217 void CovUpdateMapping(uptr caller_pc = 0);
218 void CovBeforeFork();
219 void CovAfterFork(int child_pid);
220
221 void InitTlsSize();
222 uptr GetTlsSize();
223
224 // Other
225 void SleepForSeconds(int seconds);
226 void SleepForMillis(int millis);
227 u64 NanoTime();
228 int Atexit(void (*function)(void));
229 void SortArray(uptr *array, uptr size);
230
231 // Exit
232 void NORETURN Abort();
233 void NORETURN Die();
234 void NORETURN
235 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
236
237 // Set the name of the current thread to 'name', return true on succees.
238 // The name may be truncated to a system-dependent limit.
239 bool SanitizerSetThreadName(const char *name);
240 // Get the name of the current thread (no more than max_len bytes),
241 // return true on succees. name should have space for at least max_len+1 bytes.
242 bool SanitizerGetThreadName(char *name, int max_len);
243
244 // Specific tools may override behavior of "Die" and "CheckFailed" functions
245 // to do tool-specific job.
246 typedef void (*DieCallbackType)(void);
247 void SetDieCallback(DieCallbackType);
248 DieCallbackType GetDieCallback();
249 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
250                                        u64, u64);
251 void SetCheckFailedCallback(CheckFailedCallbackType callback);
252
253 // Functions related to signal handling.
254 typedef void (*SignalHandlerType)(int, void *, void *);
255 bool IsDeadlySignal(int signum);
256 void InstallDeadlySignalHandlers(SignalHandlerType handler);
257 // Alternative signal stack (POSIX-only).
258 void SetAlternateSignalStack();
259 void UnsetAlternateSignalStack();
260
261 // We don't want a summary too long.
262 const int kMaxSummaryLength = 1024;
263 // Construct a one-line string:
264 //   SUMMARY: SanitizerToolName: error_message
265 // and pass it to __sanitizer_report_error_summary.
266 void ReportErrorSummary(const char *error_message);
267 // Same as above, but construct error_message as:
268 //   error_type file:line function
269 void ReportErrorSummary(const char *error_type, const char *file,
270                         int line, const char *function);
271 void ReportErrorSummary(const char *error_type, StackTrace *trace);
272
273 // Math
274 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
275 extern "C" {
276 unsigned char _BitScanForward(unsigned long *index, unsigned long mask);  // NOLINT
277 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);  // NOLINT
278 #if defined(_WIN64)
279 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask);  // NOLINT
280 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask);  // NOLINT
281 #endif
282 }
283 #endif
284
285 INLINE uptr MostSignificantSetBitIndex(uptr x) {
286   CHECK_NE(x, 0U);
287   unsigned long up;  // NOLINT
288 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
289   up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
290 #elif defined(_WIN64)
291   _BitScanReverse64(&up, x);
292 #else
293   _BitScanReverse(&up, x);
294 #endif
295   return up;
296 }
297
298 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
299   CHECK_NE(x, 0U);
300   unsigned long up;  // NOLINT
301 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
302   up = __builtin_ctzl(x);
303 #elif defined(_WIN64)
304   _BitScanForward64(&up, x);
305 #else
306   _BitScanForward(&up, x);
307 #endif
308   return up;
309 }
310
311 INLINE bool IsPowerOfTwo(uptr x) {
312   return (x & (x - 1)) == 0;
313 }
314
315 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
316   CHECK(size);
317   if (IsPowerOfTwo(size)) return size;
318
319   uptr up = MostSignificantSetBitIndex(size);
320   CHECK(size < (1ULL << (up + 1)));
321   CHECK(size > (1ULL << up));
322   return 1UL << (up + 1);
323 }
324
325 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
326   CHECK(IsPowerOfTwo(boundary));
327   return (size + boundary - 1) & ~(boundary - 1);
328 }
329
330 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
331   return x & ~(boundary - 1);
332 }
333
334 INLINE bool IsAligned(uptr a, uptr alignment) {
335   return (a & (alignment - 1)) == 0;
336 }
337
338 INLINE uptr Log2(uptr x) {
339   CHECK(IsPowerOfTwo(x));
340 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
341   return __builtin_ctzl(x);
342 #elif defined(_WIN64)
343   unsigned long ret;  // NOLINT
344   _BitScanForward64(&ret, x);
345   return ret;
346 #else
347   unsigned long ret;  // NOLINT
348   _BitScanForward(&ret, x);
349   return ret;
350 #endif
351 }
352
353 // Don't use std::min, std::max or std::swap, to minimize dependency
354 // on libstdc++.
355 template<class T> T Min(T a, T b) { return a < b ? a : b; }
356 template<class T> T Max(T a, T b) { return a > b ? a : b; }
357 template<class T> void Swap(T& a, T& b) {
358   T tmp = a;
359   a = b;
360   b = tmp;
361 }
362
363 // Char handling
364 INLINE bool IsSpace(int c) {
365   return (c == ' ') || (c == '\n') || (c == '\t') ||
366          (c == '\f') || (c == '\r') || (c == '\v');
367 }
368 INLINE bool IsDigit(int c) {
369   return (c >= '0') && (c <= '9');
370 }
371 INLINE int ToLower(int c) {
372   return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
373 }
374
375 // A low-level vector based on mmap. May incur a significant memory overhead for
376 // small vectors.
377 // WARNING: The current implementation supports only POD types.
378 template<typename T>
379 class InternalMmapVector {
380  public:
381   explicit InternalMmapVector(uptr initial_capacity) {
382     capacity_ = Max(initial_capacity, (uptr)1);
383     size_ = 0;
384     data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVector");
385   }
386   ~InternalMmapVector() {
387     UnmapOrDie(data_, capacity_ * sizeof(T));
388   }
389   T &operator[](uptr i) {
390     CHECK_LT(i, size_);
391     return data_[i];
392   }
393   const T &operator[](uptr i) const {
394     CHECK_LT(i, size_);
395     return data_[i];
396   }
397   void push_back(const T &element) {
398     CHECK_LE(size_, capacity_);
399     if (size_ == capacity_) {
400       uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
401       Resize(new_capacity);
402     }
403     data_[size_++] = element;
404   }
405   T &back() {
406     CHECK_GT(size_, 0);
407     return data_[size_ - 1];
408   }
409   void pop_back() {
410     CHECK_GT(size_, 0);
411     size_--;
412   }
413   uptr size() const {
414     return size_;
415   }
416   const T *data() const {
417     return data_;
418   }
419   uptr capacity() const {
420     return capacity_;
421   }
422
423   void clear() { size_ = 0; }
424
425  private:
426   void Resize(uptr new_capacity) {
427     CHECK_GT(new_capacity, 0);
428     CHECK_LE(size_, new_capacity);
429     T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
430                                  "InternalMmapVector");
431     internal_memcpy(new_data, data_, size_ * sizeof(T));
432     T *old_data = data_;
433     data_ = new_data;
434     UnmapOrDie(old_data, capacity_ * sizeof(T));
435     capacity_ = new_capacity;
436   }
437   // Disallow evil constructors.
438   InternalMmapVector(const InternalMmapVector&);
439   void operator=(const InternalMmapVector&);
440
441   T *data_;
442   uptr capacity_;
443   uptr size_;
444 };
445
446 // HeapSort for arrays and InternalMmapVector.
447 template<class Container, class Compare>
448 void InternalSort(Container *v, uptr size, Compare comp) {
449   if (size < 2)
450     return;
451   // Stage 1: insert elements to the heap.
452   for (uptr i = 1; i < size; i++) {
453     uptr j, p;
454     for (j = i; j > 0; j = p) {
455       p = (j - 1) / 2;
456       if (comp((*v)[p], (*v)[j]))
457         Swap((*v)[j], (*v)[p]);
458       else
459         break;
460     }
461   }
462   // Stage 2: swap largest element with the last one,
463   // and sink the new top.
464   for (uptr i = size - 1; i > 0; i--) {
465     Swap((*v)[0], (*v)[i]);
466     uptr j, max_ind;
467     for (j = 0; j < i; j = max_ind) {
468       uptr left = 2 * j + 1;
469       uptr right = 2 * j + 2;
470       max_ind = j;
471       if (left < i && comp((*v)[max_ind], (*v)[left]))
472         max_ind = left;
473       if (right < i && comp((*v)[max_ind], (*v)[right]))
474         max_ind = right;
475       if (max_ind != j)
476         Swap((*v)[j], (*v)[max_ind]);
477       else
478         break;
479     }
480   }
481 }
482
483 template<class Container, class Value, class Compare>
484 uptr InternalBinarySearch(const Container &v, uptr first, uptr last,
485                           const Value &val, Compare comp) {
486   uptr not_found = last + 1;
487   while (last >= first) {
488     uptr mid = (first + last) / 2;
489     if (comp(v[mid], val))
490       first = mid + 1;
491     else if (comp(val, v[mid]))
492       last = mid - 1;
493     else
494       return mid;
495   }
496   return not_found;
497 }
498
499 // Represents a binary loaded into virtual memory (e.g. this can be an
500 // executable or a shared object).
501 class LoadedModule {
502  public:
503   LoadedModule(const char *module_name, uptr base_address);
504   void addAddressRange(uptr beg, uptr end, bool executable);
505   bool containsAddress(uptr address) const;
506
507   const char *full_name() const { return full_name_; }
508   uptr base_address() const { return base_address_; }
509
510   uptr n_ranges() const { return n_ranges_; }
511   uptr address_range_start(int i) const { return ranges_[i].beg; }
512   uptr address_range_end(int i) const { return ranges_[i].end; }
513   bool address_range_executable(int i) const { return exec_[i]; }
514
515  private:
516   struct AddressRange {
517     uptr beg;
518     uptr end;
519   };
520   char *full_name_;
521   uptr base_address_;
522   static const uptr kMaxNumberOfAddressRanges = 6;
523   AddressRange ranges_[kMaxNumberOfAddressRanges];
524   bool exec_[kMaxNumberOfAddressRanges];
525   uptr n_ranges_;
526 };
527
528 // OS-dependent function that fills array with descriptions of at most
529 // "max_modules" currently loaded modules. Returns the number of
530 // initialized modules. If filter is nonzero, ignores modules for which
531 // filter(full_name) is false.
532 typedef bool (*string_predicate_t)(const char *);
533 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
534                       string_predicate_t filter);
535
536 #if SANITIZER_POSIX
537 const uptr kPthreadDestructorIterations = 4;
538 #else
539 // Unused on Windows.
540 const uptr kPthreadDestructorIterations = 0;
541 #endif
542
543 // Callback type for iterating over a set of memory ranges.
544 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
545
546 #if SANITIZER_ANDROID
547 // Initialize Android logging. Any writes before this are silently lost.
548 void AndroidLogInit();
549 void AndroidLogWrite(const char *buffer);
550 void GetExtraActivationFlags(char *buf, uptr size);
551 void SanitizerInitializeUnwinder();
552 #else
553 INLINE void AndroidLogInit() {}
554 INLINE void AndroidLogWrite(const char *buffer_unused) {}
555 INLINE void GetExtraActivationFlags(char *buf, uptr size) { *buf = '\0'; }
556 INLINE void SanitizerInitializeUnwinder() {}
557 #endif
558
559 // Make the compiler think that something is going on there.
560 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
561 // compiler from recognising it and turning it into an actual call to
562 // memset/memcpy/etc.
563 static inline void SanitizerBreakOptimization(void *arg) {
564 #if _MSC_VER
565   // FIXME: make sure this is actually enough.
566   __asm;
567 #else
568   __asm__ __volatile__("" : : "r" (arg) : "memory");
569 #endif
570 }
571
572 }  // namespace __sanitizer
573
574 inline void *operator new(__sanitizer::operator_new_size_type size,
575                           __sanitizer::LowLevelAllocator &alloc) {
576   return alloc.Allocate(size);
577 }
578
579 struct StackDepotStats {
580   uptr n_uniq_ids;
581   uptr allocated;
582 };
583
584 #endif  // SANITIZER_COMMON_H