asan_interceptors.cc revision 6c70a55a52827b2415263a0be2767672a703cd63
1//===-- asan_interceptors.cc ----------------------------------------------===//
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// Intercept various libc functions.
13//===----------------------------------------------------------------------===//
14#include "asan_interceptors.h"
15
16#include "asan_allocator.h"
17#include "asan_intercepted_functions.h"
18#include "asan_internal.h"
19#include "asan_mapping.h"
20#include "asan_poisoning.h"
21#include "asan_report.h"
22#include "asan_stack.h"
23#include "asan_stats.h"
24#include "interception/interception.h"
25#include "sanitizer_common/sanitizer_libc.h"
26
27namespace __asan {
28
29// Return true if we can quickly decide that the region is unpoisoned.
30static inline bool QuickCheckForUnpoisonedRegion(uptr beg, uptr size) {
31  if (size == 0) return true;
32  if (size <= 32)
33    return !AddressIsPoisoned(beg) &&
34           !AddressIsPoisoned(beg + size - 1) &&
35           !AddressIsPoisoned(beg + size / 2);
36  return false;
37}
38
39// We implement ACCESS_MEMORY_RANGE, ASAN_READ_RANGE,
40// and ASAN_WRITE_RANGE as macro instead of function so
41// that no extra frames are created, and stack trace contains
42// relevant information only.
43// We check all shadow bytes.
44#define ACCESS_MEMORY_RANGE(offset, size, isWrite) do {                 \
45    uptr __offset = (uptr)(offset);                                     \
46    uptr __size = (uptr)(size);                                         \
47    uptr __bad = 0;                                                     \
48    if (!QuickCheckForUnpoisonedRegion(__offset, __size) &&             \
49        (__bad = __asan_region_is_poisoned(__offset, __size))) {        \
50      GET_CURRENT_PC_BP_SP;                                             \
51      __asan_report_error(pc, bp, sp, __bad, isWrite, __size);          \
52    }                                                                   \
53  } while (0)
54
55#define ASAN_READ_RANGE(offset, size) ACCESS_MEMORY_RANGE(offset, size, false)
56#define ASAN_WRITE_RANGE(offset, size) ACCESS_MEMORY_RANGE(offset, size, true)
57
58// Behavior of functions like "memcpy" or "strcpy" is undefined
59// if memory intervals overlap. We report error in this case.
60// Macro is used to avoid creation of new frames.
61static inline bool RangesOverlap(const char *offset1, uptr length1,
62                                 const char *offset2, uptr length2) {
63  return !((offset1 + length1 <= offset2) || (offset2 + length2 <= offset1));
64}
65#define CHECK_RANGES_OVERLAP(name, _offset1, length1, _offset2, length2) do { \
66  const char *offset1 = (const char*)_offset1; \
67  const char *offset2 = (const char*)_offset2; \
68  if (RangesOverlap(offset1, length1, offset2, length2)) { \
69    GET_STACK_TRACE_FATAL_HERE; \
70    ReportStringFunctionMemoryRangesOverlap(name, offset1, length1, \
71                                            offset2, length2, &stack); \
72  } \
73} while (0)
74
75#define ENSURE_ASAN_INITED() do { \
76  CHECK(!asan_init_is_running); \
77  if (!asan_inited) { \
78    __asan_init(); \
79  } \
80} while (0)
81
82static inline uptr MaybeRealStrnlen(const char *s, uptr maxlen) {
83#if ASAN_INTERCEPT_STRNLEN
84  if (REAL(strnlen) != 0) {
85    return REAL(strnlen)(s, maxlen);
86  }
87#endif
88  return internal_strnlen(s, maxlen);
89}
90
91void SetThreadName(const char *name) {
92  AsanThread *t = GetCurrentThread();
93  if (t)
94    asanThreadRegistry().SetThreadName(t->tid(), name);
95}
96
97}  // namespace __asan
98
99// ---------------------- Wrappers ---------------- {{{1
100using namespace __asan;  // NOLINT
101
102DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr)
103DECLARE_REAL_AND_INTERCEPTOR(void, free, void *)
104
105#define COMMON_INTERCEPTOR_UNPOISON_PARAM(ctx, count) \
106  do {                                                \
107  } while (false)
108#define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
109  ASAN_WRITE_RANGE(ptr, size)
110#define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) ASAN_READ_RANGE(ptr, size)
111#define COMMON_INTERCEPTOR_ENTER(ctx, func, ...)              \
112  do {                                                        \
113    if (asan_init_is_running) return REAL(func)(__VA_ARGS__); \
114    ctx = 0;                                                  \
115    (void) ctx;                                               \
116    ENSURE_ASAN_INITED();                                     \
117  } while (false)
118#define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
119  do {                                         \
120  } while (false)
121#define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
122  do {                                         \
123  } while (false)
124#define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
125  do {                                                      \
126  } while (false)
127#define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) SetThreadName(name)
128#define COMMON_INTERCEPTOR_BLOCK_REAL(name) REAL(name)
129#include "sanitizer_common/sanitizer_common_interceptors.inc"
130
131#define COMMON_SYSCALL_PRE_READ_RANGE(p, s) ASAN_READ_RANGE(p, s)
132#define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) ASAN_WRITE_RANGE(p, s)
133#define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
134  do {                                       \
135  } while (false)
136#define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
137  do {                                        \
138  } while (false)
139#include "sanitizer_common/sanitizer_common_syscalls.inc"
140
141static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
142  AsanThread *t = (AsanThread*)arg;
143  SetCurrentThread(t);
144  return t->ThreadStart(GetTid());
145}
146
147#if ASAN_INTERCEPT_PTHREAD_CREATE
148extern "C" int pthread_attr_getdetachstate(void *attr, int *v);
149
150INTERCEPTOR(int, pthread_create, void *thread,
151    void *attr, void *(*start_routine)(void*), void *arg) {
152  EnsureMainThreadIDIsCorrect();
153  // Strict init-order checking in thread-hostile.
154  if (flags()->strict_init_order)
155    StopInitOrderChecking();
156  GET_STACK_TRACE_THREAD;
157  int detached = 0;
158  if (attr != 0)
159    pthread_attr_getdetachstate(attr, &detached);
160
161  u32 current_tid = GetCurrentTidOrInvalid();
162  AsanThread *t = AsanThread::Create(start_routine, arg);
163  CreateThreadContextArgs args = { t, &stack };
164  asanThreadRegistry().CreateThread(*(uptr*)t, detached, current_tid, &args);
165  return REAL(pthread_create)(thread, attr, asan_thread_start, t);
166}
167#endif  // ASAN_INTERCEPT_PTHREAD_CREATE
168
169#if ASAN_INTERCEPT_SIGNAL_AND_SIGACTION
170INTERCEPTOR(void*, signal, int signum, void *handler) {
171  if (!AsanInterceptsSignal(signum) || flags()->allow_user_segv_handler) {
172    return REAL(signal)(signum, handler);
173  }
174  return 0;
175}
176
177INTERCEPTOR(int, sigaction, int signum, const struct sigaction *act,
178                            struct sigaction *oldact) {
179  if (!AsanInterceptsSignal(signum) || flags()->allow_user_segv_handler) {
180    return REAL(sigaction)(signum, act, oldact);
181  }
182  return 0;
183}
184#elif SANITIZER_POSIX
185// We need to have defined REAL(sigaction) on posix systems.
186DEFINE_REAL(int, sigaction, int signum, const struct sigaction *act,
187    struct sigaction *oldact)
188#endif  // ASAN_INTERCEPT_SIGNAL_AND_SIGACTION
189
190#if ASAN_INTERCEPT_SWAPCONTEXT
191static void ClearShadowMemoryForContextStack(uptr stack, uptr ssize) {
192  // Align to page size.
193  uptr PageSize = GetPageSizeCached();
194  uptr bottom = stack & ~(PageSize - 1);
195  ssize += stack - bottom;
196  ssize = RoundUpTo(ssize, PageSize);
197  static const uptr kMaxSaneContextStackSize = 1 << 22;  // 4 Mb
198  if (ssize && ssize <= kMaxSaneContextStackSize) {
199    PoisonShadow(bottom, ssize, 0);
200  }
201}
202
203INTERCEPTOR(int, swapcontext, struct ucontext_t *oucp,
204            struct ucontext_t *ucp) {
205  static bool reported_warning = false;
206  if (!reported_warning) {
207    Report("WARNING: ASan doesn't fully support makecontext/swapcontext "
208           "functions and may produce false positives in some cases!\n");
209    reported_warning = true;
210  }
211  // Clear shadow memory for new context (it may share stack
212  // with current context).
213  uptr stack, ssize;
214  ReadContextStack(ucp, &stack, &ssize);
215  ClearShadowMemoryForContextStack(stack, ssize);
216  int res = REAL(swapcontext)(oucp, ucp);
217  // swapcontext technically does not return, but program may swap context to
218  // "oucp" later, that would look as if swapcontext() returned 0.
219  // We need to clear shadow for ucp once again, as it may be in arbitrary
220  // state.
221  ClearShadowMemoryForContextStack(stack, ssize);
222  return res;
223}
224#endif  // ASAN_INTERCEPT_SWAPCONTEXT
225
226INTERCEPTOR(void, longjmp, void *env, int val) {
227  __asan_handle_no_return();
228  REAL(longjmp)(env, val);
229}
230
231#if ASAN_INTERCEPT__LONGJMP
232INTERCEPTOR(void, _longjmp, void *env, int val) {
233  __asan_handle_no_return();
234  REAL(_longjmp)(env, val);
235}
236#endif
237
238#if ASAN_INTERCEPT_SIGLONGJMP
239INTERCEPTOR(void, siglongjmp, void *env, int val) {
240  __asan_handle_no_return();
241  REAL(siglongjmp)(env, val);
242}
243#endif
244
245#if ASAN_INTERCEPT___CXA_THROW
246INTERCEPTOR(void, __cxa_throw, void *a, void *b, void *c) {
247  CHECK(REAL(__cxa_throw));
248  __asan_handle_no_return();
249  REAL(__cxa_throw)(a, b, c);
250}
251#endif
252
253// intercept mlock and friends.
254// Since asan maps 16T of RAM, mlock is completely unfriendly to asan.
255// All functions return 0 (success).
256static void MlockIsUnsupported() {
257  static bool printed = false;
258  if (printed) return;
259  printed = true;
260  if (flags()->verbosity > 0) {
261    Printf("INFO: AddressSanitizer ignores "
262           "mlock/mlockall/munlock/munlockall\n");
263  }
264}
265
266INTERCEPTOR(int, mlock, const void *addr, uptr len) {
267  MlockIsUnsupported();
268  return 0;
269}
270
271INTERCEPTOR(int, munlock, const void *addr, uptr len) {
272  MlockIsUnsupported();
273  return 0;
274}
275
276INTERCEPTOR(int, mlockall, int flags) {
277  MlockIsUnsupported();
278  return 0;
279}
280
281INTERCEPTOR(int, munlockall, void) {
282  MlockIsUnsupported();
283  return 0;
284}
285
286static inline int CharCmp(unsigned char c1, unsigned char c2) {
287  return (c1 == c2) ? 0 : (c1 < c2) ? -1 : 1;
288}
289
290INTERCEPTOR(int, memcmp, const void *a1, const void *a2, uptr size) {
291  if (!asan_inited) return internal_memcmp(a1, a2, size);
292  ENSURE_ASAN_INITED();
293  if (flags()->replace_intrin) {
294    if (flags()->strict_memcmp) {
295      // Check the entire regions even if the first bytes of the buffers are
296      // different.
297      ASAN_READ_RANGE(a1, size);
298      ASAN_READ_RANGE(a2, size);
299      // Fallthrough to REAL(memcmp) below.
300    } else {
301      unsigned char c1 = 0, c2 = 0;
302      const unsigned char *s1 = (const unsigned char*)a1;
303      const unsigned char *s2 = (const unsigned char*)a2;
304      uptr i;
305      for (i = 0; i < size; i++) {
306        c1 = s1[i];
307        c2 = s2[i];
308        if (c1 != c2) break;
309      }
310      ASAN_READ_RANGE(s1, Min(i + 1, size));
311      ASAN_READ_RANGE(s2, Min(i + 1, size));
312      return CharCmp(c1, c2);
313    }
314  }
315  return REAL(memcmp(a1, a2, size));
316}
317
318#define MEMMOVE_BODY { \
319  if (!asan_inited) return internal_memmove(to, from, size); \
320  if (asan_init_is_running) { \
321    return REAL(memmove)(to, from, size); \
322  } \
323  ENSURE_ASAN_INITED(); \
324  if (flags()->replace_intrin) { \
325    ASAN_READ_RANGE(from, size); \
326    ASAN_WRITE_RANGE(to, size); \
327  } \
328  return internal_memmove(to, from, size); \
329}
330
331INTERCEPTOR(void*, memmove, void *to, const void *from, uptr size) MEMMOVE_BODY
332
333INTERCEPTOR(void*, memcpy, void *to, const void *from, uptr size) {
334#if !SANITIZER_MAC
335  if (!asan_inited) return internal_memcpy(to, from, size);
336  // memcpy is called during __asan_init() from the internals
337  // of printf(...).
338  if (asan_init_is_running) {
339    return REAL(memcpy)(to, from, size);
340  }
341  ENSURE_ASAN_INITED();
342  if (flags()->replace_intrin) {
343    if (to != from) {
344      // We do not treat memcpy with to==from as a bug.
345      // See http://llvm.org/bugs/show_bug.cgi?id=11763.
346      CHECK_RANGES_OVERLAP("memcpy", to, size, from, size);
347    }
348    ASAN_READ_RANGE(from, size);
349    ASAN_WRITE_RANGE(to, size);
350  }
351  // Interposing of resolver functions is broken on Mac OS 10.7 and 10.8, so
352  // calling REAL(memcpy) here leads to infinite recursion.
353  // See also http://code.google.com/p/address-sanitizer/issues/detail?id=116.
354  return internal_memcpy(to, from, size);
355#else
356  // At least on 10.7 and 10.8 both memcpy() and memmove() are being replaced
357  // with WRAP(memcpy). As a result, false positives are reported for memmove()
358  // calls. If we just disable error reporting with
359  // ASAN_OPTIONS=replace_intrin=0, memmove() is still replaced with
360  // internal_memcpy(), which may lead to crashes, see
361  // http://llvm.org/bugs/show_bug.cgi?id=16362.
362  MEMMOVE_BODY
363#endif  // !SANITIZER_MAC
364}
365
366INTERCEPTOR(void*, memset, void *block, int c, uptr size) {
367  if (!asan_inited) return internal_memset(block, c, size);
368  // memset is called inside Printf.
369  if (asan_init_is_running) {
370    return REAL(memset)(block, c, size);
371  }
372  ENSURE_ASAN_INITED();
373  if (flags()->replace_intrin) {
374    ASAN_WRITE_RANGE(block, size);
375  }
376  return REAL(memset)(block, c, size);
377}
378
379INTERCEPTOR(char*, strchr, const char *str, int c) {
380  if (!asan_inited) return internal_strchr(str, c);
381  // strchr is called inside create_purgeable_zone() when MallocGuardEdges=1 is
382  // used.
383  if (asan_init_is_running) {
384    return REAL(strchr)(str, c);
385  }
386  ENSURE_ASAN_INITED();
387  char *result = REAL(strchr)(str, c);
388  if (flags()->replace_str) {
389    uptr bytes_read = (result ? result - str : REAL(strlen)(str)) + 1;
390    ASAN_READ_RANGE(str, bytes_read);
391  }
392  return result;
393}
394
395#if ASAN_INTERCEPT_INDEX
396# if ASAN_USE_ALIAS_ATTRIBUTE_FOR_INDEX
397INTERCEPTOR(char*, index, const char *string, int c)
398  ALIAS(WRAPPER_NAME(strchr));
399# else
400#  if SANITIZER_MAC
401DECLARE_REAL(char*, index, const char *string, int c)
402OVERRIDE_FUNCTION(index, strchr);
403#  else
404DEFINE_REAL(char*, index, const char *string, int c)
405#  endif
406# endif
407#endif  // ASAN_INTERCEPT_INDEX
408
409// For both strcat() and strncat() we need to check the validity of |to|
410// argument irrespective of the |from| length.
411INTERCEPTOR(char*, strcat, char *to, const char *from) {  // NOLINT
412  ENSURE_ASAN_INITED();
413  if (flags()->replace_str) {
414    uptr from_length = REAL(strlen)(from);
415    ASAN_READ_RANGE(from, from_length + 1);
416    uptr to_length = REAL(strlen)(to);
417    ASAN_READ_RANGE(to, to_length);
418    ASAN_WRITE_RANGE(to + to_length, from_length + 1);
419    // If the copying actually happens, the |from| string should not overlap
420    // with the resulting string starting at |to|, which has a length of
421    // to_length + from_length + 1.
422    if (from_length > 0) {
423      CHECK_RANGES_OVERLAP("strcat", to, from_length + to_length + 1,
424                           from, from_length + 1);
425    }
426  }
427  return REAL(strcat)(to, from);  // NOLINT
428}
429
430INTERCEPTOR(char*, strncat, char *to, const char *from, uptr size) {
431  ENSURE_ASAN_INITED();
432  if (flags()->replace_str) {
433    uptr from_length = MaybeRealStrnlen(from, size);
434    uptr copy_length = Min(size, from_length + 1);
435    ASAN_READ_RANGE(from, copy_length);
436    uptr to_length = REAL(strlen)(to);
437    ASAN_READ_RANGE(to, to_length);
438    ASAN_WRITE_RANGE(to + to_length, from_length + 1);
439    if (from_length > 0) {
440      CHECK_RANGES_OVERLAP("strncat", to, to_length + copy_length + 1,
441                           from, copy_length);
442    }
443  }
444  return REAL(strncat)(to, from, size);
445}
446
447INTERCEPTOR(char*, strcpy, char *to, const char *from) {  // NOLINT
448#if SANITIZER_MAC
449  if (!asan_inited) return REAL(strcpy)(to, from);  // NOLINT
450#endif
451  // strcpy is called from malloc_default_purgeable_zone()
452  // in __asan::ReplaceSystemAlloc() on Mac.
453  if (asan_init_is_running) {
454    return REAL(strcpy)(to, from);  // NOLINT
455  }
456  ENSURE_ASAN_INITED();
457  if (flags()->replace_str) {
458    uptr from_size = REAL(strlen)(from) + 1;
459    CHECK_RANGES_OVERLAP("strcpy", to, from_size, from, from_size);
460    ASAN_READ_RANGE(from, from_size);
461    ASAN_WRITE_RANGE(to, from_size);
462  }
463  return REAL(strcpy)(to, from);  // NOLINT
464}
465
466#if ASAN_INTERCEPT_STRDUP
467INTERCEPTOR(char*, strdup, const char *s) {
468  if (!asan_inited) return internal_strdup(s);
469  ENSURE_ASAN_INITED();
470  uptr length = REAL(strlen)(s);
471  if (flags()->replace_str) {
472    ASAN_READ_RANGE(s, length + 1);
473  }
474  GET_STACK_TRACE_MALLOC;
475  void *new_mem = asan_malloc(length + 1, &stack);
476  REAL(memcpy)(new_mem, s, length + 1);
477  return reinterpret_cast<char*>(new_mem);
478}
479#endif
480
481INTERCEPTOR(uptr, strlen, const char *s) {
482  if (!asan_inited) return internal_strlen(s);
483  // strlen is called from malloc_default_purgeable_zone()
484  // in __asan::ReplaceSystemAlloc() on Mac.
485  if (asan_init_is_running) {
486    return REAL(strlen)(s);
487  }
488  ENSURE_ASAN_INITED();
489  uptr length = REAL(strlen)(s);
490  if (flags()->replace_str) {
491    ASAN_READ_RANGE(s, length + 1);
492  }
493  return length;
494}
495
496INTERCEPTOR(uptr, wcslen, const wchar_t *s) {
497  uptr length = REAL(wcslen)(s);
498  if (!asan_init_is_running) {
499    ENSURE_ASAN_INITED();
500    ASAN_READ_RANGE(s, (length + 1) * sizeof(wchar_t));
501  }
502  return length;
503}
504
505INTERCEPTOR(char*, strncpy, char *to, const char *from, uptr size) {
506  ENSURE_ASAN_INITED();
507  if (flags()->replace_str) {
508    uptr from_size = Min(size, MaybeRealStrnlen(from, size) + 1);
509    CHECK_RANGES_OVERLAP("strncpy", to, from_size, from, from_size);
510    ASAN_READ_RANGE(from, from_size);
511    ASAN_WRITE_RANGE(to, size);
512  }
513  return REAL(strncpy)(to, from, size);
514}
515
516#if ASAN_INTERCEPT_STRNLEN
517INTERCEPTOR(uptr, strnlen, const char *s, uptr maxlen) {
518  ENSURE_ASAN_INITED();
519  uptr length = REAL(strnlen)(s, maxlen);
520  if (flags()->replace_str) {
521    ASAN_READ_RANGE(s, Min(length + 1, maxlen));
522  }
523  return length;
524}
525#endif  // ASAN_INTERCEPT_STRNLEN
526
527static inline bool IsValidStrtolBase(int base) {
528  return (base == 0) || (2 <= base && base <= 36);
529}
530
531static inline void FixRealStrtolEndptr(const char *nptr, char **endptr) {
532  CHECK(endptr);
533  if (nptr == *endptr) {
534    // No digits were found at strtol call, we need to find out the last
535    // symbol accessed by strtoll on our own.
536    // We get this symbol by skipping leading blanks and optional +/- sign.
537    while (IsSpace(*nptr)) nptr++;
538    if (*nptr == '+' || *nptr == '-') nptr++;
539    *endptr = (char*)nptr;
540  }
541  CHECK(*endptr >= nptr);
542}
543
544INTERCEPTOR(long, strtol, const char *nptr,  // NOLINT
545            char **endptr, int base) {
546  ENSURE_ASAN_INITED();
547  if (!flags()->replace_str) {
548    return REAL(strtol)(nptr, endptr, base);
549  }
550  char *real_endptr;
551  long result = REAL(strtol)(nptr, &real_endptr, base);  // NOLINT
552  if (endptr != 0) {
553    *endptr = real_endptr;
554  }
555  if (IsValidStrtolBase(base)) {
556    FixRealStrtolEndptr(nptr, &real_endptr);
557    ASAN_READ_RANGE(nptr, (real_endptr - nptr) + 1);
558  }
559  return result;
560}
561
562INTERCEPTOR(int, atoi, const char *nptr) {
563#if SANITIZER_MAC
564  if (!asan_inited) return REAL(atoi)(nptr);
565#endif
566  ENSURE_ASAN_INITED();
567  if (!flags()->replace_str) {
568    return REAL(atoi)(nptr);
569  }
570  char *real_endptr;
571  // "man atoi" tells that behavior of atoi(nptr) is the same as
572  // strtol(nptr, 0, 10), i.e. it sets errno to ERANGE if the
573  // parsed integer can't be stored in *long* type (even if it's
574  // different from int). So, we just imitate this behavior.
575  int result = REAL(strtol)(nptr, &real_endptr, 10);
576  FixRealStrtolEndptr(nptr, &real_endptr);
577  ASAN_READ_RANGE(nptr, (real_endptr - nptr) + 1);
578  return result;
579}
580
581INTERCEPTOR(long, atol, const char *nptr) {  // NOLINT
582#if SANITIZER_MAC
583  if (!asan_inited) return REAL(atol)(nptr);
584#endif
585  ENSURE_ASAN_INITED();
586  if (!flags()->replace_str) {
587    return REAL(atol)(nptr);
588  }
589  char *real_endptr;
590  long result = REAL(strtol)(nptr, &real_endptr, 10);  // NOLINT
591  FixRealStrtolEndptr(nptr, &real_endptr);
592  ASAN_READ_RANGE(nptr, (real_endptr - nptr) + 1);
593  return result;
594}
595
596#if ASAN_INTERCEPT_ATOLL_AND_STRTOLL
597INTERCEPTOR(long long, strtoll, const char *nptr,  // NOLINT
598            char **endptr, int base) {
599  ENSURE_ASAN_INITED();
600  if (!flags()->replace_str) {
601    return REAL(strtoll)(nptr, endptr, base);
602  }
603  char *real_endptr;
604  long long result = REAL(strtoll)(nptr, &real_endptr, base);  // NOLINT
605  if (endptr != 0) {
606    *endptr = real_endptr;
607  }
608  // If base has unsupported value, strtoll can exit with EINVAL
609  // without reading any characters. So do additional checks only
610  // if base is valid.
611  if (IsValidStrtolBase(base)) {
612    FixRealStrtolEndptr(nptr, &real_endptr);
613    ASAN_READ_RANGE(nptr, (real_endptr - nptr) + 1);
614  }
615  return result;
616}
617
618INTERCEPTOR(long long, atoll, const char *nptr) {  // NOLINT
619  ENSURE_ASAN_INITED();
620  if (!flags()->replace_str) {
621    return REAL(atoll)(nptr);
622  }
623  char *real_endptr;
624  long long result = REAL(strtoll)(nptr, &real_endptr, 10);  // NOLINT
625  FixRealStrtolEndptr(nptr, &real_endptr);
626  ASAN_READ_RANGE(nptr, (real_endptr - nptr) + 1);
627  return result;
628}
629#endif  // ASAN_INTERCEPT_ATOLL_AND_STRTOLL
630
631static void AtCxaAtexit(void *unused) {
632  (void)unused;
633  StopInitOrderChecking();
634}
635
636#if ASAN_INTERCEPT___CXA_ATEXIT
637INTERCEPTOR(int, __cxa_atexit, void (*func)(void *), void *arg,
638            void *dso_handle) {
639  ENSURE_ASAN_INITED();
640  int res = REAL(__cxa_atexit)(func, arg, dso_handle);
641  REAL(__cxa_atexit)(AtCxaAtexit, 0, 0);
642  return res;
643}
644#endif  // ASAN_INTERCEPT___CXA_ATEXIT
645
646#if !SANITIZER_MAC
647#define ASAN_INTERCEPT_FUNC(name) do { \
648      if (!INTERCEPT_FUNCTION(name) && flags()->verbosity > 0) \
649        Report("AddressSanitizer: failed to intercept '" #name "'\n"); \
650    } while (0)
651#else
652// OS X interceptors don't need to be initialized with INTERCEPT_FUNCTION.
653#define ASAN_INTERCEPT_FUNC(name)
654#endif  // SANITIZER_MAC
655
656#if SANITIZER_WINDOWS
657INTERCEPTOR_WINAPI(DWORD, CreateThread,
658                   void* security, uptr stack_size,
659                   DWORD (__stdcall *start_routine)(void*), void* arg,
660                   DWORD thr_flags, void* tid) {
661  // Strict init-order checking in thread-hostile.
662  if (flags()->strict_init_order)
663    StopInitOrderChecking();
664  GET_STACK_TRACE_THREAD;
665  u32 current_tid = GetCurrentTidOrInvalid();
666  AsanThread *t = AsanThread::Create(start_routine, arg);
667  CreateThreadContextArgs args = { t, &stack };
668  bool detached = false;  // FIXME: how can we determine it on Windows?
669  asanThreadRegistry().CreateThread(*(uptr*)t, detached, current_tid, &args);
670  return REAL(CreateThread)(security, stack_size,
671                            asan_thread_start, t, thr_flags, tid);
672}
673
674namespace __asan {
675void InitializeWindowsInterceptors() {
676  ASAN_INTERCEPT_FUNC(CreateThread);
677}
678
679}  // namespace __asan
680#endif
681
682// ---------------------- InitializeAsanInterceptors ---------------- {{{1
683namespace __asan {
684void InitializeAsanInterceptors() {
685  static bool was_called_once;
686  CHECK(was_called_once == false);
687  was_called_once = true;
688  SANITIZER_COMMON_INTERCEPTORS_INIT;
689
690  // Intercept mem* functions.
691  ASAN_INTERCEPT_FUNC(memcmp);
692  ASAN_INTERCEPT_FUNC(memmove);
693  ASAN_INTERCEPT_FUNC(memset);
694  if (PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE) {
695    ASAN_INTERCEPT_FUNC(memcpy);
696  }
697
698  // Intercept str* functions.
699  ASAN_INTERCEPT_FUNC(strcat);  // NOLINT
700  ASAN_INTERCEPT_FUNC(strchr);
701  ASAN_INTERCEPT_FUNC(strcpy);  // NOLINT
702  ASAN_INTERCEPT_FUNC(strlen);
703  ASAN_INTERCEPT_FUNC(wcslen);
704  ASAN_INTERCEPT_FUNC(strncat);
705  ASAN_INTERCEPT_FUNC(strncpy);
706#if ASAN_INTERCEPT_STRDUP
707  ASAN_INTERCEPT_FUNC(strdup);
708#endif
709#if ASAN_INTERCEPT_STRNLEN
710  ASAN_INTERCEPT_FUNC(strnlen);
711#endif
712#if ASAN_INTERCEPT_INDEX && ASAN_USE_ALIAS_ATTRIBUTE_FOR_INDEX
713  ASAN_INTERCEPT_FUNC(index);
714#endif
715
716  ASAN_INTERCEPT_FUNC(atoi);
717  ASAN_INTERCEPT_FUNC(atol);
718  ASAN_INTERCEPT_FUNC(strtol);
719#if ASAN_INTERCEPT_ATOLL_AND_STRTOLL
720  ASAN_INTERCEPT_FUNC(atoll);
721  ASAN_INTERCEPT_FUNC(strtoll);
722#endif
723
724#if ASAN_INTERCEPT_MLOCKX
725  // Intercept mlock/munlock.
726  ASAN_INTERCEPT_FUNC(mlock);
727  ASAN_INTERCEPT_FUNC(munlock);
728  ASAN_INTERCEPT_FUNC(mlockall);
729  ASAN_INTERCEPT_FUNC(munlockall);
730#endif
731
732  // Intecept signal- and jump-related functions.
733  ASAN_INTERCEPT_FUNC(longjmp);
734#if ASAN_INTERCEPT_SIGNAL_AND_SIGACTION
735  ASAN_INTERCEPT_FUNC(sigaction);
736  ASAN_INTERCEPT_FUNC(signal);
737#endif
738#if ASAN_INTERCEPT_SWAPCONTEXT
739  ASAN_INTERCEPT_FUNC(swapcontext);
740#endif
741#if ASAN_INTERCEPT__LONGJMP
742  ASAN_INTERCEPT_FUNC(_longjmp);
743#endif
744#if ASAN_INTERCEPT_SIGLONGJMP
745  ASAN_INTERCEPT_FUNC(siglongjmp);
746#endif
747
748  // Intercept exception handling functions.
749#if ASAN_INTERCEPT___CXA_THROW
750  INTERCEPT_FUNCTION(__cxa_throw);
751#endif
752
753  // Intercept threading-related functions
754#if ASAN_INTERCEPT_PTHREAD_CREATE
755  ASAN_INTERCEPT_FUNC(pthread_create);
756#endif
757
758  // Intercept atexit function.
759#if ASAN_INTERCEPT___CXA_ATEXIT
760  ASAN_INTERCEPT_FUNC(__cxa_atexit);
761#endif
762
763  // Some Windows-specific interceptors.
764#if SANITIZER_WINDOWS
765  InitializeWindowsInterceptors();
766#endif
767
768  if (flags()->verbosity > 0) {
769    Report("AddressSanitizer: libc interceptors initialized\n");
770  }
771}
772
773}  // namespace __asan
774