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