tsan: fix strerror interceptor (eliminate false positives)
[blocksruntime.git] / lib / sanitizer_common / sanitizer_common.h
blob87f3b48f3726b4ee9dd461cb41eb25b9bec0928f
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
19 #include "sanitizer_internal_defs.h"
20 #include "sanitizer_libc.h"
21 #include "sanitizer_mutex.h"
23 namespace __sanitizer {
24 struct StackTrace;
26 // Constants.
27 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
28 const uptr kWordSizeInBits = 8 * kWordSize;
30 #if defined(__powerpc__) || defined(__powerpc64__)
31 const uptr kCacheLineSize = 128;
32 #else
33 const uptr kCacheLineSize = 64;
34 #endif
36 const uptr kMaxPathLength = 512;
38 extern const char *SanitizerToolName; // Can be changed by the tool.
40 uptr GetPageSize();
41 uptr GetPageSizeCached();
42 uptr GetMmapGranularity();
43 uptr GetMaxVirtualAddress();
44 // Threads
45 uptr GetTid();
46 uptr GetThreadSelf();
47 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
48 uptr *stack_bottom);
49 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
50 uptr *tls_addr, uptr *tls_size);
52 // Memory management
53 void *MmapOrDie(uptr size, const char *mem_type);
54 void UnmapOrDie(void *addr, uptr size);
55 void *MmapFixedNoReserve(uptr fixed_addr, uptr size);
56 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
57 void *Mprotect(uptr fixed_addr, uptr size);
58 // Map aligned chunk of address space; size and alignment are powers of two.
59 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
60 // Used to check if we can map shadow memory to a fixed location.
61 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
62 void FlushUnneededShadowMemory(uptr addr, uptr size);
64 // InternalScopedBuffer can be used instead of large stack arrays to
65 // keep frame size low.
66 // FIXME: use InternalAlloc instead of MmapOrDie once
67 // InternalAlloc is made libc-free.
68 template<typename T>
69 class InternalScopedBuffer {
70 public:
71 explicit InternalScopedBuffer(uptr cnt) {
72 cnt_ = cnt;
73 ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
75 ~InternalScopedBuffer() {
76 UnmapOrDie(ptr_, cnt_ * sizeof(T));
78 T &operator[](uptr i) { return ptr_[i]; }
79 T *data() { return ptr_; }
80 uptr size() { return cnt_ * sizeof(T); }
82 private:
83 T *ptr_;
84 uptr cnt_;
85 // Disallow evil constructors.
86 InternalScopedBuffer(const InternalScopedBuffer&);
87 void operator=(const InternalScopedBuffer&);
90 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
91 // constructor, so all instances of LowLevelAllocator should be
92 // linker initialized.
93 class LowLevelAllocator {
94 public:
95 // Requires an external lock.
96 void *Allocate(uptr size);
97 private:
98 char *allocated_end_;
99 char *allocated_current_;
101 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
102 // Allows to register tool-specific callbacks for LowLevelAllocator.
103 // Passing NULL removes the callback.
104 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
106 // IO
107 void RawWrite(const char *buffer);
108 bool PrintsToTty();
109 // Caching version of PrintsToTty(). Not thread-safe.
110 bool PrintsToTtyCached();
111 void Printf(const char *format, ...);
112 void Report(const char *format, ...);
113 void SetPrintfAndReportCallback(void (*callback)(const char *));
114 // Can be used to prevent mixing error reports from different sanitizers.
115 extern StaticSpinMutex CommonSanitizerReportMutex;
116 void MaybeOpenReportFile();
117 extern fd_t report_fd;
118 extern bool log_to_file;
119 extern char report_path_prefix[4096];
120 extern uptr report_fd_pid;
122 uptr OpenFile(const char *filename, bool write);
123 // Opens the file 'file_name" and reads up to 'max_len' bytes.
124 // The resulting buffer is mmaped and stored in '*buff'.
125 // The size of the mmaped region is stored in '*buff_size',
126 // Returns the number of read bytes or 0 if file can not be opened.
127 uptr ReadFileToBuffer(const char *file_name, char **buff,
128 uptr *buff_size, uptr max_len);
129 // Maps given file to virtual memory, and returns pointer to it
130 // (or NULL if the mapping failes). Stores the size of mmaped region
131 // in '*buff_size'.
132 void *MapFileToMemory(const char *file_name, uptr *buff_size);
134 // Error report formatting.
135 const char *StripPathPrefix(const char *filepath,
136 const char *strip_file_prefix);
137 void PrintSourceLocation(const char *file, int line, int column);
138 void PrintModuleAndOffset(const char *module, uptr offset);
141 // OS
142 void DisableCoreDumper();
143 void DumpProcessMap();
144 bool FileExists(const char *filename);
145 const char *GetEnv(const char *name);
146 bool SetEnv(const char *name, const char *value);
147 const char *GetPwd();
148 char *FindPathToBinary(const char *name);
149 u32 GetUid();
150 void ReExec();
151 bool StackSizeIsUnlimited();
152 void SetStackSizeLimitInBytes(uptr limit);
153 void PrepareForSandboxing();
155 void InitTlsSize();
156 uptr GetTlsSize();
158 // Other
159 void SleepForSeconds(int seconds);
160 void SleepForMillis(int millis);
161 u64 NanoTime();
162 int Atexit(void (*function)(void));
163 void SortArray(uptr *array, uptr size);
165 // Exit
166 void NORETURN Abort();
167 void NORETURN Die();
168 void NORETURN
169 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
171 // Set the name of the current thread to 'name', return true on succees.
172 // The name may be truncated to a system-dependent limit.
173 bool SanitizerSetThreadName(const char *name);
174 // Get the name of the current thread (no more than max_len bytes),
175 // return true on succees. name should have space for at least max_len+1 bytes.
176 bool SanitizerGetThreadName(char *name, int max_len);
178 // Specific tools may override behavior of "Die" and "CheckFailed" functions
179 // to do tool-specific job.
180 typedef void (*DieCallbackType)(void);
181 void SetDieCallback(DieCallbackType);
182 DieCallbackType GetDieCallback();
183 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
184 u64, u64);
185 void SetCheckFailedCallback(CheckFailedCallbackType callback);
187 // Construct a one-line string like
188 // SanitizerToolName: error_type file:line function
189 // and call __sanitizer_report_error_summary on it.
190 void ReportErrorSummary(const char *error_type, const char *file,
191 int line, const char *function);
193 // Math
194 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
195 extern "C" {
196 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
197 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
198 #if defined(_WIN64)
199 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
200 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
201 #endif
203 #endif
205 INLINE uptr MostSignificantSetBitIndex(uptr x) {
206 CHECK_NE(x, 0U);
207 unsigned long up; // NOLINT
208 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
209 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
210 #elif defined(_WIN64)
211 _BitScanReverse64(&up, x);
212 #else
213 _BitScanReverse(&up, x);
214 #endif
215 return up;
218 INLINE bool IsPowerOfTwo(uptr x) {
219 return (x & (x - 1)) == 0;
222 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
223 CHECK(size);
224 if (IsPowerOfTwo(size)) return size;
226 uptr up = MostSignificantSetBitIndex(size);
227 CHECK(size < (1ULL << (up + 1)));
228 CHECK(size > (1ULL << up));
229 return 1UL << (up + 1);
232 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
233 CHECK(IsPowerOfTwo(boundary));
234 return (size + boundary - 1) & ~(boundary - 1);
237 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
238 return x & ~(boundary - 1);
241 INLINE bool IsAligned(uptr a, uptr alignment) {
242 return (a & (alignment - 1)) == 0;
245 INLINE uptr Log2(uptr x) {
246 CHECK(IsPowerOfTwo(x));
247 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
248 return __builtin_ctzl(x);
249 #elif defined(_WIN64)
250 unsigned long ret; // NOLINT
251 _BitScanForward64(&ret, x);
252 return ret;
253 #else
254 unsigned long ret; // NOLINT
255 _BitScanForward(&ret, x);
256 return ret;
257 #endif
260 // Don't use std::min, std::max or std::swap, to minimize dependency
261 // on libstdc++.
262 template<class T> T Min(T a, T b) { return a < b ? a : b; }
263 template<class T> T Max(T a, T b) { return a > b ? a : b; }
264 template<class T> void Swap(T& a, T& b) {
265 T tmp = a;
266 a = b;
267 b = tmp;
270 // Char handling
271 INLINE bool IsSpace(int c) {
272 return (c == ' ') || (c == '\n') || (c == '\t') ||
273 (c == '\f') || (c == '\r') || (c == '\v');
275 INLINE bool IsDigit(int c) {
276 return (c >= '0') && (c <= '9');
278 INLINE int ToLower(int c) {
279 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
282 #if SANITIZER_WORDSIZE == 64
283 # define FIRST_32_SECOND_64(a, b) (b)
284 #else
285 # define FIRST_32_SECOND_64(a, b) (a)
286 #endif
288 // A low-level vector based on mmap. May incur a significant memory overhead for
289 // small vectors.
290 // WARNING: The current implementation supports only POD types.
291 template<typename T>
292 class InternalMmapVector {
293 public:
294 explicit InternalMmapVector(uptr initial_capacity) {
295 CHECK_GT(initial_capacity, 0);
296 capacity_ = initial_capacity;
297 size_ = 0;
298 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVector");
300 ~InternalMmapVector() {
301 UnmapOrDie(data_, capacity_ * sizeof(T));
303 T &operator[](uptr i) {
304 CHECK_LT(i, size_);
305 return data_[i];
307 const T &operator[](uptr i) const {
308 CHECK_LT(i, size_);
309 return data_[i];
311 void push_back(const T &element) {
312 CHECK_LE(size_, capacity_);
313 if (size_ == capacity_) {
314 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
315 Resize(new_capacity);
317 data_[size_++] = element;
319 T &back() {
320 CHECK_GT(size_, 0);
321 return data_[size_ - 1];
323 void pop_back() {
324 CHECK_GT(size_, 0);
325 size_--;
327 uptr size() const {
328 return size_;
330 const T *data() const {
331 return data_;
333 uptr capacity() const {
334 return capacity_;
337 private:
338 void Resize(uptr new_capacity) {
339 CHECK_GT(new_capacity, 0);
340 CHECK_LE(size_, new_capacity);
341 T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
342 "InternalMmapVector");
343 internal_memcpy(new_data, data_, size_ * sizeof(T));
344 T *old_data = data_;
345 data_ = new_data;
346 UnmapOrDie(old_data, capacity_ * sizeof(T));
347 capacity_ = new_capacity;
349 // Disallow evil constructors.
350 InternalMmapVector(const InternalMmapVector&);
351 void operator=(const InternalMmapVector&);
353 T *data_;
354 uptr capacity_;
355 uptr size_;
358 // HeapSort for arrays and InternalMmapVector.
359 template<class Container, class Compare>
360 void InternalSort(Container *v, uptr size, Compare comp) {
361 if (size < 2)
362 return;
363 // Stage 1: insert elements to the heap.
364 for (uptr i = 1; i < size; i++) {
365 uptr j, p;
366 for (j = i; j > 0; j = p) {
367 p = (j - 1) / 2;
368 if (comp((*v)[p], (*v)[j]))
369 Swap((*v)[j], (*v)[p]);
370 else
371 break;
374 // Stage 2: swap largest element with the last one,
375 // and sink the new top.
376 for (uptr i = size - 1; i > 0; i--) {
377 Swap((*v)[0], (*v)[i]);
378 uptr j, max_ind;
379 for (j = 0; j < i; j = max_ind) {
380 uptr left = 2 * j + 1;
381 uptr right = 2 * j + 2;
382 max_ind = j;
383 if (left < i && comp((*v)[max_ind], (*v)[left]))
384 max_ind = left;
385 if (right < i && comp((*v)[max_ind], (*v)[right]))
386 max_ind = right;
387 if (max_ind != j)
388 Swap((*v)[j], (*v)[max_ind]);
389 else
390 break;
395 template<class Container, class Value, class Compare>
396 uptr InternalBinarySearch(const Container &v, uptr first, uptr last,
397 const Value &val, Compare comp) {
398 uptr not_found = last + 1;
399 while (last >= first) {
400 uptr mid = (first + last) / 2;
401 if (comp(v[mid], val))
402 first = mid + 1;
403 else if (comp(val, v[mid]))
404 last = mid - 1;
405 else
406 return mid;
408 return not_found;
411 // Represents a binary loaded into virtual memory (e.g. this can be an
412 // executable or a shared object).
413 class LoadedModule {
414 public:
415 LoadedModule(const char *module_name, uptr base_address);
416 void addAddressRange(uptr beg, uptr end);
417 bool containsAddress(uptr address) const;
419 const char *full_name() const { return full_name_; }
420 uptr base_address() const { return base_address_; }
422 private:
423 struct AddressRange {
424 uptr beg;
425 uptr end;
427 char *full_name_;
428 uptr base_address_;
429 static const uptr kMaxNumberOfAddressRanges = 6;
430 AddressRange ranges_[kMaxNumberOfAddressRanges];
431 uptr n_ranges_;
434 // OS-dependent function that fills array with descriptions of at most
435 // "max_modules" currently loaded modules. Returns the number of
436 // initialized modules. If filter is nonzero, ignores modules for which
437 // filter(full_name) is false.
438 typedef bool (*string_predicate_t)(const char *);
439 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
440 string_predicate_t filter);
442 #if SANITIZER_POSIX
443 const uptr kPthreadDestructorIterations = 4;
444 #else
445 // Unused on Windows.
446 const uptr kPthreadDestructorIterations = 0;
447 #endif
449 // Callback type for iterating over a set of memory ranges.
450 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
451 } // namespace __sanitizer
453 #endif // SANITIZER_COMMON_H