sanitizer_common.h revision 1dcd1d9d1c86ab9b728386d261fbebe00b32e097
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
23namespace __sanitizer {
24struct StackTrace;
25
26// Constants.
27const uptr kWordSize = SANITIZER_WORDSIZE / 8;
28const uptr kWordSizeInBits = 8 * kWordSize;
29
30#if defined(__powerpc__) || defined(__powerpc64__)
31const uptr kCacheLineSize = 128;
32#else
33const uptr kCacheLineSize = 64;
34#endif
35
36const uptr kMaxPathLength = 512;
37
38extern const char *SanitizerToolName;  // Can be changed by the tool.
39extern uptr SanitizerVerbosity;
40
41uptr GetPageSize();
42uptr GetPageSizeCached();
43uptr GetMmapGranularity();
44uptr GetMaxVirtualAddress();
45// Threads
46uptr GetTid();
47uptr GetThreadSelf();
48void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
49                                uptr *stack_bottom);
50void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
51                          uptr *tls_addr, uptr *tls_size);
52
53// Memory management
54void *MmapOrDie(uptr size, const char *mem_type);
55void UnmapOrDie(void *addr, uptr size);
56void *MmapFixedNoReserve(uptr fixed_addr, uptr size);
57void *MmapFixedOrDie(uptr fixed_addr, uptr size);
58void *Mprotect(uptr fixed_addr, uptr size);
59// Map aligned chunk of address space; size and alignment are powers of two.
60void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
61// Used to check if we can map shadow memory to a fixed location.
62bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
63void FlushUnneededShadowMemory(uptr addr, uptr size);
64
65// InternalScopedBuffer can be used instead of large stack arrays to
66// keep frame size low.
67// FIXME: use InternalAlloc instead of MmapOrDie once
68// InternalAlloc is made libc-free.
69template<typename T>
70class InternalScopedBuffer {
71 public:
72  explicit InternalScopedBuffer(uptr cnt) {
73    cnt_ = cnt;
74    ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
75  }
76  ~InternalScopedBuffer() {
77    UnmapOrDie(ptr_, cnt_ * sizeof(T));
78  }
79  T &operator[](uptr i) { return ptr_[i]; }
80  T *data() { return ptr_; }
81  uptr size() { return cnt_ * sizeof(T); }
82
83 private:
84  T *ptr_;
85  uptr cnt_;
86  // Disallow evil constructors.
87  InternalScopedBuffer(const InternalScopedBuffer&);
88  void operator=(const InternalScopedBuffer&);
89};
90
91// Simple low-level (mmap-based) allocator for internal use. Doesn't have
92// constructor, so all instances of LowLevelAllocator should be
93// linker initialized.
94class LowLevelAllocator {
95 public:
96  // Requires an external lock.
97  void *Allocate(uptr size);
98 private:
99  char *allocated_end_;
100  char *allocated_current_;
101};
102typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
103// Allows to register tool-specific callbacks for LowLevelAllocator.
104// Passing NULL removes the callback.
105void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
106
107// IO
108void RawWrite(const char *buffer);
109bool PrintsToTty();
110void Printf(const char *format, ...);
111void Report(const char *format, ...);
112void SetPrintfAndReportCallback(void (*callback)(const char *));
113// Can be used to prevent mixing error reports from different sanitizers.
114extern StaticSpinMutex CommonSanitizerReportMutex;
115void MaybeOpenReportFile();
116extern fd_t report_fd;
117
118uptr OpenFile(const char *filename, bool write);
119// Opens the file 'file_name" and reads up to 'max_len' bytes.
120// The resulting buffer is mmaped and stored in '*buff'.
121// The size of the mmaped region is stored in '*buff_size',
122// Returns the number of read bytes or 0 if file can not be opened.
123uptr ReadFileToBuffer(const char *file_name, char **buff,
124                      uptr *buff_size, uptr max_len);
125// Maps given file to virtual memory, and returns pointer to it
126// (or NULL if the mapping failes). Stores the size of mmaped region
127// in '*buff_size'.
128void *MapFileToMemory(const char *file_name, uptr *buff_size);
129
130// OS
131void DisableCoreDumper();
132void DumpProcessMap();
133bool FileExists(const char *filename);
134const char *GetEnv(const char *name);
135bool SetEnv(const char *name, const char *value);
136const char *GetPwd();
137char *FindPathToBinary(const char *name);
138u32 GetUid();
139void ReExec();
140bool StackSizeIsUnlimited();
141void SetStackSizeLimitInBytes(uptr limit);
142void PrepareForSandboxing();
143
144void InitTlsSize();
145uptr GetTlsSize();
146
147// Other
148void SleepForSeconds(int seconds);
149void SleepForMillis(int millis);
150u64 NanoTime();
151int Atexit(void (*function)(void));
152void SortArray(uptr *array, uptr size);
153
154// Exit
155void NORETURN Abort();
156void NORETURN Die();
157void NORETURN
158CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
159
160// Set the name of the current thread to 'name', return true on succees.
161// The name may be truncated to a system-dependent limit.
162bool SanitizerSetThreadName(const char *name);
163// Get the name of the current thread (no more than max_len bytes),
164// return true on succees. name should have space for at least max_len+1 bytes.
165bool SanitizerGetThreadName(char *name, int max_len);
166
167// Specific tools may override behavior of "Die" and "CheckFailed" functions
168// to do tool-specific job.
169typedef void (*DieCallbackType)(void);
170void SetDieCallback(DieCallbackType);
171DieCallbackType GetDieCallback();
172typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
173                                       u64, u64);
174void SetCheckFailedCallback(CheckFailedCallbackType callback);
175
176// Construct a one-line string like
177//  SanitizerToolName: error_type file:line function
178// and call __sanitizer_report_error_summary on it.
179void ReportErrorSummary(const char *error_type, const char *file,
180                        int line, const char *function);
181
182// Math
183#if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
184extern "C" {
185unsigned char _BitScanForward(unsigned long *index, unsigned long mask);  // NOLINT
186unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);  // NOLINT
187#if defined(_WIN64)
188unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask);  // NOLINT
189unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask);  // NOLINT
190#endif
191}
192#endif
193
194INLINE uptr MostSignificantSetBitIndex(uptr x) {
195  CHECK_NE(x, 0U);
196  unsigned long up;  // NOLINT
197#if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
198  up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
199#elif defined(_WIN64)
200  _BitScanReverse64(&up, x);
201#else
202  _BitScanReverse(&up, x);
203#endif
204  return up;
205}
206
207INLINE bool IsPowerOfTwo(uptr x) {
208  return (x & (x - 1)) == 0;
209}
210
211INLINE uptr RoundUpToPowerOfTwo(uptr size) {
212  CHECK(size);
213  if (IsPowerOfTwo(size)) return size;
214
215  uptr up = MostSignificantSetBitIndex(size);
216  CHECK(size < (1ULL << (up + 1)));
217  CHECK(size > (1ULL << up));
218  return 1UL << (up + 1);
219}
220
221INLINE uptr RoundUpTo(uptr size, uptr boundary) {
222  CHECK(IsPowerOfTwo(boundary));
223  return (size + boundary - 1) & ~(boundary - 1);
224}
225
226INLINE uptr RoundDownTo(uptr x, uptr boundary) {
227  return x & ~(boundary - 1);
228}
229
230INLINE bool IsAligned(uptr a, uptr alignment) {
231  return (a & (alignment - 1)) == 0;
232}
233
234INLINE uptr Log2(uptr x) {
235  CHECK(IsPowerOfTwo(x));
236#if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
237  return __builtin_ctzl(x);
238#elif defined(_WIN64)
239  unsigned long ret;  // NOLINT
240  _BitScanForward64(&ret, x);
241  return ret;
242#else
243  unsigned long ret;  // NOLINT
244  _BitScanForward(&ret, x);
245  return ret;
246#endif
247}
248
249// Don't use std::min, std::max or std::swap, to minimize dependency
250// on libstdc++.
251template<class T> T Min(T a, T b) { return a < b ? a : b; }
252template<class T> T Max(T a, T b) { return a > b ? a : b; }
253template<class T> void Swap(T& a, T& b) {
254  T tmp = a;
255  a = b;
256  b = tmp;
257}
258
259// Char handling
260INLINE bool IsSpace(int c) {
261  return (c == ' ') || (c == '\n') || (c == '\t') ||
262         (c == '\f') || (c == '\r') || (c == '\v');
263}
264INLINE bool IsDigit(int c) {
265  return (c >= '0') && (c <= '9');
266}
267INLINE int ToLower(int c) {
268  return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
269}
270
271#if SANITIZER_WORDSIZE == 64
272# define FIRST_32_SECOND_64(a, b) (b)
273#else
274# define FIRST_32_SECOND_64(a, b) (a)
275#endif
276
277// A low-level vector based on mmap. May incur a significant memory overhead for
278// small vectors.
279// WARNING: The current implementation supports only POD types.
280template<typename T>
281class InternalMmapVector {
282 public:
283  explicit InternalMmapVector(uptr initial_capacity) {
284    CHECK_GT(initial_capacity, 0);
285    capacity_ = initial_capacity;
286    size_ = 0;
287    data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVector");
288  }
289  ~InternalMmapVector() {
290    UnmapOrDie(data_, capacity_ * sizeof(T));
291  }
292  T &operator[](uptr i) {
293    CHECK_LT(i, size_);
294    return data_[i];
295  }
296  const T &operator[](uptr i) const {
297    CHECK_LT(i, size_);
298    return data_[i];
299  }
300  void push_back(const T &element) {
301    CHECK_LE(size_, capacity_);
302    if (size_ == capacity_) {
303      uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
304      Resize(new_capacity);
305    }
306    data_[size_++] = element;
307  }
308  T &back() {
309    CHECK_GT(size_, 0);
310    return data_[size_ - 1];
311  }
312  void pop_back() {
313    CHECK_GT(size_, 0);
314    size_--;
315  }
316  uptr size() const {
317    return size_;
318  }
319  const T *data() const {
320    return data_;
321  }
322  uptr capacity() const {
323    return capacity_;
324  }
325
326 private:
327  void Resize(uptr new_capacity) {
328    CHECK_GT(new_capacity, 0);
329    CHECK_LE(size_, new_capacity);
330    T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
331                                 "InternalMmapVector");
332    internal_memcpy(new_data, data_, size_ * sizeof(T));
333    T *old_data = data_;
334    data_ = new_data;
335    UnmapOrDie(old_data, capacity_ * sizeof(T));
336    capacity_ = new_capacity;
337  }
338  // Disallow evil constructors.
339  InternalMmapVector(const InternalMmapVector&);
340  void operator=(const InternalMmapVector&);
341
342  T *data_;
343  uptr capacity_;
344  uptr size_;
345};
346
347// HeapSort for arrays and InternalMmapVector.
348template<class Container, class Compare>
349void InternalSort(Container *v, uptr size, Compare comp) {
350  if (size < 2)
351    return;
352  // Stage 1: insert elements to the heap.
353  for (uptr i = 1; i < size; i++) {
354    uptr j, p;
355    for (j = i; j > 0; j = p) {
356      p = (j - 1) / 2;
357      if (comp((*v)[p], (*v)[j]))
358        Swap((*v)[j], (*v)[p]);
359      else
360        break;
361    }
362  }
363  // Stage 2: swap largest element with the last one,
364  // and sink the new top.
365  for (uptr i = size - 1; i > 0; i--) {
366    Swap((*v)[0], (*v)[i]);
367    uptr j, max_ind;
368    for (j = 0; j < i; j = max_ind) {
369      uptr left = 2 * j + 1;
370      uptr right = 2 * j + 2;
371      max_ind = j;
372      if (left < i && comp((*v)[max_ind], (*v)[left]))
373        max_ind = left;
374      if (right < i && comp((*v)[max_ind], (*v)[right]))
375        max_ind = right;
376      if (max_ind != j)
377        Swap((*v)[j], (*v)[max_ind]);
378      else
379        break;
380    }
381  }
382}
383
384template<class Container, class Value, class Compare>
385uptr InternalBinarySearch(const Container &v, uptr first, uptr last,
386                          const Value &val, Compare comp) {
387  uptr not_found = last + 1;
388  while (last >= first) {
389    uptr mid = (first + last) / 2;
390    if (comp(v[mid], val))
391      first = mid + 1;
392    else if (comp(val, v[mid]))
393      last = mid - 1;
394    else
395      return mid;
396  }
397  return not_found;
398}
399
400}  // namespace __sanitizer
401
402#endif  // SANITIZER_COMMON_H
403