Remove a trivial assert (missed in previous checkin)
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_common.h
blobd2782b6c9dce0d22b7e5469182c09113c34f7a66
1 //===-- sanitizer_common.h --------------------------------------*- C++ -*-===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries.
10 // It declares common functions and classes that are used in both runtimes.
11 // Implementation of some functions are provided in sanitizer_common, while
12 // others must be defined by run-time library itself.
13 //===----------------------------------------------------------------------===//
14 #ifndef SANITIZER_COMMON_H
15 #define SANITIZER_COMMON_H
17 #include "sanitizer_internal_defs.h"
18 #include "sanitizer_mutex.h"
20 namespace __sanitizer {
21 struct StackTrace;
23 // Constants.
24 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
25 const uptr kWordSizeInBits = 8 * kWordSize;
27 #if defined(__powerpc__) || defined(__powerpc64__)
28 const uptr kCacheLineSize = 128;
29 #else
30 const uptr kCacheLineSize = 64;
31 #endif
33 extern const char *SanitizerToolName; // Can be changed by the tool.
35 uptr GetPageSize();
36 uptr GetPageSizeCached();
37 uptr GetMmapGranularity();
38 // Threads
39 int GetPid();
40 uptr GetTid();
41 uptr GetThreadSelf();
42 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
43 uptr *stack_bottom);
45 // Memory management
46 void *MmapOrDie(uptr size, const char *mem_type);
47 void UnmapOrDie(void *addr, uptr size);
48 void *MmapFixedNoReserve(uptr fixed_addr, uptr size);
49 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
50 void *Mprotect(uptr fixed_addr, uptr size);
51 // Map aligned chunk of address space; size and alignment are powers of two.
52 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
53 // Used to check if we can map shadow memory to a fixed location.
54 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
55 void FlushUnneededShadowMemory(uptr addr, uptr size);
57 // Internal allocator
58 void *InternalAlloc(uptr size);
59 void InternalFree(void *p);
61 // InternalScopedBuffer can be used instead of large stack arrays to
62 // keep frame size low.
63 // FIXME: use InternalAlloc instead of MmapOrDie once
64 // InternalAlloc is made libc-free.
65 template<typename T>
66 class InternalScopedBuffer {
67 public:
68 explicit InternalScopedBuffer(uptr cnt) {
69 cnt_ = cnt;
70 ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
72 ~InternalScopedBuffer() {
73 UnmapOrDie(ptr_, cnt_ * sizeof(T));
75 T &operator[](uptr i) { return ptr_[i]; }
76 T *data() { return ptr_; }
77 uptr size() { return cnt_ * sizeof(T); }
79 private:
80 T *ptr_;
81 uptr cnt_;
82 // Disallow evil constructors.
83 InternalScopedBuffer(const InternalScopedBuffer&);
84 void operator=(const InternalScopedBuffer&);
87 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
88 // constructor, so all instances of LowLevelAllocator should be
89 // linker initialized.
90 class LowLevelAllocator {
91 public:
92 // Requires an external lock.
93 void *Allocate(uptr size);
94 private:
95 char *allocated_end_;
96 char *allocated_current_;
98 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
99 // Allows to register tool-specific callbacks for LowLevelAllocator.
100 // Passing NULL removes the callback.
101 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
103 // IO
104 void RawWrite(const char *buffer);
105 bool PrintsToTty();
106 void Printf(const char *format, ...);
107 void Report(const char *format, ...);
108 void SetPrintfAndReportCallback(void (*callback)(const char *));
109 // Can be used to prevent mixing error reports from different sanitizers.
110 extern StaticSpinMutex CommonSanitizerReportMutex;
112 fd_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.
117 uptr 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'.
122 void *MapFileToMemory(const char *file_name, uptr *buff_size);
124 // OS
125 void DisableCoreDumper();
126 void DumpProcessMap();
127 bool FileExists(const char *filename);
128 const char *GetEnv(const char *name);
129 const char *GetPwd();
130 u32 GetUid();
131 void ReExec();
132 bool StackSizeIsUnlimited();
133 void SetStackSizeLimitInBytes(uptr limit);
134 void PrepareForSandboxing();
136 // Other
137 void SleepForSeconds(int seconds);
138 void SleepForMillis(int millis);
139 int Atexit(void (*function)(void));
140 void SortArray(uptr *array, uptr size);
142 // Exit
143 void NORETURN Abort();
144 void NORETURN Die();
145 void NORETURN SANITIZER_INTERFACE_ATTRIBUTE
146 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
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.
150 bool 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.
153 bool SanitizerGetThreadName(char *name, int max_len);
155 // Specific tools may override behavior of "Die" and "CheckFailed" functions
156 // to do tool-specific job.
157 void SetDieCallback(void (*callback)(void));
158 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
159 u64, u64);
160 void SetCheckFailedCallback(CheckFailedCallbackType callback);
162 // Construct a one-line string like
163 // SanitizerToolName: error_type file:line function
164 // and call __sanitizer_report_error_summary on it.
165 void ReportErrorSummary(const char *error_type, const char *file,
166 int line, const char *function);
168 // Math
169 #if defined(_WIN32) && !defined(__clang__)
170 extern "C" {
171 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
172 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
173 #if defined(_WIN64)
174 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
175 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
176 #endif
178 #endif
180 INLINE uptr MostSignificantSetBitIndex(uptr x) {
181 CHECK(x != 0);
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;
193 INLINE bool IsPowerOfTwo(uptr x) {
194 return (x & (x - 1)) == 0;
197 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
198 CHECK(size);
199 if (IsPowerOfTwo(size)) return size;
201 uptr up = MostSignificantSetBitIndex(size);
202 CHECK(size < (1ULL << (up + 1)));
203 CHECK(size > (1ULL << up));
204 return 1UL << (up + 1);
207 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
208 CHECK(IsPowerOfTwo(boundary));
209 return (size + boundary - 1) & ~(boundary - 1);
212 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
213 return x & ~(boundary - 1);
216 INLINE bool IsAligned(uptr a, uptr alignment) {
217 return (a & (alignment - 1)) == 0;
220 INLINE 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
235 // Don't use std::min, std::max or std::swap, to minimize dependency
236 // on libstdc++.
237 template<class T> T Min(T a, T b) { return a < b ? a : b; }
238 template<class T> T Max(T a, T b) { return a > b ? a : b; }
239 template<class T> void Swap(T& a, T& b) {
240 T tmp = a;
241 a = b;
242 b = tmp;
245 // Char handling
246 INLINE bool IsSpace(int c) {
247 return (c == ' ') || (c == '\n') || (c == '\t') ||
248 (c == '\f') || (c == '\r') || (c == '\v');
250 INLINE bool IsDigit(int c) {
251 return (c >= '0') && (c <= '9');
253 INLINE int ToLower(int c) {
254 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
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
263 } // namespace __sanitizer
265 #endif // SANITIZER_COMMON_H