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