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