Home | History | Annotate | Download | only in asan
      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 
     15 #include "asan_interceptors.h"
     16 #include "asan_allocator.h"
     17 #include "asan_internal.h"
     18 #include "asan_mapping.h"
     19 #include "asan_poisoning.h"
     20 #include "asan_report.h"
     21 #include "asan_stack.h"
     22 #include "asan_stats.h"
     23 #include "asan_suppressions.h"
     24 #include "lsan/lsan_common.h"
     25 #include "sanitizer_common/sanitizer_libc.h"
     26 
     27 #if SANITIZER_POSIX
     28 #include "sanitizer_common/sanitizer_posix.h"
     29 #endif
     30 
     31 #if defined(__i386) && SANITIZER_LINUX
     32 #define ASAN_PTHREAD_CREATE_VERSION "GLIBC_2.1"
     33 #elif defined(__mips__) && SANITIZER_LINUX
     34 #define ASAN_PTHREAD_CREATE_VERSION "GLIBC_2.2"
     35 #endif
     36 
     37 namespace __asan {
     38 
     39 // Return true if we can quickly decide that the region is unpoisoned.
     40 static inline bool QuickCheckForUnpoisonedRegion(uptr beg, uptr size) {
     41   if (size == 0) return true;
     42   if (size <= 32)
     43     return !AddressIsPoisoned(beg) &&
     44            !AddressIsPoisoned(beg + size - 1) &&
     45            !AddressIsPoisoned(beg + size / 2);
     46   return false;
     47 }
     48 
     49 struct AsanInterceptorContext {
     50   const char *interceptor_name;
     51 };
     52 
     53 // We implement ACCESS_MEMORY_RANGE, ASAN_READ_RANGE,
     54 // and ASAN_WRITE_RANGE as macro instead of function so
     55 // that no extra frames are created, and stack trace contains
     56 // relevant information only.
     57 // We check all shadow bytes.
     58 #define ACCESS_MEMORY_RANGE(ctx, offset, size, isWrite) do {            \
     59     uptr __offset = (uptr)(offset);                                     \
     60     uptr __size = (uptr)(size);                                         \
     61     uptr __bad = 0;                                                     \
     62     if (__offset > __offset + __size) {                                 \
     63       GET_STACK_TRACE_FATAL_HERE;                                       \
     64       ReportStringFunctionSizeOverflow(__offset, __size, &stack);       \
     65     }                                                                   \
     66     if (!QuickCheckForUnpoisonedRegion(__offset, __size) &&             \
     67         (__bad = __asan_region_is_poisoned(__offset, __size))) {        \
     68       AsanInterceptorContext *_ctx = (AsanInterceptorContext *)ctx;     \
     69       bool suppressed = false;                                          \
     70       if (_ctx) {                                                       \
     71         suppressed = IsInterceptorSuppressed(_ctx->interceptor_name);   \
     72         if (!suppressed && HaveStackTraceBasedSuppressions()) {         \
     73           GET_STACK_TRACE_FATAL_HERE;                                   \
     74           suppressed = IsStackTraceSuppressed(&stack);                  \
     75         }                                                               \
     76       }                                                                 \
     77       if (!suppressed) {                                                \
     78         GET_CURRENT_PC_BP_SP;                                           \
     79         ReportGenericError(pc, bp, sp, __bad, isWrite, __size, 0, false);\
     80       }                                                                 \
     81     }                                                                   \
     82   } while (0)
     83 
     84 #define ASAN_READ_RANGE(ctx, offset, size) \
     85   ACCESS_MEMORY_RANGE(ctx, offset, size, false)
     86 #define ASAN_WRITE_RANGE(ctx, offset, size) \
     87   ACCESS_MEMORY_RANGE(ctx, offset, size, true)
     88 
     89 #define ASAN_READ_STRING_OF_LEN(ctx, s, len, n)                 \
     90   ASAN_READ_RANGE((ctx), (s),                                   \
     91     common_flags()->strict_string_checks ? (len) + 1 : (n))
     92 
     93 #define ASAN_READ_STRING(ctx, s, n)                             \
     94   ASAN_READ_STRING_OF_LEN((ctx), (s), REAL(strlen)(s), (n))
     95 
     96 // Behavior of functions like "memcpy" or "strcpy" is undefined
     97 // if memory intervals overlap. We report error in this case.
     98 // Macro is used to avoid creation of new frames.
     99 static inline bool RangesOverlap(const char *offset1, uptr length1,
    100                                  const char *offset2, uptr length2) {
    101   return !((offset1 + length1 <= offset2) || (offset2 + length2 <= offset1));
    102 }
    103 #define CHECK_RANGES_OVERLAP(name, _offset1, length1, _offset2, length2) do { \
    104   const char *offset1 = (const char*)_offset1; \
    105   const char *offset2 = (const char*)_offset2; \
    106   if (RangesOverlap(offset1, length1, offset2, length2)) { \
    107     GET_STACK_TRACE_FATAL_HERE; \
    108     ReportStringFunctionMemoryRangesOverlap(name, offset1, length1, \
    109                                             offset2, length2, &stack); \
    110   } \
    111 } while (0)
    112 
    113 static inline uptr MaybeRealStrnlen(const char *s, uptr maxlen) {
    114 #if SANITIZER_INTERCEPT_STRNLEN
    115   if (REAL(strnlen)) {
    116     return REAL(strnlen)(s, maxlen);
    117   }
    118 #endif
    119   return internal_strnlen(s, maxlen);
    120 }
    121 
    122 void SetThreadName(const char *name) {
    123   AsanThread *t = GetCurrentThread();
    124   if (t)
    125     asanThreadRegistry().SetThreadName(t->tid(), name);
    126 }
    127 
    128 int OnExit() {
    129   // FIXME: ask frontend whether we need to return failure.
    130   return 0;
    131 }
    132 
    133 } // namespace __asan
    134 
    135 // ---------------------- Wrappers ---------------- {{{1
    136 using namespace __asan;  // NOLINT
    137 
    138 DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr)
    139 DECLARE_REAL_AND_INTERCEPTOR(void, free, void *)
    140 
    141 #define ASAN_INTERCEPTOR_ENTER(ctx, func)                                      \
    142   AsanInterceptorContext _ctx = {#func};                                       \
    143   ctx = (void *)&_ctx;                                                         \
    144   (void) ctx;                                                                  \
    145 
    146 #define COMMON_INTERCEPT_FUNCTION(name) ASAN_INTERCEPT_FUNC(name)
    147 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver)                          \
    148   ASAN_INTERCEPT_FUNC_VER(name, ver)
    149 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
    150   ASAN_WRITE_RANGE(ctx, ptr, size)
    151 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
    152   ASAN_READ_RANGE(ctx, ptr, size)
    153 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...)                               \
    154   ASAN_INTERCEPTOR_ENTER(ctx, func);                                           \
    155   do {                                                                         \
    156     if (asan_init_is_running)                                                  \
    157       return REAL(func)(__VA_ARGS__);                                          \
    158     if (SANITIZER_MAC && UNLIKELY(!asan_inited))                               \
    159       return REAL(func)(__VA_ARGS__);                                          \
    160     ENSURE_ASAN_INITED();                                                      \
    161   } while (false)
    162 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
    163   do {                                            \
    164   } while (false)
    165 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
    166   do {                                         \
    167   } while (false)
    168 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
    169   do {                                         \
    170   } while (false)
    171 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
    172   do {                                                      \
    173   } while (false)
    174 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) SetThreadName(name)
    175 // Should be asanThreadRegistry().SetThreadNameByUserId(thread, name)
    176 // But asan does not remember UserId's for threads (pthread_t);
    177 // and remembers all ever existed threads, so the linear search by UserId
    178 // can be slow.
    179 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
    180   do {                                                         \
    181   } while (false)
    182 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) REAL(name)
    183 // Strict init-order checking is dlopen-hostile:
    184 // https://github.com/google/sanitizers/issues/178
    185 #define COMMON_INTERCEPTOR_ON_DLOPEN(filename, flag)                           \
    186   if (flags()->strict_init_order) {                                            \
    187     StopInitOrderChecking();                                                   \
    188   }
    189 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) OnExit()
    190 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
    191   CoverageUpdateMapping()
    192 #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() CoverageUpdateMapping()
    193 #define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED (!asan_inited)
    194 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end)                           \
    195   if (AsanThread *t = GetCurrentThread()) {                                    \
    196     *begin = t->tls_begin();                                                   \
    197     *end = t->tls_end();                                                       \
    198   } else {                                                                     \
    199     *begin = *end = 0;                                                         \
    200   }
    201 // Asan needs custom handling of these:
    202 #undef SANITIZER_INTERCEPT_MEMSET
    203 #undef SANITIZER_INTERCEPT_MEMMOVE
    204 #undef SANITIZER_INTERCEPT_MEMCPY
    205 #include "sanitizer_common/sanitizer_common_interceptors.inc"
    206 
    207 // Syscall interceptors don't have contexts, we don't support suppressions
    208 // for them.
    209 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) ASAN_READ_RANGE(nullptr, p, s)
    210 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) ASAN_WRITE_RANGE(nullptr, p, s)
    211 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
    212   do {                                       \
    213     (void)(p);                               \
    214     (void)(s);                               \
    215   } while (false)
    216 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
    217   do {                                        \
    218     (void)(p);                                \
    219     (void)(s);                                \
    220   } while (false)
    221 #include "sanitizer_common/sanitizer_common_syscalls.inc"
    222 
    223 struct ThreadStartParam {
    224   atomic_uintptr_t t;
    225   atomic_uintptr_t is_registered;
    226 };
    227 
    228 #if ASAN_INTERCEPT_PTHREAD_CREATE
    229 static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
    230   ThreadStartParam *param = reinterpret_cast<ThreadStartParam *>(arg);
    231   AsanThread *t = nullptr;
    232   while ((t = reinterpret_cast<AsanThread *>(
    233               atomic_load(&param->t, memory_order_acquire))) == nullptr)
    234     internal_sched_yield();
    235   SetCurrentThread(t);
    236   return t->ThreadStart(GetTid(), &param->is_registered);
    237 }
    238 
    239 INTERCEPTOR(int, pthread_create, void *thread,
    240     void *attr, void *(*start_routine)(void*), void *arg) {
    241   EnsureMainThreadIDIsCorrect();
    242   // Strict init-order checking is thread-hostile.
    243   if (flags()->strict_init_order)
    244     StopInitOrderChecking();
    245   GET_STACK_TRACE_THREAD;
    246   int detached = 0;
    247   if (attr)
    248     REAL(pthread_attr_getdetachstate)(attr, &detached);
    249   ThreadStartParam param;
    250   atomic_store(&param.t, 0, memory_order_relaxed);
    251   atomic_store(&param.is_registered, 0, memory_order_relaxed);
    252   int result;
    253   {
    254     // Ignore all allocations made by pthread_create: thread stack/TLS may be
    255     // stored by pthread for future reuse even after thread destruction, and
    256     // the linked list it's stored in doesn't even hold valid pointers to the
    257     // objects, the latter are calculated by obscure pointer arithmetic.
    258 #if CAN_SANITIZE_LEAKS
    259     __lsan::ScopedInterceptorDisabler disabler;
    260 #endif
    261     result = REAL(pthread_create)(thread, attr, asan_thread_start, &param);
    262   }
    263   if (result == 0) {
    264     u32 current_tid = GetCurrentTidOrInvalid();
    265     AsanThread *t =
    266         AsanThread::Create(start_routine, arg, current_tid, &stack, detached);
    267     atomic_store(&param.t, reinterpret_cast<uptr>(t), memory_order_release);
    268     // Wait until the AsanThread object is initialized and the ThreadRegistry
    269     // entry is in "started" state. One reason for this is that after this
    270     // interceptor exits, the child thread's stack may be the only thing holding
    271     // the |arg| pointer. This may cause LSan to report a leak if leak checking
    272     // happens at a point when the interceptor has already exited, but the stack
    273     // range for the child thread is not yet known.
    274     while (atomic_load(&param.is_registered, memory_order_acquire) == 0)
    275       internal_sched_yield();
    276   }
    277   return result;
    278 }
    279 
    280 INTERCEPTOR(int, pthread_join, void *t, void **arg) {
    281   return real_pthread_join(t, arg);
    282 }
    283 
    284 DEFINE_REAL_PTHREAD_FUNCTIONS
    285 #endif  // ASAN_INTERCEPT_PTHREAD_CREATE
    286 
    287 #if ASAN_INTERCEPT_SIGNAL_AND_SIGACTION
    288 
    289 #if SANITIZER_ANDROID
    290 INTERCEPTOR(void*, bsd_signal, int signum, void *handler) {
    291   if (!IsHandledDeadlySignal(signum) ||
    292       common_flags()->allow_user_segv_handler) {
    293     return REAL(bsd_signal)(signum, handler);
    294   }
    295   return 0;
    296 }
    297 #endif
    298 
    299 INTERCEPTOR(void*, signal, int signum, void *handler) {
    300   if (!IsHandledDeadlySignal(signum) ||
    301       common_flags()->allow_user_segv_handler) {
    302     return REAL(signal)(signum, handler);
    303   }
    304   return nullptr;
    305 }
    306 
    307 INTERCEPTOR(int, sigaction, int signum, const struct sigaction *act,
    308                             struct sigaction *oldact) {
    309   if (!IsHandledDeadlySignal(signum) ||
    310       common_flags()->allow_user_segv_handler) {
    311     return REAL(sigaction)(signum, act, oldact);
    312   }
    313   return 0;
    314 }
    315 
    316 namespace __sanitizer {
    317 int real_sigaction(int signum, const void *act, void *oldact) {
    318   return REAL(sigaction)(signum, (const struct sigaction *)act,
    319                          (struct sigaction *)oldact);
    320 }
    321 } // namespace __sanitizer
    322 
    323 #elif SANITIZER_POSIX
    324 // We need to have defined REAL(sigaction) on posix systems.
    325 DEFINE_REAL(int, sigaction, int signum, const struct sigaction *act,
    326     struct sigaction *oldact)
    327 #endif  // ASAN_INTERCEPT_SIGNAL_AND_SIGACTION
    328 
    329 #if ASAN_INTERCEPT_SWAPCONTEXT
    330 static void ClearShadowMemoryForContextStack(uptr stack, uptr ssize) {
    331   // Align to page size.
    332   uptr PageSize = GetPageSizeCached();
    333   uptr bottom = stack & ~(PageSize - 1);
    334   ssize += stack - bottom;
    335   ssize = RoundUpTo(ssize, PageSize);
    336   static const uptr kMaxSaneContextStackSize = 1 << 22;  // 4 Mb
    337   if (AddrIsInMem(bottom) && ssize && ssize <= kMaxSaneContextStackSize) {
    338     PoisonShadow(bottom, ssize, 0);
    339   }
    340 }
    341 
    342 INTERCEPTOR(int, swapcontext, struct ucontext_t *oucp,
    343             struct ucontext_t *ucp) {
    344   static bool reported_warning = false;
    345   if (!reported_warning) {
    346     Report("WARNING: ASan doesn't fully support makecontext/swapcontext "
    347            "functions and may produce false positives in some cases!\n");
    348     reported_warning = true;
    349   }
    350   // Clear shadow memory for new context (it may share stack
    351   // with current context).
    352   uptr stack, ssize;
    353   ReadContextStack(ucp, &stack, &ssize);
    354   ClearShadowMemoryForContextStack(stack, ssize);
    355   int res = REAL(swapcontext)(oucp, ucp);
    356   // swapcontext technically does not return, but program may swap context to
    357   // "oucp" later, that would look as if swapcontext() returned 0.
    358   // We need to clear shadow for ucp once again, as it may be in arbitrary
    359   // state.
    360   ClearShadowMemoryForContextStack(stack, ssize);
    361   return res;
    362 }
    363 #endif  // ASAN_INTERCEPT_SWAPCONTEXT
    364 
    365 INTERCEPTOR(void, longjmp, void *env, int val) {
    366   __asan_handle_no_return();
    367   REAL(longjmp)(env, val);
    368 }
    369 
    370 #if ASAN_INTERCEPT__LONGJMP
    371 INTERCEPTOR(void, _longjmp, void *env, int val) {
    372   __asan_handle_no_return();
    373   REAL(_longjmp)(env, val);
    374 }
    375 #endif
    376 
    377 #if ASAN_INTERCEPT_SIGLONGJMP
    378 INTERCEPTOR(void, siglongjmp, void *env, int val) {
    379   __asan_handle_no_return();
    380   REAL(siglongjmp)(env, val);
    381 }
    382 #endif
    383 
    384 #if ASAN_INTERCEPT___CXA_THROW
    385 INTERCEPTOR(void, __cxa_throw, void *a, void *b, void *c) {
    386   CHECK(REAL(__cxa_throw));
    387   __asan_handle_no_return();
    388   REAL(__cxa_throw)(a, b, c);
    389 }
    390 #endif
    391 
    392 // memcpy is called during __asan_init() from the internals of printf(...).
    393 // We do not treat memcpy with to==from as a bug.
    394 // See http://llvm.org/bugs/show_bug.cgi?id=11763.
    395 #define ASAN_MEMCPY_IMPL(ctx, to, from, size) do {                             \
    396     if (UNLIKELY(!asan_inited)) return internal_memcpy(to, from, size);        \
    397     if (asan_init_is_running) {                                                \
    398       return REAL(memcpy)(to, from, size);                                     \
    399     }                                                                          \
    400     ENSURE_ASAN_INITED();                                                      \
    401     if (flags()->replace_intrin) {                                             \
    402       if (to != from) {                                                        \
    403         CHECK_RANGES_OVERLAP("memcpy", to, size, from, size);                  \
    404       }                                                                        \
    405       ASAN_READ_RANGE(ctx, from, size);                                        \
    406       ASAN_WRITE_RANGE(ctx, to, size);                                         \
    407     }                                                                          \
    408     return REAL(memcpy)(to, from, size);                                       \
    409   } while (0)
    410 
    411 
    412 void *__asan_memcpy(void *to, const void *from, uptr size) {
    413   ASAN_MEMCPY_IMPL(nullptr, to, from, size);
    414 }
    415 
    416 // memset is called inside Printf.
    417 #define ASAN_MEMSET_IMPL(ctx, block, c, size) do {                             \
    418     if (UNLIKELY(!asan_inited)) return internal_memset(block, c, size);        \
    419     if (asan_init_is_running) {                                                \
    420       return REAL(memset)(block, c, size);                                     \
    421     }                                                                          \
    422     ENSURE_ASAN_INITED();                                                      \
    423     if (flags()->replace_intrin) {                                             \
    424       ASAN_WRITE_RANGE(ctx, block, size);                                      \
    425     }                                                                          \
    426     return REAL(memset)(block, c, size);                                       \
    427   } while (0)
    428 
    429 void *__asan_memset(void *block, int c, uptr size) {
    430   ASAN_MEMSET_IMPL(nullptr, block, c, size);
    431 }
    432 
    433 #define ASAN_MEMMOVE_IMPL(ctx, to, from, size) do {                            \
    434     if (UNLIKELY(!asan_inited))                                                \
    435       return internal_memmove(to, from, size);                                 \
    436     ENSURE_ASAN_INITED();                                                      \
    437     if (flags()->replace_intrin) {                                             \
    438       ASAN_READ_RANGE(ctx, from, size);                                        \
    439       ASAN_WRITE_RANGE(ctx, to, size);                                         \
    440     }                                                                          \
    441     return internal_memmove(to, from, size);                                   \
    442   } while (0)
    443 
    444 void *__asan_memmove(void *to, const void *from, uptr size) {
    445   ASAN_MEMMOVE_IMPL(nullptr, to, from, size);
    446 }
    447 
    448 INTERCEPTOR(void*, memmove, void *to, const void *from, uptr size) {
    449   void *ctx;
    450   ASAN_INTERCEPTOR_ENTER(ctx, memmove);
    451   ASAN_MEMMOVE_IMPL(ctx, to, from, size);
    452 }
    453 
    454 INTERCEPTOR(void*, memcpy, void *to, const void *from, uptr size) {
    455   void *ctx;
    456   ASAN_INTERCEPTOR_ENTER(ctx, memcpy);
    457 #if !SANITIZER_MAC
    458   ASAN_MEMCPY_IMPL(ctx, to, from, size);
    459 #else
    460   // At least on 10.7 and 10.8 both memcpy() and memmove() are being replaced
    461   // with WRAP(memcpy). As a result, false positives are reported for memmove()
    462   // calls. If we just disable error reporting with
    463   // ASAN_OPTIONS=replace_intrin=0, memmove() is still replaced with
    464   // internal_memcpy(), which may lead to crashes, see
    465   // http://llvm.org/bugs/show_bug.cgi?id=16362.
    466   ASAN_MEMMOVE_IMPL(ctx, to, from, size);
    467 #endif  // !SANITIZER_MAC
    468 }
    469 
    470 INTERCEPTOR(void*, memset, void *block, int c, uptr size) {
    471   void *ctx;
    472   ASAN_INTERCEPTOR_ENTER(ctx, memset);
    473   ASAN_MEMSET_IMPL(ctx, block, c, size);
    474 }
    475 
    476 #if ASAN_INTERCEPT_INDEX
    477 # if ASAN_USE_ALIAS_ATTRIBUTE_FOR_INDEX
    478 INTERCEPTOR(char*, index, const char *string, int c)
    479   ALIAS(WRAPPER_NAME(strchr));
    480 # else
    481 #  if SANITIZER_MAC
    482 DECLARE_REAL(char*, index, const char *string, int c)
    483 OVERRIDE_FUNCTION(index, strchr);
    484 #  else
    485 DEFINE_REAL(char*, index, const char *string, int c)
    486 #  endif
    487 # endif
    488 #endif  // ASAN_INTERCEPT_INDEX
    489 
    490 // For both strcat() and strncat() we need to check the validity of |to|
    491 // argument irrespective of the |from| length.
    492 INTERCEPTOR(char*, strcat, char *to, const char *from) {  // NOLINT
    493   void *ctx;
    494   ASAN_INTERCEPTOR_ENTER(ctx, strcat);  // NOLINT
    495   ENSURE_ASAN_INITED();
    496   if (flags()->replace_str) {
    497     uptr from_length = REAL(strlen)(from);
    498     ASAN_READ_RANGE(ctx, from, from_length + 1);
    499     uptr to_length = REAL(strlen)(to);
    500     ASAN_READ_STRING_OF_LEN(ctx, to, to_length, to_length);
    501     ASAN_WRITE_RANGE(ctx, to + to_length, from_length + 1);
    502     // If the copying actually happens, the |from| string should not overlap
    503     // with the resulting string starting at |to|, which has a length of
    504     // to_length + from_length + 1.
    505     if (from_length > 0) {
    506       CHECK_RANGES_OVERLAP("strcat", to, from_length + to_length + 1,
    507                            from, from_length + 1);
    508     }
    509   }
    510   return REAL(strcat)(to, from);  // NOLINT
    511 }
    512 
    513 INTERCEPTOR(char*, strncat, char *to, const char *from, uptr size) {
    514   void *ctx;
    515   ASAN_INTERCEPTOR_ENTER(ctx, strncat);
    516   ENSURE_ASAN_INITED();
    517   if (flags()->replace_str) {
    518     uptr from_length = MaybeRealStrnlen(from, size);
    519     uptr copy_length = Min(size, from_length + 1);
    520     ASAN_READ_RANGE(ctx, from, copy_length);
    521     uptr to_length = REAL(strlen)(to);
    522     ASAN_READ_STRING_OF_LEN(ctx, to, to_length, to_length);
    523     ASAN_WRITE_RANGE(ctx, to + to_length, from_length + 1);
    524     if (from_length > 0) {
    525       CHECK_RANGES_OVERLAP("strncat", to, to_length + copy_length + 1,
    526                            from, copy_length);
    527     }
    528   }
    529   return REAL(strncat)(to, from, size);
    530 }
    531 
    532 INTERCEPTOR(char*, strcpy, char *to, const char *from) {  // NOLINT
    533   void *ctx;
    534   ASAN_INTERCEPTOR_ENTER(ctx, strcpy);  // NOLINT
    535 #if SANITIZER_MAC
    536   if (UNLIKELY(!asan_inited)) return REAL(strcpy)(to, from);  // NOLINT
    537 #endif
    538   // strcpy is called from malloc_default_purgeable_zone()
    539   // in __asan::ReplaceSystemAlloc() on Mac.
    540   if (asan_init_is_running) {
    541     return REAL(strcpy)(to, from);  // NOLINT
    542   }
    543   ENSURE_ASAN_INITED();
    544   if (flags()->replace_str) {
    545     uptr from_size = REAL(strlen)(from) + 1;
    546     CHECK_RANGES_OVERLAP("strcpy", to, from_size, from, from_size);
    547     ASAN_READ_RANGE(ctx, from, from_size);
    548     ASAN_WRITE_RANGE(ctx, to, from_size);
    549   }
    550   return REAL(strcpy)(to, from);  // NOLINT
    551 }
    552 
    553 INTERCEPTOR(char*, strdup, const char *s) {
    554   void *ctx;
    555   ASAN_INTERCEPTOR_ENTER(ctx, strdup);
    556   if (UNLIKELY(!asan_inited)) return internal_strdup(s);
    557   ENSURE_ASAN_INITED();
    558   uptr length = REAL(strlen)(s);
    559   if (flags()->replace_str) {
    560     ASAN_READ_RANGE(ctx, s, length + 1);
    561   }
    562   GET_STACK_TRACE_MALLOC;
    563   void *new_mem = asan_malloc(length + 1, &stack);
    564   REAL(memcpy)(new_mem, s, length + 1);
    565   return reinterpret_cast<char*>(new_mem);
    566 }
    567 
    568 #if ASAN_INTERCEPT___STRDUP
    569 INTERCEPTOR(char*, __strdup, const char *s) {
    570   void *ctx;
    571   ASAN_INTERCEPTOR_ENTER(ctx, strdup);
    572   if (UNLIKELY(!asan_inited)) return internal_strdup(s);
    573   ENSURE_ASAN_INITED();
    574   uptr length = REAL(strlen)(s);
    575   if (flags()->replace_str) {
    576     ASAN_READ_RANGE(ctx, s, length + 1);
    577   }
    578   GET_STACK_TRACE_MALLOC;
    579   void *new_mem = asan_malloc(length + 1, &stack);
    580   REAL(memcpy)(new_mem, s, length + 1);
    581   return reinterpret_cast<char*>(new_mem);
    582 }
    583 #endif // ASAN_INTERCEPT___STRDUP
    584 
    585 INTERCEPTOR(SIZE_T, wcslen, const wchar_t *s) {
    586   void *ctx;
    587   ASAN_INTERCEPTOR_ENTER(ctx, wcslen);
    588   SIZE_T length = REAL(wcslen)(s);
    589   if (!asan_init_is_running) {
    590     ENSURE_ASAN_INITED();
    591     ASAN_READ_RANGE(ctx, s, (length + 1) * sizeof(wchar_t));
    592   }
    593   return length;
    594 }
    595 
    596 INTERCEPTOR(char*, strncpy, char *to, const char *from, uptr size) {
    597   void *ctx;
    598   ASAN_INTERCEPTOR_ENTER(ctx, strncpy);
    599   ENSURE_ASAN_INITED();
    600   if (flags()->replace_str) {
    601     uptr from_size = Min(size, MaybeRealStrnlen(from, size) + 1);
    602     CHECK_RANGES_OVERLAP("strncpy", to, from_size, from, from_size);
    603     ASAN_READ_RANGE(ctx, from, from_size);
    604     ASAN_WRITE_RANGE(ctx, to, size);
    605   }
    606   return REAL(strncpy)(to, from, size);
    607 }
    608 
    609 INTERCEPTOR(long, strtol, const char *nptr,  // NOLINT
    610             char **endptr, int base) {
    611   void *ctx;
    612   ASAN_INTERCEPTOR_ENTER(ctx, strtol);
    613   ENSURE_ASAN_INITED();
    614   if (!flags()->replace_str) {
    615     return REAL(strtol)(nptr, endptr, base);
    616   }
    617   char *real_endptr;
    618   long result = REAL(strtol)(nptr, &real_endptr, base);  // NOLINT
    619   StrtolFixAndCheck(ctx, nptr, endptr, real_endptr, base);
    620   return result;
    621 }
    622 
    623 INTERCEPTOR(int, atoi, const char *nptr) {
    624   void *ctx;
    625   ASAN_INTERCEPTOR_ENTER(ctx, atoi);
    626 #if SANITIZER_MAC
    627   if (UNLIKELY(!asan_inited)) return REAL(atoi)(nptr);
    628 #endif
    629   ENSURE_ASAN_INITED();
    630   if (!flags()->replace_str) {
    631     return REAL(atoi)(nptr);
    632   }
    633   char *real_endptr;
    634   // "man atoi" tells that behavior of atoi(nptr) is the same as
    635   // strtol(nptr, 0, 10), i.e. it sets errno to ERANGE if the
    636   // parsed integer can't be stored in *long* type (even if it's
    637   // different from int). So, we just imitate this behavior.
    638   int result = REAL(strtol)(nptr, &real_endptr, 10);
    639   FixRealStrtolEndptr(nptr, &real_endptr);
    640   ASAN_READ_STRING(ctx, nptr, (real_endptr - nptr) + 1);
    641   return result;
    642 }
    643 
    644 INTERCEPTOR(long, atol, const char *nptr) {  // NOLINT
    645   void *ctx;
    646   ASAN_INTERCEPTOR_ENTER(ctx, atol);
    647 #if SANITIZER_MAC
    648   if (UNLIKELY(!asan_inited)) return REAL(atol)(nptr);
    649 #endif
    650   ENSURE_ASAN_INITED();
    651   if (!flags()->replace_str) {
    652     return REAL(atol)(nptr);
    653   }
    654   char *real_endptr;
    655   long result = REAL(strtol)(nptr, &real_endptr, 10);  // NOLINT
    656   FixRealStrtolEndptr(nptr, &real_endptr);
    657   ASAN_READ_STRING(ctx, nptr, (real_endptr - nptr) + 1);
    658   return result;
    659 }
    660 
    661 #if ASAN_INTERCEPT_ATOLL_AND_STRTOLL
    662 INTERCEPTOR(long long, strtoll, const char *nptr,  // NOLINT
    663             char **endptr, int base) {
    664   void *ctx;
    665   ASAN_INTERCEPTOR_ENTER(ctx, strtoll);
    666   ENSURE_ASAN_INITED();
    667   if (!flags()->replace_str) {
    668     return REAL(strtoll)(nptr, endptr, base);
    669   }
    670   char *real_endptr;
    671   long long result = REAL(strtoll)(nptr, &real_endptr, base);  // NOLINT
    672   StrtolFixAndCheck(ctx, nptr, endptr, real_endptr, base);
    673   return result;
    674 }
    675 
    676 INTERCEPTOR(long long, atoll, const char *nptr) {  // NOLINT
    677   void *ctx;
    678   ASAN_INTERCEPTOR_ENTER(ctx, atoll);
    679   ENSURE_ASAN_INITED();
    680   if (!flags()->replace_str) {
    681     return REAL(atoll)(nptr);
    682   }
    683   char *real_endptr;
    684   long long result = REAL(strtoll)(nptr, &real_endptr, 10);  // NOLINT
    685   FixRealStrtolEndptr(nptr, &real_endptr);
    686   ASAN_READ_STRING(ctx, nptr, (real_endptr - nptr) + 1);
    687   return result;
    688 }
    689 #endif  // ASAN_INTERCEPT_ATOLL_AND_STRTOLL
    690 
    691 #if ASAN_INTERCEPT___CXA_ATEXIT
    692 static void AtCxaAtexit(void *unused) {
    693   (void)unused;
    694   StopInitOrderChecking();
    695 }
    696 
    697 INTERCEPTOR(int, __cxa_atexit, void (*func)(void *), void *arg,
    698             void *dso_handle) {
    699 #if SANITIZER_MAC
    700   if (UNLIKELY(!asan_inited)) return REAL(__cxa_atexit)(func, arg, dso_handle);
    701 #endif
    702   ENSURE_ASAN_INITED();
    703   int res = REAL(__cxa_atexit)(func, arg, dso_handle);
    704   REAL(__cxa_atexit)(AtCxaAtexit, nullptr, nullptr);
    705   return res;
    706 }
    707 #endif  // ASAN_INTERCEPT___CXA_ATEXIT
    708 
    709 #if ASAN_INTERCEPT_FORK
    710 INTERCEPTOR(int, fork, void) {
    711   ENSURE_ASAN_INITED();
    712   if (common_flags()->coverage) CovBeforeFork();
    713   int pid = REAL(fork)();
    714   if (common_flags()->coverage) CovAfterFork(pid);
    715   return pid;
    716 }
    717 #endif  // ASAN_INTERCEPT_FORK
    718 
    719 // ---------------------- InitializeAsanInterceptors ---------------- {{{1
    720 namespace __asan {
    721 void InitializeAsanInterceptors() {
    722   static bool was_called_once;
    723   CHECK(was_called_once == false);
    724   was_called_once = true;
    725   InitializeCommonInterceptors();
    726 
    727   // Intercept mem* functions.
    728   ASAN_INTERCEPT_FUNC(memcpy);
    729   ASAN_INTERCEPT_FUNC(memset);
    730   if (PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE) {
    731     // In asan, REAL(memmove) is not used, but it is used in msan.
    732     ASAN_INTERCEPT_FUNC(memmove);
    733   }
    734   CHECK(REAL(memcpy));
    735 
    736   // Intercept str* functions.
    737   ASAN_INTERCEPT_FUNC(strcat);  // NOLINT
    738   ASAN_INTERCEPT_FUNC(strcpy);  // NOLINT
    739   ASAN_INTERCEPT_FUNC(wcslen);
    740   ASAN_INTERCEPT_FUNC(strncat);
    741   ASAN_INTERCEPT_FUNC(strncpy);
    742   ASAN_INTERCEPT_FUNC(strdup);
    743 #if ASAN_INTERCEPT___STRDUP
    744   ASAN_INTERCEPT_FUNC(__strdup);
    745 #endif
    746 #if ASAN_INTERCEPT_INDEX && ASAN_USE_ALIAS_ATTRIBUTE_FOR_INDEX
    747   ASAN_INTERCEPT_FUNC(index);
    748 #endif
    749 
    750   ASAN_INTERCEPT_FUNC(atoi);
    751   ASAN_INTERCEPT_FUNC(atol);
    752   ASAN_INTERCEPT_FUNC(strtol);
    753 #if ASAN_INTERCEPT_ATOLL_AND_STRTOLL
    754   ASAN_INTERCEPT_FUNC(atoll);
    755   ASAN_INTERCEPT_FUNC(strtoll);
    756 #endif
    757 
    758   // Intecept signal- and jump-related functions.
    759   ASAN_INTERCEPT_FUNC(longjmp);
    760 #if ASAN_INTERCEPT_SIGNAL_AND_SIGACTION
    761   ASAN_INTERCEPT_FUNC(sigaction);
    762 #if SANITIZER_ANDROID
    763   ASAN_INTERCEPT_FUNC(bsd_signal);
    764 #endif
    765   ASAN_INTERCEPT_FUNC(signal);
    766 #endif
    767 #if ASAN_INTERCEPT_SWAPCONTEXT
    768   ASAN_INTERCEPT_FUNC(swapcontext);
    769 #endif
    770 #if ASAN_INTERCEPT__LONGJMP
    771   ASAN_INTERCEPT_FUNC(_longjmp);
    772 #endif
    773 #if ASAN_INTERCEPT_SIGLONGJMP
    774   ASAN_INTERCEPT_FUNC(siglongjmp);
    775 #endif
    776 
    777   // Intercept exception handling functions.
    778 #if ASAN_INTERCEPT___CXA_THROW
    779   ASAN_INTERCEPT_FUNC(__cxa_throw);
    780 #endif
    781 
    782   // Intercept threading-related functions
    783 #if ASAN_INTERCEPT_PTHREAD_CREATE
    784 #if defined(ASAN_PTHREAD_CREATE_VERSION)
    785   ASAN_INTERCEPT_FUNC_VER(pthread_create, ASAN_PTHREAD_CREATE_VERSION);
    786 #else
    787   ASAN_INTERCEPT_FUNC(pthread_create);
    788 #endif
    789   ASAN_INTERCEPT_FUNC(pthread_join);
    790 #endif
    791 
    792   // Intercept atexit function.
    793 #if ASAN_INTERCEPT___CXA_ATEXIT
    794   ASAN_INTERCEPT_FUNC(__cxa_atexit);
    795 #endif
    796 
    797 #if ASAN_INTERCEPT_FORK
    798   ASAN_INTERCEPT_FUNC(fork);
    799 #endif
    800 
    801   InitializePlatformInterceptors();
    802 
    803   VReport(1, "AddressSanitizer: libc interceptors initialized\n");
    804 }
    805 
    806 } // namespace __asan
    807