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