sanitizer_common.h revision a54aec8ca2e372b1a841d605d53cab5e336aeb03
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
21namespace __sanitizer {
22
23// Constants.
24const uptr kWordSize = SANITIZER_WORDSIZE / 8;
25const uptr kWordSizeInBits = 8 * kWordSize;
26
27#if defined(__powerpc__) || defined(__powerpc64__)
28const uptr kCacheLineSize = 128;
29#else
30const uptr kCacheLineSize = 64;
31#endif
32
33uptr GetPageSize();
34uptr GetPageSizeCached();
35uptr GetMmapGranularity();
36// Threads
37int GetPid();
38uptr GetTid();
39uptr GetThreadSelf();
40void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
41                                uptr *stack_bottom);
42
43// Memory management
44void *MmapOrDie(uptr size, const char *mem_type);
45void UnmapOrDie(void *addr, uptr size);
46void *MmapFixedNoReserve(uptr fixed_addr, uptr size);
47void *MmapFixedOrDie(uptr fixed_addr, uptr size);
48void *Mprotect(uptr fixed_addr, uptr size);
49// Map aligned chunk of address space; size and alignment are powers of two.
50void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
51// Used to check if we can map shadow memory to a fixed location.
52bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
53void FlushUnneededShadowMemory(uptr addr, uptr size);
54
55// Internal allocator
56void *InternalAlloc(uptr size);
57void InternalFree(void *p);
58
59// InternalScopedBuffer can be used instead of large stack arrays to
60// keep frame size low.
61// FIXME: use InternalAlloc instead of MmapOrDie once
62// InternalAlloc is made libc-free.
63template<typename T>
64class InternalScopedBuffer {
65 public:
66  explicit InternalScopedBuffer(uptr cnt) {
67    cnt_ = cnt;
68    ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
69  }
70  ~InternalScopedBuffer() {
71    UnmapOrDie(ptr_, cnt_ * sizeof(T));
72  }
73  T &operator[](uptr i) { return ptr_[i]; }
74  T *data() { return ptr_; }
75  uptr size() { return cnt_ * sizeof(T); }
76
77 private:
78  T *ptr_;
79  uptr cnt_;
80  // Disallow evil constructors.
81  InternalScopedBuffer(const InternalScopedBuffer&);
82  void operator=(const InternalScopedBuffer&);
83};
84
85// Simple low-level (mmap-based) allocator for internal use. Doesn't have
86// constructor, so all instances of LowLevelAllocator should be
87// linker initialized.
88class LowLevelAllocator {
89 public:
90  // Requires an external lock.
91  void *Allocate(uptr size);
92 private:
93  char *allocated_end_;
94  char *allocated_current_;
95};
96typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
97// Allows to register tool-specific callbacks for LowLevelAllocator.
98// Passing NULL removes the callback.
99void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
100
101// IO
102void RawWrite(const char *buffer);
103bool PrintsToTty();
104void Printf(const char *format, ...);
105void Report(const char *format, ...);
106void SetPrintfAndReportCallback(void (*callback)(const char *));
107
108// Opens the file 'file_name" and reads up to 'max_len' bytes.
109// The resulting buffer is mmaped and stored in '*buff'.
110// The size of the mmaped region is stored in '*buff_size',
111// Returns the number of read bytes or 0 if file can not be opened.
112uptr ReadFileToBuffer(const char *file_name, char **buff,
113                      uptr *buff_size, uptr max_len);
114// Maps given file to virtual memory, and returns pointer to it
115// (or NULL if the mapping failes). Stores the size of mmaped region
116// in '*buff_size'.
117void *MapFileToMemory(const char *file_name, uptr *buff_size);
118
119// OS
120void DisableCoreDumper();
121void DumpProcessMap();
122bool FileExists(const char *filename);
123const char *GetEnv(const char *name);
124const char *GetPwd();
125void ReExec();
126bool StackSizeIsUnlimited();
127void SetStackSizeLimitInBytes(uptr limit);
128void PrepareForSandboxing();
129
130// Other
131void SleepForSeconds(int seconds);
132void SleepForMillis(int millis);
133int Atexit(void (*function)(void));
134void SortArray(uptr *array, uptr size);
135
136// Exit
137void NORETURN Abort();
138void NORETURN Exit(int exitcode);
139void NORETURN Die();
140void NORETURN SANITIZER_INTERFACE_ATTRIBUTE
141CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
142
143// Set the name of the current thread to 'name', return true on succees.
144// The name may be truncated to a system-dependent limit.
145bool SanitizerSetThreadName(const char *name);
146// Get the name of the current thread (no more than max_len bytes),
147// return true on succees. name should have space for at least max_len+1 bytes.
148bool SanitizerGetThreadName(char *name, int max_len);
149
150// Specific tools may override behavior of "Die" and "CheckFailed" functions
151// to do tool-specific job.
152void SetDieCallback(void (*callback)(void));
153typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
154                                       u64, u64);
155void SetCheckFailedCallback(CheckFailedCallbackType callback);
156
157// Math
158INLINE bool IsPowerOfTwo(uptr x) {
159  return (x & (x - 1)) == 0;
160}
161INLINE uptr RoundUpTo(uptr size, uptr boundary) {
162  CHECK(IsPowerOfTwo(boundary));
163  return (size + boundary - 1) & ~(boundary - 1);
164}
165INLINE uptr RoundDownTo(uptr x, uptr boundary) {
166  return x & ~(boundary - 1);
167}
168INLINE bool IsAligned(uptr a, uptr alignment) {
169  return (a & (alignment - 1)) == 0;
170}
171// Don't use std::min, std::max or std::swap, to minimize dependency
172// on libstdc++.
173template<class T> T Min(T a, T b) { return a < b ? a : b; }
174template<class T> T Max(T a, T b) { return a > b ? a : b; }
175template<class T> void Swap(T& a, T& b) {
176  T tmp = a;
177  a = b;
178  b = tmp;
179}
180
181// Char handling
182INLINE bool IsSpace(int c) {
183  return (c == ' ') || (c == '\n') || (c == '\t') ||
184         (c == '\f') || (c == '\r') || (c == '\v');
185}
186INLINE bool IsDigit(int c) {
187  return (c >= '0') && (c <= '9');
188}
189INLINE int ToLower(int c) {
190  return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
191}
192
193#if SANITIZER_WORDSIZE == 64
194# define FIRST_32_SECOND_64(a, b) (b)
195#else
196# define FIRST_32_SECOND_64(a, b) (a)
197#endif
198
199}  // namespace __sanitizer
200
201#endif  // SANITIZER_COMMON_H
202