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