sanitizer_common.h revision 2fb08720b11b4c339e191b90d85477c6a2dd74db
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// We don't want a summary too long. 188const int kMaxSummaryLength = 1024; 189// Construct a one-line string: 190// SUMMARY: SanitizerToolName: error_message 191// and pass it to __sanitizer_report_error_summary. 192void ReportErrorSummary(const char *error_message); 193// Same as above, but construct error_message as: 194// error_type: file:line function 195void ReportErrorSummary(const char *error_type, const char *file, 196 int line, const char *function); 197void ReportErrorSummary(const char *error_type, StackTrace *trace); 198 199// Math 200#if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__) 201extern "C" { 202unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT 203unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT 204#if defined(_WIN64) 205unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT 206unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT 207#endif 208} 209#endif 210 211INLINE uptr MostSignificantSetBitIndex(uptr x) { 212 CHECK_NE(x, 0U); 213 unsigned long up; // NOLINT 214#if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__) 215 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x); 216#elif defined(_WIN64) 217 _BitScanReverse64(&up, x); 218#else 219 _BitScanReverse(&up, x); 220#endif 221 return up; 222} 223 224INLINE bool IsPowerOfTwo(uptr x) { 225 return (x & (x - 1)) == 0; 226} 227 228INLINE uptr RoundUpToPowerOfTwo(uptr size) { 229 CHECK(size); 230 if (IsPowerOfTwo(size)) return size; 231 232 uptr up = MostSignificantSetBitIndex(size); 233 CHECK(size < (1ULL << (up + 1))); 234 CHECK(size > (1ULL << up)); 235 return 1UL << (up + 1); 236} 237 238INLINE uptr RoundUpTo(uptr size, uptr boundary) { 239 CHECK(IsPowerOfTwo(boundary)); 240 return (size + boundary - 1) & ~(boundary - 1); 241} 242 243INLINE uptr RoundDownTo(uptr x, uptr boundary) { 244 return x & ~(boundary - 1); 245} 246 247INLINE bool IsAligned(uptr a, uptr alignment) { 248 return (a & (alignment - 1)) == 0; 249} 250 251INLINE uptr Log2(uptr x) { 252 CHECK(IsPowerOfTwo(x)); 253#if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__) 254 return __builtin_ctzl(x); 255#elif defined(_WIN64) 256 unsigned long ret; // NOLINT 257 _BitScanForward64(&ret, x); 258 return ret; 259#else 260 unsigned long ret; // NOLINT 261 _BitScanForward(&ret, x); 262 return ret; 263#endif 264} 265 266// Don't use std::min, std::max or std::swap, to minimize dependency 267// on libstdc++. 268template<class T> T Min(T a, T b) { return a < b ? a : b; } 269template<class T> T Max(T a, T b) { return a > b ? a : b; } 270template<class T> void Swap(T& a, T& b) { 271 T tmp = a; 272 a = b; 273 b = tmp; 274} 275 276// Char handling 277INLINE bool IsSpace(int c) { 278 return (c == ' ') || (c == '\n') || (c == '\t') || 279 (c == '\f') || (c == '\r') || (c == '\v'); 280} 281INLINE bool IsDigit(int c) { 282 return (c >= '0') && (c <= '9'); 283} 284INLINE int ToLower(int c) { 285 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c; 286} 287 288#if SANITIZER_WORDSIZE == 64 289# define FIRST_32_SECOND_64(a, b) (b) 290#else 291# define FIRST_32_SECOND_64(a, b) (a) 292#endif 293 294// A low-level vector based on mmap. May incur a significant memory overhead for 295// small vectors. 296// WARNING: The current implementation supports only POD types. 297template<typename T> 298class InternalMmapVector { 299 public: 300 explicit InternalMmapVector(uptr initial_capacity) { 301 CHECK_GT(initial_capacity, 0); 302 capacity_ = initial_capacity; 303 size_ = 0; 304 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVector"); 305 } 306 ~InternalMmapVector() { 307 UnmapOrDie(data_, capacity_ * sizeof(T)); 308 } 309 T &operator[](uptr i) { 310 CHECK_LT(i, size_); 311 return data_[i]; 312 } 313 const T &operator[](uptr i) const { 314 CHECK_LT(i, size_); 315 return data_[i]; 316 } 317 void push_back(const T &element) { 318 CHECK_LE(size_, capacity_); 319 if (size_ == capacity_) { 320 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1); 321 Resize(new_capacity); 322 } 323 data_[size_++] = element; 324 } 325 T &back() { 326 CHECK_GT(size_, 0); 327 return data_[size_ - 1]; 328 } 329 void pop_back() { 330 CHECK_GT(size_, 0); 331 size_--; 332 } 333 uptr size() const { 334 return size_; 335 } 336 const T *data() const { 337 return data_; 338 } 339 uptr capacity() const { 340 return capacity_; 341 } 342 343 private: 344 void Resize(uptr new_capacity) { 345 CHECK_GT(new_capacity, 0); 346 CHECK_LE(size_, new_capacity); 347 T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T), 348 "InternalMmapVector"); 349 internal_memcpy(new_data, data_, size_ * sizeof(T)); 350 T *old_data = data_; 351 data_ = new_data; 352 UnmapOrDie(old_data, capacity_ * sizeof(T)); 353 capacity_ = new_capacity; 354 } 355 // Disallow evil constructors. 356 InternalMmapVector(const InternalMmapVector&); 357 void operator=(const InternalMmapVector&); 358 359 T *data_; 360 uptr capacity_; 361 uptr size_; 362}; 363 364// HeapSort for arrays and InternalMmapVector. 365template<class Container, class Compare> 366void InternalSort(Container *v, uptr size, Compare comp) { 367 if (size < 2) 368 return; 369 // Stage 1: insert elements to the heap. 370 for (uptr i = 1; i < size; i++) { 371 uptr j, p; 372 for (j = i; j > 0; j = p) { 373 p = (j - 1) / 2; 374 if (comp((*v)[p], (*v)[j])) 375 Swap((*v)[j], (*v)[p]); 376 else 377 break; 378 } 379 } 380 // Stage 2: swap largest element with the last one, 381 // and sink the new top. 382 for (uptr i = size - 1; i > 0; i--) { 383 Swap((*v)[0], (*v)[i]); 384 uptr j, max_ind; 385 for (j = 0; j < i; j = max_ind) { 386 uptr left = 2 * j + 1; 387 uptr right = 2 * j + 2; 388 max_ind = j; 389 if (left < i && comp((*v)[max_ind], (*v)[left])) 390 max_ind = left; 391 if (right < i && comp((*v)[max_ind], (*v)[right])) 392 max_ind = right; 393 if (max_ind != j) 394 Swap((*v)[j], (*v)[max_ind]); 395 else 396 break; 397 } 398 } 399} 400 401template<class Container, class Value, class Compare> 402uptr InternalBinarySearch(const Container &v, uptr first, uptr last, 403 const Value &val, Compare comp) { 404 uptr not_found = last + 1; 405 while (last >= first) { 406 uptr mid = (first + last) / 2; 407 if (comp(v[mid], val)) 408 first = mid + 1; 409 else if (comp(val, v[mid])) 410 last = mid - 1; 411 else 412 return mid; 413 } 414 return not_found; 415} 416 417// Represents a binary loaded into virtual memory (e.g. this can be an 418// executable or a shared object). 419class LoadedModule { 420 public: 421 LoadedModule(const char *module_name, uptr base_address); 422 void addAddressRange(uptr beg, uptr end); 423 bool containsAddress(uptr address) const; 424 425 const char *full_name() const { return full_name_; } 426 uptr base_address() const { return base_address_; } 427 428 private: 429 struct AddressRange { 430 uptr beg; 431 uptr end; 432 }; 433 char *full_name_; 434 uptr base_address_; 435 static const uptr kMaxNumberOfAddressRanges = 6; 436 AddressRange ranges_[kMaxNumberOfAddressRanges]; 437 uptr n_ranges_; 438}; 439 440// OS-dependent function that fills array with descriptions of at most 441// "max_modules" currently loaded modules. Returns the number of 442// initialized modules. If filter is nonzero, ignores modules for which 443// filter(full_name) is false. 444typedef bool (*string_predicate_t)(const char *); 445uptr GetListOfModules(LoadedModule *modules, uptr max_modules, 446 string_predicate_t filter); 447 448#if SANITIZER_POSIX 449const uptr kPthreadDestructorIterations = 4; 450#else 451// Unused on Windows. 452const uptr kPthreadDestructorIterations = 0; 453#endif 454 455// Callback type for iterating over a set of memory ranges. 456typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg); 457} // namespace __sanitizer 458 459inline void *operator new(__sanitizer::operator_new_size_type size, 460 __sanitizer::LowLevelAllocator &alloc) { 461 return alloc.Allocate(size); 462} 463 464#endif // SANITIZER_COMMON_H 465