asan_internal.h revision 469a1ab32f53b8fd7cde76211565ce577dfb8f14
1//===-- asan_internal.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 a part of AddressSanitizer, an address sanity checker.
11//
12// ASan-private header which defines various general utilities.
13//===----------------------------------------------------------------------===//
14#ifndef ASAN_INTERNAL_H
15#define ASAN_INTERNAL_H
16
17#if !defined(__linux__) && !defined(__APPLE__) && !defined(_WIN32)
18# error "This operating system is not supported by AddressSanitizer"
19#endif
20
21#include <stddef.h>  // for size_t, uintptr_t, etc.
22
23#if defined(_WIN32)
24// There's no <stdint.h> in Visual Studio 9, so we have to define [u]int*_t.
25typedef unsigned __int8  uint8_t;
26typedef unsigned __int16 uint16_t;
27typedef unsigned __int32 uint32_t;
28typedef unsigned __int64 uint64_t;
29typedef __int8           int8_t;
30typedef __int16          int16_t;
31typedef __int32          int32_t;
32typedef __int64          int64_t;
33typedef unsigned long    DWORD;  // NOLINT
34
35extern "C" void* _ReturnAddress(void);
36# pragma intrinsic(_ReturnAddress)
37
38# define ALIAS(x)   // TODO(timurrrr): do we need this on Windows?
39# define ALIGNED(x) __declspec(align(x))
40# define NOINLINE __declspec(noinline)
41# define NORETURN __declspec(noreturn)
42
43# define ASAN_INTERFACE_ATTRIBUTE  // TODO(timurrrr): do we need this on Win?
44#else  // defined(_WIN32)
45# include <stdint.h>  // for __WORDSIZE
46
47# define ALIAS(x) __attribute__((alias(x)))
48# define ALIGNED(x) __attribute__((aligned(x)))
49# define NOINLINE __attribute__((noinline))
50# define NORETURN  // FIXME: should be __attribute__((noreturn)), revisit later.
51
52# define ASAN_INTERFACE_ATTRIBUTE __attribute__((visibility("default")))
53#endif  // defined(_WIN32)
54
55// If __WORDSIZE was undefined by the platform, define it in terms of the
56// compiler built-ins __LP64__ and _WIN64.
57#ifndef __WORDSIZE
58#if __LP64__ || defined(_WIN64)
59#define __WORDSIZE 64
60#else
61#define __WORDSIZE 32
62#endif
63#endif
64
65// Limits for integral types. We have to redefine it in case we don't
66// have stdint.h (like in Visual Studio 9).
67#if __WORDSIZE == 64
68# define __INT64_C(c)  c ## L
69# define __UINT64_C(c) c ## UL
70#else
71# define __INT64_C(c)  c ## LL
72# define __UINT64_C(c) c ## ULL
73#endif  // __WORDSIZE == 64
74#undef INT32_MIN
75#define INT32_MIN              (-2147483647-1)
76#undef INT32_MAX
77#define INT32_MAX              (2147483647)
78#undef UINT32_MAX
79#define UINT32_MAX             (4294967295U)
80#undef INT64_MIN
81#define INT64_MIN              (-__INT64_C(9223372036854775807)-1)
82#undef INT64_MAX
83#define INT64_MAX              (__INT64_C(9223372036854775807))
84#undef UINT64_MAX
85#define UINT64_MAX             (__UINT64_C(18446744073709551615))
86
87#define ASAN_DEFAULT_FAILURE_EXITCODE 1
88
89#if defined(__linux__)
90# define ASAN_LINUX   1
91#else
92# define ASAN_LINUX   0
93#endif
94
95#if defined(__APPLE__)
96# define ASAN_MAC     1
97#else
98# define ASAN_MAC     0
99#endif
100
101#if defined(_WIN32)
102# define ASAN_WINDOWS 1
103#else
104# define ASAN_WINDOWS 0
105#endif
106
107#if !defined(__has_feature)
108#define __has_feature(x) 0
109#endif
110
111#if defined(__has_feature) && __has_feature(address_sanitizer)
112# error "The AddressSanitizer run-time should not be"
113        " instrumented by AddressSanitizer"
114#endif
115
116// Build-time configuration options.
117
118// If set, asan will install its own SEGV signal handler.
119#ifndef ASAN_NEEDS_SEGV
120# define ASAN_NEEDS_SEGV 1
121#endif
122
123// If set, asan will intercept C++ exception api call(s).
124#ifndef ASAN_HAS_EXCEPTIONS
125# define ASAN_HAS_EXCEPTIONS 1
126#endif
127
128// If set, asan uses the values of SHADOW_SCALE and SHADOW_OFFSET
129// provided by the instrumented objects. Otherwise constants are used.
130#ifndef ASAN_FLEXIBLE_MAPPING_AND_OFFSET
131# define ASAN_FLEXIBLE_MAPPING_AND_OFFSET 0
132#endif
133
134// If set, values like allocator chunk size, as well as defaults for some flags
135// will be changed towards less memory overhead.
136#ifndef ASAN_LOW_MEMORY
137# define ASAN_LOW_MEMORY 0
138#endif
139
140// All internal functions in asan reside inside the __asan namespace
141// to avoid namespace collisions with the user programs.
142// Seperate namespace also makes it simpler to distinguish the asan run-time
143// functions from the instrumented user code in a profile.
144namespace __asan {
145
146class AsanThread;
147struct AsanStackTrace;
148
149// asan_rtl.cc
150void NORETURN CheckFailed(const char *cond, const char *file, int line);
151void NORETURN ShowStatsAndAbort();
152
153// asan_globals.cc
154bool DescribeAddrIfGlobal(uintptr_t addr);
155
156// asan_malloc_linux.cc / asan_malloc_mac.cc
157void ReplaceSystemMalloc();
158
159void OutOfMemoryMessageAndDie(const char *mem_type, size_t size);
160
161// asan_linux.cc / asan_mac.cc / asan_win.cc
162void *AsanDoesNotSupportStaticLinkage();
163bool AsanShadowRangeIsAvailable();
164int AsanOpenReadonly(const char* filename);
165const char *AsanGetEnv(const char *name);
166void AsanDumpProcessMap();
167
168void *AsanMmapFixedNoReserve(uintptr_t fixed_addr, size_t size);
169void *AsanMmapFixedReserve(uintptr_t fixed_addr, size_t size);
170void *AsanMprotect(uintptr_t fixed_addr, size_t size);
171void *AsanMmapSomewhereOrDie(size_t size, const char *where);
172void AsanUnmapOrDie(void *ptr, size_t size);
173
174void AsanDisableCoreDumper();
175void GetPcSpBp(void *context, uintptr_t *pc, uintptr_t *sp, uintptr_t *bp);
176
177size_t AsanRead(int fd, void *buf, size_t count);
178size_t AsanWrite(int fd, const void *buf, size_t count);
179int AsanClose(int fd);
180
181bool AsanInterceptsSignal(int signum);
182void InstallSignalHandlers();
183int GetPid();
184uintptr_t GetThreadSelf();
185int AtomicInc(int *a);
186
187// Wrapper for TLS/TSD.
188void AsanTSDInit(void (*destructor)(void *tsd));
189void *AsanTSDGet();
190void AsanTSDSet(void *tsd);
191
192// Opens the file 'file_name" and reads up to 'max_len' bytes.
193// The resulting buffer is mmaped and stored in '*buff'.
194// The size of the mmaped region is stored in '*buff_size',
195// Returns the number of read bytes or 0 if file can not be opened.
196size_t ReadFileToBuffer(const char *file_name, char **buff,
197                        size_t *buff_size, size_t max_len);
198
199// asan_printf.cc
200void RawWrite(const char *buffer);
201int SNPrintf(char *buffer, size_t length, const char *format, ...);
202void Printf(const char *format, ...);
203int SScanf(const char *str, const char *format, ...);
204void Report(const char *format, ...);
205
206// Don't use std::min and std::max, to minimize dependency on libstdc++.
207template<class T> T Min(T a, T b) { return a < b ? a : b; }
208template<class T> T Max(T a, T b) { return a > b ? a : b; }
209
210void SortArray(uintptr_t *array, size_t size);
211
212// asan_poisoning.cc
213// Poisons the shadow memory for "size" bytes starting from "addr".
214void PoisonShadow(uintptr_t addr, size_t size, uint8_t value);
215// Poisons the shadow memory for "redzone_size" bytes starting from
216// "addr + size".
217void PoisonShadowPartialRightRedzone(uintptr_t addr,
218                                     uintptr_t size,
219                                     uintptr_t redzone_size,
220                                     uint8_t value);
221
222extern size_t FLAG_quarantine_size;
223extern int    FLAG_demangle;
224extern bool   FLAG_symbolize;
225extern int    FLAG_v;
226extern size_t FLAG_redzone;
227extern int    FLAG_debug;
228extern bool   FLAG_poison_shadow;
229extern int    FLAG_report_globals;
230extern size_t FLAG_malloc_context_size;
231extern bool   FLAG_replace_str;
232extern bool   FLAG_replace_intrin;
233extern bool   FLAG_replace_cfallocator;
234extern bool   FLAG_fast_unwind;
235extern bool   FLAG_use_fake_stack;
236extern size_t FLAG_max_malloc_fill_size;
237extern int    FLAG_exitcode;
238extern bool   FLAG_allow_user_poisoning;
239extern int    FLAG_sleep_before_dying;
240extern bool   FLAG_handle_segv;
241
242extern int asan_inited;
243// Used to avoid infinite recursion in __asan_init().
244extern bool asan_init_is_running;
245
246enum LinkerInitialized { LINKER_INITIALIZED = 0 };
247
248void NORETURN AsanDie();
249void SleepForSeconds(int seconds);
250void NORETURN Exit(int exitcode);
251int Atexit(void (*function)(void));
252
253#define CHECK(cond) do { if (!(cond)) { \
254  CheckFailed(#cond, __FILE__, __LINE__); \
255}}while(0)
256
257#define RAW_CHECK_MSG(expr, msg) do { \
258  if (!(expr)) { \
259    RawWrite(msg); \
260    AsanDie(); \
261  } \
262} while (0)
263
264#define RAW_CHECK(expr) RAW_CHECK_MSG(expr, #expr)
265
266#define UNIMPLEMENTED() CHECK("unimplemented" && 0)
267
268#define ASAN_ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
269
270const size_t kWordSize = __WORDSIZE / 8;
271const size_t kWordSizeInBits = 8 * kWordSize;
272const size_t kPageSizeBits = 12;
273const size_t kPageSize = 1UL << kPageSizeBits;
274
275#ifndef _WIN32
276const size_t kMmapGranularity = kPageSize;
277# define GET_CALLER_PC() (uintptr_t)__builtin_return_address(0)
278# define GET_CURRENT_FRAME() (uintptr_t)__builtin_frame_address(0)
279# define THREAD_CALLING_CONV
280typedef void* thread_return_t;
281#else
282const size_t kMmapGranularity = 1UL << 16;
283# define GET_CALLER_PC() (uintptr_t)_ReturnAddress()
284// CaptureStackBackTrace doesn't need to know BP on Windows.
285// FIXME: This macro is still used when printing error reports though it's not
286// clear if the BP value is needed in the ASan reports on Windows.
287# define GET_CURRENT_FRAME() (uintptr_t)0xDEADBEEF
288# define THREAD_CALLING_CONV __stdcall
289typedef DWORD thread_return_t;
290
291# ifndef ASAN_USE_EXTERNAL_SYMBOLIZER
292#  define ASAN_USE_EXTERNAL_SYMBOLIZER __asan::WinSymbolize
293bool WinSymbolize(const void *addr, char *out_buffer, int buffer_size);
294# endif
295#endif
296
297typedef thread_return_t (THREAD_CALLING_CONV *thread_callback_t)(void* arg);
298
299#define GET_BP_PC_SP \
300  uintptr_t bp = GET_CURRENT_FRAME();              \
301  uintptr_t pc = GET_CALLER_PC();                  \
302  uintptr_t local_stack;                           \
303  uintptr_t sp = (uintptr_t)&local_stack;
304
305// These magic values are written to shadow for better error reporting.
306const int kAsanHeapLeftRedzoneMagic = 0xfa;
307const int kAsanHeapRightRedzoneMagic = 0xfb;
308const int kAsanHeapFreeMagic = 0xfd;
309const int kAsanStackLeftRedzoneMagic = 0xf1;
310const int kAsanStackMidRedzoneMagic = 0xf2;
311const int kAsanStackRightRedzoneMagic = 0xf3;
312const int kAsanStackPartialRedzoneMagic = 0xf4;
313const int kAsanStackAfterReturnMagic = 0xf5;
314const int kAsanUserPoisonedMemoryMagic = 0xf7;
315const int kAsanGlobalRedzoneMagic = 0xf9;
316const int kAsanInternalHeapMagic = 0xfe;
317
318static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
319static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
320
321// --------------------------- Bit twiddling ------- {{{1
322inline bool IsPowerOfTwo(size_t x) {
323  return (x & (x - 1)) == 0;
324}
325
326inline size_t RoundUpTo(size_t size, size_t boundary) {
327  CHECK(IsPowerOfTwo(boundary));
328  return (size + boundary - 1) & ~(boundary - 1);
329}
330
331// -------------------------- LowLevelAllocator ----- {{{1
332// A simple low-level memory allocator for internal use.
333class LowLevelAllocator {
334 public:
335  explicit LowLevelAllocator(LinkerInitialized) {}
336  // 'size' must be a power of two.
337  // Requires an external lock.
338  void *Allocate(size_t size);
339 private:
340  char *allocated_end_;
341  char *allocated_current_;
342};
343
344}  // namespace __asan
345
346#endif  // ASAN_INTERNAL_H
347