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