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 run-time libraries of sanitizers.
11 //
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_flags.h"
20 #include "sanitizer_interface_internal.h"
21 #include "sanitizer_internal_defs.h"
22 #include "sanitizer_libc.h"
23 #include "sanitizer_list.h"
24 #include "sanitizer_mutex.h"
25
26 #ifdef _MSC_VER
27 extern "C" void _ReadWriteBarrier();
28 #pragma intrinsic(_ReadWriteBarrier)
29 #endif
30
31 namespace __sanitizer {
32 struct StackTrace;
33 struct AddressInfo;
34
35 // Constants.
36 const uptr kWordSize = SANITIZER_WORDSIZE / 8;
37 const uptr kWordSizeInBits = 8 * kWordSize;
38
39 #if defined(__powerpc__) || defined(__powerpc64__)
40 const uptr kCacheLineSize = 128;
41 #else
42 const uptr kCacheLineSize = 64;
43 #endif
44
45 const uptr kMaxPathLength = 4096;
46
47 // 16K loaded modules should be enough for everyone.
48 static const uptr kMaxNumberOfModules = 1 << 14;
49
50 const uptr kMaxThreadStackSize = 1 << 30; // 1Gb
51
52 // Denotes fake PC values that come from JIT/JAVA/etc.
53 // For such PC values __tsan_symbolize_external() will be called.
54 const u64 kExternalPCBit = 1ULL << 60;
55
56 extern const char *SanitizerToolName; // Can be changed by the tool.
57
58 extern atomic_uint32_t current_verbosity;
SetVerbosity(int verbosity)59 INLINE void SetVerbosity(int verbosity) {
60 atomic_store(¤t_verbosity, verbosity, memory_order_relaxed);
61 }
Verbosity()62 INLINE int Verbosity() {
63 return atomic_load(¤t_verbosity, memory_order_relaxed);
64 }
65
66 uptr GetPageSize();
67 uptr GetPageSizeCached();
68 uptr GetMmapGranularity();
69 uptr GetMaxVirtualAddress();
70 // Threads
71 uptr GetTid();
72 uptr GetThreadSelf();
73 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
74 uptr *stack_bottom);
75 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
76 uptr *tls_addr, uptr *tls_size);
77
78 // Memory management
79 void *MmapOrDie(uptr size, const char *mem_type);
80 void UnmapOrDie(void *addr, uptr size);
81 void *MmapFixedNoReserve(uptr fixed_addr, uptr size,
82 const char *name = nullptr);
83 void *MmapNoReserveOrDie(uptr size, const char *mem_type);
84 void *MmapFixedOrDie(uptr fixed_addr, uptr size);
85 void *MmapNoAccess(uptr fixed_addr, uptr size, const char *name = nullptr);
86 // Map aligned chunk of address space; size and alignment are powers of two.
87 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
88 // Disallow access to a memory range. Use MmapNoAccess to allocate an
89 // unaccessible memory.
90 bool MprotectNoAccess(uptr addr, uptr size);
91
92 // Used to check if we can map shadow memory to a fixed location.
93 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
94 void FlushUnneededShadowMemory(uptr addr, uptr size);
95 void IncreaseTotalMmap(uptr size);
96 void DecreaseTotalMmap(uptr size);
97 uptr GetRSS();
98 void NoHugePagesInRegion(uptr addr, uptr length);
99 void DontDumpShadowMemory(uptr addr, uptr length);
100
101 // InternalScopedBuffer can be used instead of large stack arrays to
102 // keep frame size low.
103 // FIXME: use InternalAlloc instead of MmapOrDie once
104 // InternalAlloc is made libc-free.
105 template<typename T>
106 class InternalScopedBuffer {
107 public:
InternalScopedBuffer(uptr cnt)108 explicit InternalScopedBuffer(uptr cnt) {
109 cnt_ = cnt;
110 ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
111 }
~InternalScopedBuffer()112 ~InternalScopedBuffer() {
113 UnmapOrDie(ptr_, cnt_ * sizeof(T));
114 }
115 T &operator[](uptr i) { return ptr_[i]; }
data()116 T *data() { return ptr_; }
size()117 uptr size() { return cnt_ * sizeof(T); }
118
119 private:
120 T *ptr_;
121 uptr cnt_;
122 // Disallow evil constructors.
123 InternalScopedBuffer(const InternalScopedBuffer&);
124 void operator=(const InternalScopedBuffer&);
125 };
126
127 class InternalScopedString : public InternalScopedBuffer<char> {
128 public:
InternalScopedString(uptr max_length)129 explicit InternalScopedString(uptr max_length)
130 : InternalScopedBuffer<char>(max_length), length_(0) {
131 (*this)[0] = '\0';
132 }
length()133 uptr length() { return length_; }
clear()134 void clear() {
135 (*this)[0] = '\0';
136 length_ = 0;
137 }
138 void append(const char *format, ...);
139
140 private:
141 uptr length_;
142 };
143
144 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
145 // constructor, so all instances of LowLevelAllocator should be
146 // linker initialized.
147 class LowLevelAllocator {
148 public:
149 // Requires an external lock.
150 void *Allocate(uptr size);
151 private:
152 char *allocated_end_;
153 char *allocated_current_;
154 };
155 typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
156 // Allows to register tool-specific callbacks for LowLevelAllocator.
157 // Passing NULL removes the callback.
158 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
159
160 // IO
161 void RawWrite(const char *buffer);
162 bool ColorizeReports();
163 void Printf(const char *format, ...);
164 void Report(const char *format, ...);
165 void SetPrintfAndReportCallback(void (*callback)(const char *));
166 #define VReport(level, ...) \
167 do { \
168 if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
169 } while (0)
170 #define VPrintf(level, ...) \
171 do { \
172 if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
173 } while (0)
174
175 // Can be used to prevent mixing error reports from different sanitizers.
176 extern StaticSpinMutex CommonSanitizerReportMutex;
177
178 struct ReportFile {
179 void Write(const char *buffer, uptr length);
180 bool SupportsColors();
181 void SetReportPath(const char *path);
182
183 // Don't use fields directly. They are only declared public to allow
184 // aggregate initialization.
185
186 // Protects fields below.
187 StaticSpinMutex *mu;
188 // Opened file descriptor. Defaults to stderr. It may be equal to
189 // kInvalidFd, in which case new file will be opened when necessary.
190 fd_t fd;
191 // Path prefix of report file, set via __sanitizer_set_report_path.
192 char path_prefix[kMaxPathLength];
193 // Full path to report, obtained as <path_prefix>.PID
194 char full_path[kMaxPathLength];
195 // PID of the process that opened fd. If a fork() occurs,
196 // the PID of child will be different from fd_pid.
197 uptr fd_pid;
198
199 private:
200 void ReopenIfNecessary();
201 };
202 extern ReportFile report_file;
203
204 extern uptr stoptheworld_tracer_pid;
205 extern uptr stoptheworld_tracer_ppid;
206
207 enum FileAccessMode {
208 RdOnly,
209 WrOnly,
210 RdWr
211 };
212
213 // Returns kInvalidFd on error.
214 fd_t OpenFile(const char *filename, FileAccessMode mode,
215 error_t *errno_p = nullptr);
216 void CloseFile(fd_t);
217
218 // Return true on success, false on error.
219 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size,
220 uptr *bytes_read = nullptr, error_t *error_p = nullptr);
221 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size,
222 uptr *bytes_written = nullptr, error_t *error_p = nullptr);
223
224 bool RenameFile(const char *oldpath, const char *newpath,
225 error_t *error_p = nullptr);
226
227 bool SupportsColoredOutput(fd_t fd);
228
229 // Opens the file 'file_name" and reads up to 'max_len' bytes.
230 // The resulting buffer is mmaped and stored in '*buff'.
231 // The size of the mmaped region is stored in '*buff_size',
232 // Returns the number of read bytes or 0 if file can not be opened.
233 uptr ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
234 uptr max_len, error_t *errno_p = nullptr);
235 // Maps given file to virtual memory, and returns pointer to it
236 // (or NULL if mapping fails). Stores the size of mmaped region
237 // in '*buff_size'.
238 void *MapFileToMemory(const char *file_name, uptr *buff_size);
239 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset);
240
241 bool IsAccessibleMemoryRange(uptr beg, uptr size);
242
243 // Error report formatting.
244 const char *StripPathPrefix(const char *filepath,
245 const char *strip_file_prefix);
246 // Strip the directories from the module name.
247 const char *StripModuleName(const char *module);
248
249 // OS
250 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
251 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
252 const char *GetBinaryBasename();
253 void CacheBinaryName();
254 void DisableCoreDumperIfNecessary();
255 void DumpProcessMap();
256 bool FileExists(const char *filename);
257 const char *GetEnv(const char *name);
258 bool SetEnv(const char *name, const char *value);
259 const char *GetPwd();
260 char *FindPathToBinary(const char *name);
261 bool IsPathSeparator(const char c);
262 bool IsAbsolutePath(const char *path);
263
264 u32 GetUid();
265 void ReExec();
266 bool StackSizeIsUnlimited();
267 void SetStackSizeLimitInBytes(uptr limit);
268 bool AddressSpaceIsUnlimited();
269 void SetAddressSpaceUnlimited();
270 void AdjustStackSize(void *attr);
271 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args);
272 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args);
273 void SetSandboxingCallback(void (*f)());
274
275 void CoverageUpdateMapping();
276 void CovBeforeFork();
277 void CovAfterFork(int child_pid);
278
279 void InitializeCoverage(bool enabled, const char *coverage_dir);
280 void ReInitializeCoverage(bool enabled, const char *coverage_dir);
281
282 void InitTlsSize();
283 uptr GetTlsSize();
284
285 // Other
286 void SleepForSeconds(int seconds);
287 void SleepForMillis(int millis);
288 u64 NanoTime();
289 int Atexit(void (*function)(void));
290 void SortArray(uptr *array, uptr size);
291 bool TemplateMatch(const char *templ, const char *str);
292
293 // Exit
294 void NORETURN Abort();
295 void NORETURN Die();
296 void NORETURN
297 CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
298
299 // Set the name of the current thread to 'name', return true on succees.
300 // The name may be truncated to a system-dependent limit.
301 bool SanitizerSetThreadName(const char *name);
302 // Get the name of the current thread (no more than max_len bytes),
303 // return true on succees. name should have space for at least max_len+1 bytes.
304 bool SanitizerGetThreadName(char *name, int max_len);
305
306 // Specific tools may override behavior of "Die" and "CheckFailed" functions
307 // to do tool-specific job.
308 typedef void (*DieCallbackType)(void);
309 void SetDieCallback(DieCallbackType);
310 void SetUserDieCallback(DieCallbackType);
311 DieCallbackType GetDieCallback();
312 typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
313 u64, u64);
314 void SetCheckFailedCallback(CheckFailedCallbackType callback);
315
316 // Callback will be called if soft_rss_limit_mb is given and the limit is
317 // exceeded (exceeded==true) or if rss went down below the limit
318 // (exceeded==false).
319 // The callback should be registered once at the tool init time.
320 void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded));
321
322 // Functions related to signal handling.
323 typedef void (*SignalHandlerType)(int, void *, void *);
324 bool IsDeadlySignal(int signum);
325 void InstallDeadlySignalHandlers(SignalHandlerType handler);
326 // Alternative signal stack (POSIX-only).
327 void SetAlternateSignalStack();
328 void UnsetAlternateSignalStack();
329
330 // We don't want a summary too long.
331 const int kMaxSummaryLength = 1024;
332 // Construct a one-line string:
333 // SUMMARY: SanitizerToolName: error_message
334 // and pass it to __sanitizer_report_error_summary.
335 void ReportErrorSummary(const char *error_message);
336 // Same as above, but construct error_message as:
337 // error_type file:line[:column][ function]
338 void ReportErrorSummary(const char *error_type, const AddressInfo &info);
339 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
340 void ReportErrorSummary(const char *error_type, StackTrace *trace);
341
342 // Math
343 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
344 extern "C" {
345 unsigned char _BitScanForward(unsigned long *index, unsigned long mask); // NOLINT
346 unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); // NOLINT
347 #if defined(_WIN64)
348 unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); // NOLINT
349 unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); // NOLINT
350 #endif
351 }
352 #endif
353
MostSignificantSetBitIndex(uptr x)354 INLINE uptr MostSignificantSetBitIndex(uptr x) {
355 CHECK_NE(x, 0U);
356 unsigned long up; // NOLINT
357 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
358 # ifdef _WIN64
359 up = SANITIZER_WORDSIZE - 1 - __builtin_clzll(x);
360 # else
361 up = SANITIZER_WORDSIZE - 1 - __builtin_clzl(x);
362 # endif
363 #elif defined(_WIN64)
364 _BitScanReverse64(&up, x);
365 #else
366 _BitScanReverse(&up, x);
367 #endif
368 return up;
369 }
370
LeastSignificantSetBitIndex(uptr x)371 INLINE uptr LeastSignificantSetBitIndex(uptr x) {
372 CHECK_NE(x, 0U);
373 unsigned long up; // NOLINT
374 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
375 # ifdef _WIN64
376 up = __builtin_ctzll(x);
377 # else
378 up = __builtin_ctzl(x);
379 # endif
380 #elif defined(_WIN64)
381 _BitScanForward64(&up, x);
382 #else
383 _BitScanForward(&up, x);
384 #endif
385 return up;
386 }
387
IsPowerOfTwo(uptr x)388 INLINE bool IsPowerOfTwo(uptr x) {
389 return (x & (x - 1)) == 0;
390 }
391
RoundUpToPowerOfTwo(uptr size)392 INLINE uptr RoundUpToPowerOfTwo(uptr size) {
393 CHECK(size);
394 if (IsPowerOfTwo(size)) return size;
395
396 uptr up = MostSignificantSetBitIndex(size);
397 CHECK(size < (1ULL << (up + 1)));
398 CHECK(size > (1ULL << up));
399 return 1ULL << (up + 1);
400 }
401
RoundUpTo(uptr size,uptr boundary)402 INLINE uptr RoundUpTo(uptr size, uptr boundary) {
403 CHECK(IsPowerOfTwo(boundary));
404 return (size + boundary - 1) & ~(boundary - 1);
405 }
406
RoundDownTo(uptr x,uptr boundary)407 INLINE uptr RoundDownTo(uptr x, uptr boundary) {
408 return x & ~(boundary - 1);
409 }
410
IsAligned(uptr a,uptr alignment)411 INLINE bool IsAligned(uptr a, uptr alignment) {
412 return (a & (alignment - 1)) == 0;
413 }
414
Log2(uptr x)415 INLINE uptr Log2(uptr x) {
416 CHECK(IsPowerOfTwo(x));
417 return LeastSignificantSetBitIndex(x);
418 }
419
420 // Don't use std::min, std::max or std::swap, to minimize dependency
421 // on libstdc++.
Min(T a,T b)422 template<class T> T Min(T a, T b) { return a < b ? a : b; }
Max(T a,T b)423 template<class T> T Max(T a, T b) { return a > b ? a : b; }
Swap(T & a,T & b)424 template<class T> void Swap(T& a, T& b) {
425 T tmp = a;
426 a = b;
427 b = tmp;
428 }
429
430 // Char handling
IsSpace(int c)431 INLINE bool IsSpace(int c) {
432 return (c == ' ') || (c == '\n') || (c == '\t') ||
433 (c == '\f') || (c == '\r') || (c == '\v');
434 }
IsDigit(int c)435 INLINE bool IsDigit(int c) {
436 return (c >= '0') && (c <= '9');
437 }
ToLower(int c)438 INLINE int ToLower(int c) {
439 return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
440 }
441
442 // A low-level vector based on mmap. May incur a significant memory overhead for
443 // small vectors.
444 // WARNING: The current implementation supports only POD types.
445 template<typename T>
446 class InternalMmapVectorNoCtor {
447 public:
Initialize(uptr initial_capacity)448 void Initialize(uptr initial_capacity) {
449 capacity_ = Max(initial_capacity, (uptr)1);
450 size_ = 0;
451 data_ = (T *)MmapOrDie(capacity_ * sizeof(T), "InternalMmapVectorNoCtor");
452 }
Destroy()453 void Destroy() {
454 UnmapOrDie(data_, capacity_ * sizeof(T));
455 }
456 T &operator[](uptr i) {
457 CHECK_LT(i, size_);
458 return data_[i];
459 }
460 const T &operator[](uptr i) const {
461 CHECK_LT(i, size_);
462 return data_[i];
463 }
push_back(const T & element)464 void push_back(const T &element) {
465 CHECK_LE(size_, capacity_);
466 if (size_ == capacity_) {
467 uptr new_capacity = RoundUpToPowerOfTwo(size_ + 1);
468 Resize(new_capacity);
469 }
470 data_[size_++] = element;
471 }
back()472 T &back() {
473 CHECK_GT(size_, 0);
474 return data_[size_ - 1];
475 }
pop_back()476 void pop_back() {
477 CHECK_GT(size_, 0);
478 size_--;
479 }
size()480 uptr size() const {
481 return size_;
482 }
data()483 const T *data() const {
484 return data_;
485 }
data()486 T *data() {
487 return data_;
488 }
capacity()489 uptr capacity() const {
490 return capacity_;
491 }
492
clear()493 void clear() { size_ = 0; }
empty()494 bool empty() const { return size() == 0; }
495
496 private:
Resize(uptr new_capacity)497 void Resize(uptr new_capacity) {
498 CHECK_GT(new_capacity, 0);
499 CHECK_LE(size_, new_capacity);
500 T *new_data = (T *)MmapOrDie(new_capacity * sizeof(T),
501 "InternalMmapVector");
502 internal_memcpy(new_data, data_, size_ * sizeof(T));
503 T *old_data = data_;
504 data_ = new_data;
505 UnmapOrDie(old_data, capacity_ * sizeof(T));
506 capacity_ = new_capacity;
507 }
508
509 T *data_;
510 uptr capacity_;
511 uptr size_;
512 };
513
514 template<typename T>
515 class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
516 public:
InternalMmapVector(uptr initial_capacity)517 explicit InternalMmapVector(uptr initial_capacity) {
518 InternalMmapVectorNoCtor<T>::Initialize(initial_capacity);
519 }
~InternalMmapVector()520 ~InternalMmapVector() { InternalMmapVectorNoCtor<T>::Destroy(); }
521 // Disallow evil constructors.
522 InternalMmapVector(const InternalMmapVector&);
523 void operator=(const InternalMmapVector&);
524 };
525
526 // HeapSort for arrays and InternalMmapVector.
527 template<class Container, class Compare>
InternalSort(Container * v,uptr size,Compare comp)528 void InternalSort(Container *v, uptr size, Compare comp) {
529 if (size < 2)
530 return;
531 // Stage 1: insert elements to the heap.
532 for (uptr i = 1; i < size; i++) {
533 uptr j, p;
534 for (j = i; j > 0; j = p) {
535 p = (j - 1) / 2;
536 if (comp((*v)[p], (*v)[j]))
537 Swap((*v)[j], (*v)[p]);
538 else
539 break;
540 }
541 }
542 // Stage 2: swap largest element with the last one,
543 // and sink the new top.
544 for (uptr i = size - 1; i > 0; i--) {
545 Swap((*v)[0], (*v)[i]);
546 uptr j, max_ind;
547 for (j = 0; j < i; j = max_ind) {
548 uptr left = 2 * j + 1;
549 uptr right = 2 * j + 2;
550 max_ind = j;
551 if (left < i && comp((*v)[max_ind], (*v)[left]))
552 max_ind = left;
553 if (right < i && comp((*v)[max_ind], (*v)[right]))
554 max_ind = right;
555 if (max_ind != j)
556 Swap((*v)[j], (*v)[max_ind]);
557 else
558 break;
559 }
560 }
561 }
562
563 template<class Container, class Value, class Compare>
InternalBinarySearch(const Container & v,uptr first,uptr last,const Value & val,Compare comp)564 uptr InternalBinarySearch(const Container &v, uptr first, uptr last,
565 const Value &val, Compare comp) {
566 uptr not_found = last + 1;
567 while (last >= first) {
568 uptr mid = (first + last) / 2;
569 if (comp(v[mid], val))
570 first = mid + 1;
571 else if (comp(val, v[mid]))
572 last = mid - 1;
573 else
574 return mid;
575 }
576 return not_found;
577 }
578
579 // Represents a binary loaded into virtual memory (e.g. this can be an
580 // executable or a shared object).
581 class LoadedModule {
582 public:
LoadedModule()583 LoadedModule() : full_name_(nullptr), base_address_(0) { ranges_.clear(); }
584 void set(const char *module_name, uptr base_address);
585 void clear();
586 void addAddressRange(uptr beg, uptr end, bool executable);
587 bool containsAddress(uptr address) const;
588
full_name()589 const char *full_name() const { return full_name_; }
base_address()590 uptr base_address() const { return base_address_; }
591
592 struct AddressRange {
593 AddressRange *next;
594 uptr beg;
595 uptr end;
596 bool executable;
597
AddressRangeAddressRange598 AddressRange(uptr beg, uptr end, bool executable)
599 : next(nullptr), beg(beg), end(end), executable(executable) {}
600 };
601
602 typedef IntrusiveList<AddressRange>::ConstIterator Iterator;
ranges()603 Iterator ranges() const { return Iterator(&ranges_); }
604
605 private:
606 char *full_name_; // Owned.
607 uptr base_address_;
608 IntrusiveList<AddressRange> ranges_;
609 };
610
611 // OS-dependent function that fills array with descriptions of at most
612 // "max_modules" currently loaded modules. Returns the number of
613 // initialized modules. If filter is nonzero, ignores modules for which
614 // filter(full_name) is false.
615 typedef bool (*string_predicate_t)(const char *);
616 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
617 string_predicate_t filter);
618
619 // Callback type for iterating over a set of memory ranges.
620 typedef void (*RangeIteratorCallback)(uptr begin, uptr end, void *arg);
621
622 enum AndroidApiLevel {
623 ANDROID_NOT_ANDROID = 0,
624 ANDROID_KITKAT = 19,
625 ANDROID_LOLLIPOP_MR1 = 22,
626 ANDROID_POST_LOLLIPOP = 23
627 };
628
629 #if SANITIZER_ANDROID
630 // Initialize Android logging. Any writes before this are silently lost.
631 void AndroidLogInit();
632 void AndroidLogWrite(const char *buffer);
633 void GetExtraActivationFlags(char *buf, uptr size);
634 void SanitizerInitializeUnwinder();
635 AndroidApiLevel AndroidGetApiLevel();
636 #else
AndroidLogInit()637 INLINE void AndroidLogInit() {}
AndroidLogWrite(const char * buffer_unused)638 INLINE void AndroidLogWrite(const char *buffer_unused) {}
GetExtraActivationFlags(char * buf,uptr size)639 INLINE void GetExtraActivationFlags(char *buf, uptr size) { *buf = '\0'; }
SanitizerInitializeUnwinder()640 INLINE void SanitizerInitializeUnwinder() {}
AndroidGetApiLevel()641 INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
642 #endif
643
GetPthreadDestructorIterations()644 INLINE uptr GetPthreadDestructorIterations() {
645 #if SANITIZER_ANDROID
646 return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
647 #elif SANITIZER_POSIX
648 return 4;
649 #else
650 // Unused on Windows.
651 return 0;
652 #endif
653 }
654
655 void *internal_start_thread(void(*func)(void*), void *arg);
656 void internal_join_thread(void *th);
657 void MaybeStartBackgroudThread();
658
659 // Make the compiler think that something is going on there.
660 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
661 // compiler from recognising it and turning it into an actual call to
662 // memset/memcpy/etc.
SanitizerBreakOptimization(void * arg)663 static inline void SanitizerBreakOptimization(void *arg) {
664 #if _MSC_VER && !defined(__clang__)
665 _ReadWriteBarrier();
666 #else
667 __asm__ __volatile__("" : : "r" (arg) : "memory");
668 #endif
669 }
670
671 struct SignalContext {
672 void *context;
673 uptr addr;
674 uptr pc;
675 uptr sp;
676 uptr bp;
677
SignalContextSignalContext678 SignalContext(void *context, uptr addr, uptr pc, uptr sp, uptr bp) :
679 context(context), addr(addr), pc(pc), sp(sp), bp(bp) {
680 }
681
682 // Creates signal context in a platform-specific manner.
683 static SignalContext Create(void *siginfo, void *context);
684 };
685
686 void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp);
687
688 } // namespace __sanitizer
689
new(__sanitizer::operator_new_size_type size,__sanitizer::LowLevelAllocator & alloc)690 inline void *operator new(__sanitizer::operator_new_size_type size,
691 __sanitizer::LowLevelAllocator &alloc) {
692 return alloc.Allocate(size);
693 }
694
695 struct StackDepotStats {
696 uptr n_uniq_ids;
697 uptr allocated;
698 };
699
700 #endif // SANITIZER_COMMON_H
701