sanitizer_common.h revision 2673fd8406197c42f16cede6d287f72169298c2e
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
21namespace __sanitizer {
22struct StackTrace;
23
24// Constants.
25const uptr kWordSize = SANITIZER_WORDSIZE / 8;
26const uptr kWordSizeInBits = 8 * kWordSize;
27
28#if defined(__powerpc__) || defined(__powerpc64__)
29const uptr kCacheLineSize = 128;
30#else
31const uptr kCacheLineSize = 64;
32#endif
33
34extern const char *SanitizerToolName;  // Can be changed by the tool.
35
36uptr GetPageSize();
37uptr GetPageSizeCached();
38uptr GetMmapGranularity();
39// Threads
40int GetPid();
41uptr GetTid();
42uptr GetThreadSelf();
43void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
44                                uptr *stack_bottom);
45
46// Memory management
47void *MmapOrDie(uptr size, const char *mem_type);
48void UnmapOrDie(void *addr, uptr size);
49void *MmapFixedNoReserve(uptr fixed_addr, uptr size);
50void *MmapFixedOrDie(uptr fixed_addr, uptr size);
51void *Mprotect(uptr fixed_addr, uptr size);
52// Map aligned chunk of address space; size and alignment are powers of two.
53void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type);
54// Used to check if we can map shadow memory to a fixed location.
55bool MemoryRangeIsAvailable(uptr range_start, uptr range_end);
56void FlushUnneededShadowMemory(uptr addr, uptr size);
57
58// Internal allocator
59void *InternalAlloc(uptr size);
60void InternalFree(void *p);
61
62// InternalScopedBuffer can be used instead of large stack arrays to
63// keep frame size low.
64// FIXME: use InternalAlloc instead of MmapOrDie once
65// InternalAlloc is made libc-free.
66template<typename T>
67class InternalScopedBuffer {
68 public:
69  explicit InternalScopedBuffer(uptr cnt) {
70    cnt_ = cnt;
71    ptr_ = (T*)MmapOrDie(cnt * sizeof(T), "InternalScopedBuffer");
72  }
73  ~InternalScopedBuffer() {
74    UnmapOrDie(ptr_, cnt_ * sizeof(T));
75  }
76  T &operator[](uptr i) { return ptr_[i]; }
77  T *data() { return ptr_; }
78  uptr size() { return cnt_ * sizeof(T); }
79
80 private:
81  T *ptr_;
82  uptr cnt_;
83  // Disallow evil constructors.
84  InternalScopedBuffer(const InternalScopedBuffer&);
85  void operator=(const InternalScopedBuffer&);
86};
87
88// Simple low-level (mmap-based) allocator for internal use. Doesn't have
89// constructor, so all instances of LowLevelAllocator should be
90// linker initialized.
91class LowLevelAllocator {
92 public:
93  // Requires an external lock.
94  void *Allocate(uptr size);
95 private:
96  char *allocated_end_;
97  char *allocated_current_;
98};
99typedef void (*LowLevelAllocateCallback)(uptr ptr, uptr size);
100// Allows to register tool-specific callbacks for LowLevelAllocator.
101// Passing NULL removes the callback.
102void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback);
103
104// IO
105void RawWrite(const char *buffer);
106bool PrintsToTty();
107void Printf(const char *format, ...);
108void Report(const char *format, ...);
109void SetPrintfAndReportCallback(void (*callback)(const char *));
110
111fd_t OpenFile(const char *filename, bool write);
112// Opens the file 'file_name" and reads up to 'max_len' bytes.
113// The resulting buffer is mmaped and stored in '*buff'.
114// The size of the mmaped region is stored in '*buff_size',
115// Returns the number of read bytes or 0 if file can not be opened.
116uptr ReadFileToBuffer(const char *file_name, char **buff,
117                      uptr *buff_size, uptr max_len);
118// Maps given file to virtual memory, and returns pointer to it
119// (or NULL if the mapping failes). Stores the size of mmaped region
120// in '*buff_size'.
121void *MapFileToMemory(const char *file_name, uptr *buff_size);
122
123// OS
124void DisableCoreDumper();
125void DumpProcessMap();
126bool FileExists(const char *filename);
127const char *GetEnv(const char *name);
128const char *GetPwd();
129void ReExec();
130bool StackSizeIsUnlimited();
131void SetStackSizeLimitInBytes(uptr limit);
132void PrepareForSandboxing();
133
134// Other
135void SleepForSeconds(int seconds);
136void SleepForMillis(int millis);
137int Atexit(void (*function)(void));
138void SortArray(uptr *array, uptr size);
139
140// Exit
141void NORETURN Abort();
142void NORETURN Exit(int exitcode);
143void NORETURN Die();
144void NORETURN SANITIZER_INTERFACE_ATTRIBUTE
145CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2);
146
147// Set the name of the current thread to 'name', return true on succees.
148// The name may be truncated to a system-dependent limit.
149bool SanitizerSetThreadName(const char *name);
150// Get the name of the current thread (no more than max_len bytes),
151// return true on succees. name should have space for at least max_len+1 bytes.
152bool SanitizerGetThreadName(char *name, int max_len);
153
154// Specific tools may override behavior of "Die" and "CheckFailed" functions
155// to do tool-specific job.
156void SetDieCallback(void (*callback)(void));
157typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
158                                       u64, u64);
159void SetCheckFailedCallback(CheckFailedCallbackType callback);
160
161// Construct a one-line string like
162//  SanitizerToolName: error_type file:line function
163// and call __sanitizer_report_error_summary on it.
164void ReportErrorSummary(const char *error_type, const char *file,
165                        int line, const char *function);
166
167// Math
168INLINE bool IsPowerOfTwo(uptr x) {
169  return (x & (x - 1)) == 0;
170}
171INLINE uptr RoundUpTo(uptr size, uptr boundary) {
172  CHECK(IsPowerOfTwo(boundary));
173  return (size + boundary - 1) & ~(boundary - 1);
174}
175INLINE uptr RoundDownTo(uptr x, uptr boundary) {
176  return x & ~(boundary - 1);
177}
178INLINE bool IsAligned(uptr a, uptr alignment) {
179  return (a & (alignment - 1)) == 0;
180}
181// Don't use std::min, std::max or std::swap, to minimize dependency
182// on libstdc++.
183template<class T> T Min(T a, T b) { return a < b ? a : b; }
184template<class T> T Max(T a, T b) { return a > b ? a : b; }
185template<class T> void Swap(T& a, T& b) {
186  T tmp = a;
187  a = b;
188  b = tmp;
189}
190
191// Char handling
192INLINE bool IsSpace(int c) {
193  return (c == ' ') || (c == '\n') || (c == '\t') ||
194         (c == '\f') || (c == '\r') || (c == '\v');
195}
196INLINE bool IsDigit(int c) {
197  return (c >= '0') && (c <= '9');
198}
199INLINE int ToLower(int c) {
200  return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
201}
202
203#if SANITIZER_WORDSIZE == 64
204# define FIRST_32_SECOND_64(a, b) (b)
205#else
206# define FIRST_32_SECOND_64(a, b) (a)
207#endif
208
209}  // namespace __sanitizer
210
211#endif  // SANITIZER_COMMON_H
212