sanitizer_common.h revision 53177247698bfba075f2d5b255a447fc3ced6976
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. 39 40uptr GetPageSize(); 41uptr GetPageSizeCached(); 42uptr GetMmapGranularity(); 43uptr GetMaxVirtualAddress(); 44// Threads 45uptr GetTid(); 46uptr GetThreadSelf(); 47void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top, 48 uptr *stack_bottom); 49void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size, 50 uptr *tls_addr, uptr *tls_size); 51 52// Memory management 53void *MmapOrDie(uptr size, const char *mem_type); 54void UnmapOrDie(void *addr, uptr size); 55void *MmapFixedNoReserve(uptr fixed_addr, uptr size); 56void *MmapFixedOrDie(uptr fixed_addr, uptr size); 57void *Mprotect(uptr fixed_addr, uptr size); 58// Map aligned chunk of address space; size and alignment are powers of two. 59void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type); 60// Used to check if we can map shadow memory to a fixed location. 61bool MemoryRangeIsAvailable(uptr range_start, uptr range_end); 62void FlushUnneededShadowMemory(uptr addr, uptr size); 63 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. 68template<typename T> 69class InternalScopedBuffer { 70 public: 71 explicit InternalScopedBuffer(uptr cnt) { 72 cnt_ = cnt; 73 ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer"); 74 } 75 ~InternalScopedBuffer() { 76 UnmapOrDie(ptr_, cnt_ * sizeof(T)); 77 } 78 T &operator[](uptr i) { return ptr_[i]; } 79 T *data() { return ptr_; } 80 uptr size() { return cnt_ * sizeof(T); } 81 82 private: 83 T *ptr_; 84 uptr cnt_; 85 // Disallow evil constructors. 86 InternalScopedBuffer(const InternalScopedBuffer&); 87 void operator=(const InternalScopedBuffer&); 88}; 89 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. 93class LowLevelAllocator { 94 public: 95 // Requires an external lock. 96 void *Allocate(uptr size); 97 private: 98 char *allocated_end_; 99 char *allocated_current_; 100}; 101typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size); 102// Allows to register tool-specific callbacks for LowLevelAllocator. 103// Passing NULL removes the callback. 104void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback); 105 106// IO 107void RawWrite(const char *buffer); 108bool PrintsToTty(); 109// Caching version of PrintsToTty(). Not thread-safe. 110bool PrintsToTtyCached(); 111void Printf(const char *format, ...); 112void Report(const char *format, ...); 113void SetPrintfAndReportCallback(void (*callback)(const char *)); 114// Can be used to prevent mixing error reports from different sanitizers. 115extern StaticSpinMutex CommonSanitizerReportMutex; 116void MaybeOpenReportFile(); 117extern fd_t report_fd; 118extern bool log_to_file; 119extern char report_path_prefix[4096]; 120extern uptr report_fd_pid; 121 122uptr 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. 127uptr 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'. 132void *MapFileToMemory(const char *file_name, uptr *buff_size); 133 134// Error report formatting. 135const char *StripPathPrefix(const char *filepath, 136 const char *strip_file_prefix); 137void PrintSourceLocation(const char *file, int line, int column); 138void PrintModuleAndOffset(const char *module, uptr offset); 139 140 141// OS 142void DisableCoreDumper(); 143void DumpProcessMap(); 144bool FileExists(const char *filename); 145const char *GetEnv(const char *name); 146bool SetEnv(const char *name, const char *value); 147const char *GetPwd(); 148char *FindPathToBinary(const char *name); 149u32 GetUid(); 150void ReExec(); 151bool StackSizeIsUnlimited(); 152void SetStackSizeLimitInBytes(uptr limit); 153void PrepareForSandboxing(); 154 155void InitTlsSize(); 156uptr GetTlsSize(); 157 158// Other 159void SleepForSeconds(int seconds); 160void SleepForMillis(int millis); 161u64 NanoTime(); 162int Atexit(void (*function)(void)); 163void SortArray(uptr *array, uptr size); 164 165// Exit 166void NORETURN Abort(); 167void NORETURN Die(); 168void NORETURN 169CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2); 170 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. 173bool 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. 176bool SanitizerGetThreadName(char *name, int max_len); 177 178// Specific tools may override behavior of "Die" and "CheckFailed" functions 179// to do tool-specific job. 180typedef void (*DieCallbackType)(void); 181void SetDieCallback(DieCallbackType); 182DieCallbackType GetDieCallback(); 183typedef void (*CheckFailedCallbackType)(const char *, int, const char *, 184 u64, u64); 185void SetCheckFailedCallback(CheckFailedCallbackType callback); 186 187// Construct a one-line string like 188// SanitizerToolName: error_type file:line function 189// and call __sanitizer_report_error_summary on it. 190void ReportErrorSummary(const char *error_type, const char *file, 191 int line, const char *function); 192 193// Math 194#if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__) 195extern "C" { 196unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT 197unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT 198#if defined(_WIN64) 199unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT 200unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT 201#endif 202} 203#endif 204 205INLINE 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; 216} 217 218INLINE bool IsPowerOfTwo(uptr x) { 219 return (x & (x - 1)) == 0; 220} 221 222INLINE uptr RoundUpToPowerOfTwo(uptr size) { 223 CHECK(size); 224 if (IsPowerOfTwo(size)) return size; 225 226 uptr up = MostSignificantSetBitIndex(size); 227 CHECK(size < (1ULL << (up + 1))); 228 CHECK(size > (1ULL << up)); 229 return 1UL << (up + 1); 230} 231 232INLINE uptr RoundUpTo(uptr size, uptr boundary) { 233 CHECK(IsPowerOfTwo(boundary)); 234 return (size + boundary - 1) & ~(boundary - 1); 235} 236 237INLINE uptr RoundDownTo(uptr x, uptr boundary) { 238 return x & ~(boundary - 1); 239} 240 241INLINE bool IsAligned(uptr a, uptr alignment) { 242 return (a & (alignment - 1)) == 0; 243} 244 245INLINE 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 258} 259 260// Don't use std::min, std::max or std::swap, to minimize dependency 261// on libstdc++. 262template<class T> T Min(T a, T b) { return a < b ? a : b; } 263template<class T> T Max(T a, T b) { return a > b ? a : b; } 264template<class T> void Swap(T& a, T& b) { 265 T tmp = a; 266 a = b; 267 b = tmp; 268} 269 270// Char handling 271INLINE bool IsSpace(int c) { 272 return (c == ' ') || (c == '\n') || (c == '\t') || 273 (c == '\f') || (c == '\r') || (c == '\v'); 274} 275INLINE bool IsDigit(int c) { 276 return (c >= '0') && (c <= '9'); 277} 278INLINE int ToLower(int c) { 279 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c; 280} 281 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 287 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. 291template<typename T> 292class 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"); 299 } 300 ~InternalMmapVector() { 301 UnmapOrDie(data_, capacity_ * sizeof(T)); 302 } 303 T &operator[](uptr i) { 304 CHECK_LT(i, size_); 305 return data_[i]; 306 } 307 const T &operator[](uptr i) const { 308 CHECK_LT(i, size_); 309 return data_[i]; 310 } 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); 316 } 317 data_[size_++] = element; 318 } 319 T &back() { 320 CHECK_GT(size_, 0); 321 return data_[size_ - 1]; 322 } 323 void pop_back() { 324 CHECK_GT(size_, 0); 325 size_--; 326 } 327 uptr size() const { 328 return size_; 329 } 330 const T *data() const { 331 return data_; 332 } 333 uptr capacity() const { 334 return capacity_; 335 } 336 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; 348 } 349 // Disallow evil constructors. 350 InternalMmapVector(const InternalMmapVector&); 351 void operator=(const InternalMmapVector&); 352 353 T *data_; 354 uptr capacity_; 355 uptr size_; 356}; 357 358// HeapSort for arrays and InternalMmapVector. 359template<class Container, class Compare> 360void 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; 372 } 373 } 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; 391 } 392 } 393} 394 395template<class Container, class Value, class Compare> 396uptr 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; 407 } 408 return not_found; 409} 410 411// Represents a binary loaded into virtual memory (e.g. this can be an 412// executable or a shared object). 413class 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; 418 419 const char *full_name() const { return full_name_; } 420 uptr base_address() const { return base_address_; } 421 422 private: 423 struct AddressRange { 424 uptr beg; 425 uptr end; 426 }; 427 char *full_name_; 428 uptr base_address_; 429 static const uptr kMaxNumberOfAddressRanges = 6; 430 AddressRange ranges_[kMaxNumberOfAddressRanges]; 431 uptr n_ranges_; 432}; 433 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. 438typedef bool (*string_predicate_t)(const char *); 439uptr GetListOfModules(LoadedModule *modules, uptr max_modules, 440 string_predicate_t filter); 441 442#if SANITIZER_POSIX 443const uptr kPthreadDestructorIterations = 4; 444#else 445// Unused on Windows. 446const uptr kPthreadDestructorIterations = 0; 447#endif 448 449// Callback type for iterating over a set of memory ranges. 450typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg); 451} // namespace __sanitizer 452 453inline void *operator new(__sanitizer::operator_new_size_type size, 454 __sanitizer::LowLevelAllocator &alloc) { 455 return alloc.Allocate(size); 456} 457 458#endif // SANITIZER_COMMON_H 459