1 //===-- msan_interceptors.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of MemorySanitizer.
10 //
11 // Interceptors for standard library functions.
12 //
13 // FIXME: move as many interceptors as possible into
14 // sanitizer_common/sanitizer_common_interceptors.h
15 //===----------------------------------------------------------------------===//
16 
17 #include "interception/interception.h"
18 #include "msan.h"
19 #include "msan_chained_origin_depot.h"
20 #include "msan_origin.h"
21 #include "msan_report.h"
22 #include "msan_thread.h"
23 #include "msan_poisoning.h"
24 #include "sanitizer_common/sanitizer_platform_limits_posix.h"
25 #include "sanitizer_common/sanitizer_platform_limits_netbsd.h"
26 #include "sanitizer_common/sanitizer_allocator.h"
27 #include "sanitizer_common/sanitizer_allocator_interface.h"
28 #include "sanitizer_common/sanitizer_allocator_internal.h"
29 #include "sanitizer_common/sanitizer_atomic.h"
30 #include "sanitizer_common/sanitizer_common.h"
31 #include "sanitizer_common/sanitizer_errno.h"
32 #include "sanitizer_common/sanitizer_stackdepot.h"
33 #include "sanitizer_common/sanitizer_libc.h"
34 #include "sanitizer_common/sanitizer_linux.h"
35 #include "sanitizer_common/sanitizer_tls_get_addr.h"
36 #include "sanitizer_common/sanitizer_vector.h"
37 
38 #if SANITIZER_NETBSD
39 #define fstat __fstat50
40 #define gettimeofday __gettimeofday50
41 #define getrusage __getrusage50
42 #define tzset __tzset50
43 #endif
44 
45 #include <stdarg.h>
46 // ACHTUNG! No other system header includes in this file.
47 // Ideally, we should get rid of stdarg.h as well.
48 
49 using namespace __msan;
50 
51 using __sanitizer::memory_order;
52 using __sanitizer::atomic_load;
53 using __sanitizer::atomic_store;
54 using __sanitizer::atomic_uintptr_t;
55 
56 DECLARE_REAL(SIZE_T, strlen, const char *s)
57 DECLARE_REAL(SIZE_T, strnlen, const char *s, SIZE_T maxlen)
58 DECLARE_REAL(void *, memcpy, void *dest, const void *src, uptr n)
59 DECLARE_REAL(void *, memset, void *dest, int c, uptr n)
60 
61 // True if this is a nested interceptor.
62 static THREADLOCAL int in_interceptor_scope;
63 
64 void __msan_scoped_disable_interceptor_checks() { ++in_interceptor_scope; }
65 void __msan_scoped_enable_interceptor_checks() { --in_interceptor_scope; }
66 
67 struct InterceptorScope {
68   InterceptorScope() { ++in_interceptor_scope; }
69   ~InterceptorScope() { --in_interceptor_scope; }
70 };
71 
72 bool IsInInterceptorScope() {
73   return in_interceptor_scope;
74 }
75 
76 static uptr allocated_for_dlsym;
77 static const uptr kDlsymAllocPoolSize = 1024;
78 static uptr alloc_memory_for_dlsym[kDlsymAllocPoolSize];
79 
80 static bool IsInDlsymAllocPool(const void *ptr) {
81   uptr off = (uptr)ptr - (uptr)alloc_memory_for_dlsym;
82   return off < sizeof(alloc_memory_for_dlsym);
83 }
84 
85 static void *AllocateFromLocalPool(uptr size_in_bytes) {
86   uptr size_in_words = RoundUpTo(size_in_bytes, kWordSize) / kWordSize;
87   void *mem = (void *)&alloc_memory_for_dlsym[allocated_for_dlsym];
88   allocated_for_dlsym += size_in_words;
89   CHECK_LT(allocated_for_dlsym, kDlsymAllocPoolSize);
90   return mem;
91 }
92 
93 #define ENSURE_MSAN_INITED() do { \
94   CHECK(!msan_init_is_running); \
95   if (!msan_inited) { \
96     __msan_init(); \
97   } \
98 } while (0)
99 
100 // Check that [x, x+n) range is unpoisoned.
101 #define CHECK_UNPOISONED_0(x, n)                                  \
102   do {                                                            \
103     sptr __offset = __msan_test_shadow(x, n);                     \
104     if (__msan::IsInSymbolizer()) break;                          \
105     if (__offset >= 0 && __msan::flags()->report_umrs) {          \
106       GET_CALLER_PC_BP_SP;                                        \
107       (void)sp;                                                   \
108       ReportUMRInsideAddressRange(__func__, x, n, __offset);      \
109       __msan::PrintWarningWithOrigin(                             \
110           pc, bp, __msan_get_origin((const char *)x + __offset)); \
111       if (__msan::flags()->halt_on_error) {                       \
112         Printf("Exiting\n");                                      \
113         Die();                                                    \
114       }                                                           \
115     }                                                             \
116   } while (0)
117 
118 // Check that [x, x+n) range is unpoisoned unless we are in a nested
119 // interceptor.
120 #define CHECK_UNPOISONED(x, n)                             \
121   do {                                                     \
122     if (!IsInInterceptorScope()) CHECK_UNPOISONED_0(x, n); \
123   } while (0)
124 
125 #define CHECK_UNPOISONED_STRING_OF_LEN(x, len, n)               \
126   CHECK_UNPOISONED((x),                                         \
127     common_flags()->strict_string_checks ? (len) + 1 : (n) )
128 
129 #define CHECK_UNPOISONED_STRING(x, n)                           \
130     CHECK_UNPOISONED_STRING_OF_LEN((x), internal_strlen(x), (n))
131 
132 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
133 INTERCEPTOR(SIZE_T, fread_unlocked, void *ptr, SIZE_T size, SIZE_T nmemb,
134             void *file) {
135   ENSURE_MSAN_INITED();
136   SIZE_T res = REAL(fread_unlocked)(ptr, size, nmemb, file);
137   if (res > 0)
138     __msan_unpoison(ptr, res *size);
139   return res;
140 }
141 #define MSAN_MAYBE_INTERCEPT_FREAD_UNLOCKED INTERCEPT_FUNCTION(fread_unlocked)
142 #else
143 #define MSAN_MAYBE_INTERCEPT_FREAD_UNLOCKED
144 #endif
145 
146 #if !SANITIZER_NETBSD
147 INTERCEPTOR(void *, mempcpy, void *dest, const void *src, SIZE_T n) {
148   return (char *)__msan_memcpy(dest, src, n) + n;
149 }
150 #define MSAN_MAYBE_INTERCEPT_MEMPCPY INTERCEPT_FUNCTION(mempcpy)
151 #else
152 #define MSAN_MAYBE_INTERCEPT_MEMPCPY
153 #endif
154 
155 INTERCEPTOR(void *, memccpy, void *dest, const void *src, int c, SIZE_T n) {
156   ENSURE_MSAN_INITED();
157   void *res = REAL(memccpy)(dest, src, c, n);
158   CHECK(!res || (res >= dest && res <= (char *)dest + n));
159   SIZE_T sz = res ? (char *)res - (char *)dest : n;
160   CHECK_UNPOISONED(src, sz);
161   __msan_unpoison(dest, sz);
162   return res;
163 }
164 
165 INTERCEPTOR(void *, bcopy, const void *src, void *dest, SIZE_T n) {
166   return __msan_memmove(dest, src, n);
167 }
168 
169 INTERCEPTOR(int, posix_memalign, void **memptr, SIZE_T alignment, SIZE_T size) {
170   GET_MALLOC_STACK_TRACE;
171   CHECK_NE(memptr, 0);
172   int res = msan_posix_memalign(memptr, alignment, size, &stack);
173   if (!res)
174     __msan_unpoison(memptr, sizeof(*memptr));
175   return res;
176 }
177 
178 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
179 INTERCEPTOR(void *, memalign, SIZE_T alignment, SIZE_T size) {
180   GET_MALLOC_STACK_TRACE;
181   return msan_memalign(alignment, size, &stack);
182 }
183 #define MSAN_MAYBE_INTERCEPT_MEMALIGN INTERCEPT_FUNCTION(memalign)
184 #else
185 #define MSAN_MAYBE_INTERCEPT_MEMALIGN
186 #endif
187 
188 INTERCEPTOR(void *, aligned_alloc, SIZE_T alignment, SIZE_T size) {
189   GET_MALLOC_STACK_TRACE;
190   return msan_aligned_alloc(alignment, size, &stack);
191 }
192 
193 #if !SANITIZER_NETBSD
194 INTERCEPTOR(void *, __libc_memalign, SIZE_T alignment, SIZE_T size) {
195   GET_MALLOC_STACK_TRACE;
196   void *ptr = msan_memalign(alignment, size, &stack);
197   if (ptr)
198     DTLS_on_libc_memalign(ptr, size);
199   return ptr;
200 }
201 #define MSAN_MAYBE_INTERCEPT___LIBC_MEMALIGN INTERCEPT_FUNCTION(__libc_memalign)
202 #else
203 #define MSAN_MAYBE_INTERCEPT___LIBC_MEMALIGN
204 #endif
205 
206 INTERCEPTOR(void *, valloc, SIZE_T size) {
207   GET_MALLOC_STACK_TRACE;
208   return msan_valloc(size, &stack);
209 }
210 
211 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
212 INTERCEPTOR(void *, pvalloc, SIZE_T size) {
213   GET_MALLOC_STACK_TRACE;
214   return msan_pvalloc(size, &stack);
215 }
216 #define MSAN_MAYBE_INTERCEPT_PVALLOC INTERCEPT_FUNCTION(pvalloc)
217 #else
218 #define MSAN_MAYBE_INTERCEPT_PVALLOC
219 #endif
220 
221 INTERCEPTOR(void, free, void *ptr) {
222   GET_MALLOC_STACK_TRACE;
223   if (!ptr || UNLIKELY(IsInDlsymAllocPool(ptr))) return;
224   MsanDeallocate(&stack, ptr);
225 }
226 
227 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
228 INTERCEPTOR(void, cfree, void *ptr) {
229   GET_MALLOC_STACK_TRACE;
230   if (!ptr || UNLIKELY(IsInDlsymAllocPool(ptr))) return;
231   MsanDeallocate(&stack, ptr);
232 }
233 #define MSAN_MAYBE_INTERCEPT_CFREE INTERCEPT_FUNCTION(cfree)
234 #else
235 #define MSAN_MAYBE_INTERCEPT_CFREE
236 #endif
237 
238 #if !SANITIZER_NETBSD
239 INTERCEPTOR(uptr, malloc_usable_size, void *ptr) {
240   return __sanitizer_get_allocated_size(ptr);
241 }
242 #define MSAN_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE \
243   INTERCEPT_FUNCTION(malloc_usable_size)
244 #else
245 #define MSAN_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE
246 #endif
247 
248 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
249 // This function actually returns a struct by value, but we can't unpoison a
250 // temporary! The following is equivalent on all supported platforms but
251 // aarch64 (which uses a different register for sret value).  We have a test
252 // to confirm that.
253 INTERCEPTOR(void, mallinfo, __sanitizer_struct_mallinfo *sret) {
254 #ifdef __aarch64__
255   uptr r8;
256   asm volatile("mov %0,x8" : "=r" (r8));
257   sret = reinterpret_cast<__sanitizer_struct_mallinfo*>(r8);
258 #endif
259   REAL(memset)(sret, 0, sizeof(*sret));
260   __msan_unpoison(sret, sizeof(*sret));
261 }
262 #define MSAN_MAYBE_INTERCEPT_MALLINFO INTERCEPT_FUNCTION(mallinfo)
263 #else
264 #define MSAN_MAYBE_INTERCEPT_MALLINFO
265 #endif
266 
267 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
268 INTERCEPTOR(int, mallopt, int cmd, int value) {
269   return 0;
270 }
271 #define MSAN_MAYBE_INTERCEPT_MALLOPT INTERCEPT_FUNCTION(mallopt)
272 #else
273 #define MSAN_MAYBE_INTERCEPT_MALLOPT
274 #endif
275 
276 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
277 INTERCEPTOR(void, malloc_stats, void) {
278   // FIXME: implement, but don't call REAL(malloc_stats)!
279 }
280 #define MSAN_MAYBE_INTERCEPT_MALLOC_STATS INTERCEPT_FUNCTION(malloc_stats)
281 #else
282 #define MSAN_MAYBE_INTERCEPT_MALLOC_STATS
283 #endif
284 
285 INTERCEPTOR(char *, strcpy, char *dest, const char *src) {  // NOLINT
286   ENSURE_MSAN_INITED();
287   GET_STORE_STACK_TRACE;
288   SIZE_T n = REAL(strlen)(src);
289   CHECK_UNPOISONED_STRING(src + n, 0);
290   char *res = REAL(strcpy)(dest, src);  // NOLINT
291   CopyShadowAndOrigin(dest, src, n + 1, &stack);
292   return res;
293 }
294 
295 INTERCEPTOR(char *, strncpy, char *dest, const char *src, SIZE_T n) {  // NOLINT
296   ENSURE_MSAN_INITED();
297   GET_STORE_STACK_TRACE;
298   SIZE_T copy_size = REAL(strnlen)(src, n);
299   if (copy_size < n)
300     copy_size++;  // trailing \0
301   char *res = REAL(strncpy)(dest, src, n);  // NOLINT
302   CopyShadowAndOrigin(dest, src, copy_size, &stack);
303   __msan_unpoison(dest + copy_size, n - copy_size);
304   return res;
305 }
306 
307 #if !SANITIZER_NETBSD
308 INTERCEPTOR(char *, stpcpy, char *dest, const char *src) {  // NOLINT
309   ENSURE_MSAN_INITED();
310   GET_STORE_STACK_TRACE;
311   SIZE_T n = REAL(strlen)(src);
312   CHECK_UNPOISONED_STRING(src + n, 0);
313   char *res = REAL(stpcpy)(dest, src);  // NOLINT
314   CopyShadowAndOrigin(dest, src, n + 1, &stack);
315   return res;
316 }
317 #define MSAN_MAYBE_INTERCEPT_STPCPY INTERCEPT_FUNCTION(stpcpy)
318 #else
319 #define MSAN_MAYBE_INTERCEPT_STPCPY
320 #endif
321 
322 INTERCEPTOR(char *, strdup, char *src) {
323   ENSURE_MSAN_INITED();
324   GET_STORE_STACK_TRACE;
325   // On FreeBSD strdup() leverages strlen().
326   InterceptorScope interceptor_scope;
327   SIZE_T n = REAL(strlen)(src);
328   CHECK_UNPOISONED_STRING(src + n, 0);
329   char *res = REAL(strdup)(src);
330   CopyShadowAndOrigin(res, src, n + 1, &stack);
331   return res;
332 }
333 
334 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
335 INTERCEPTOR(char *, __strdup, char *src) {
336   ENSURE_MSAN_INITED();
337   GET_STORE_STACK_TRACE;
338   SIZE_T n = REAL(strlen)(src);
339   CHECK_UNPOISONED_STRING(src + n, 0);
340   char *res = REAL(__strdup)(src);
341   CopyShadowAndOrigin(res, src, n + 1, &stack);
342   return res;
343 }
344 #define MSAN_MAYBE_INTERCEPT___STRDUP INTERCEPT_FUNCTION(__strdup)
345 #else
346 #define MSAN_MAYBE_INTERCEPT___STRDUP
347 #endif
348 
349 #if !SANITIZER_NETBSD
350 INTERCEPTOR(char *, gcvt, double number, SIZE_T ndigit, char *buf) {
351   ENSURE_MSAN_INITED();
352   char *res = REAL(gcvt)(number, ndigit, buf);
353   SIZE_T n = REAL(strlen)(buf);
354   __msan_unpoison(buf, n + 1);
355   return res;
356 }
357 #define MSAN_MAYBE_INTERCEPT_GCVT INTERCEPT_FUNCTION(gcvt)
358 #else
359 #define MSAN_MAYBE_INTERCEPT_GCVT
360 #endif
361 
362 INTERCEPTOR(char *, strcat, char *dest, const char *src) {  // NOLINT
363   ENSURE_MSAN_INITED();
364   GET_STORE_STACK_TRACE;
365   SIZE_T src_size = REAL(strlen)(src);
366   SIZE_T dest_size = REAL(strlen)(dest);
367   CHECK_UNPOISONED_STRING(src + src_size, 0);
368   CHECK_UNPOISONED_STRING(dest + dest_size, 0);
369   char *res = REAL(strcat)(dest, src);  // NOLINT
370   CopyShadowAndOrigin(dest + dest_size, src, src_size + 1, &stack);
371   return res;
372 }
373 
374 INTERCEPTOR(char *, strncat, char *dest, const char *src, SIZE_T n) {  // NOLINT
375   ENSURE_MSAN_INITED();
376   GET_STORE_STACK_TRACE;
377   SIZE_T dest_size = REAL(strlen)(dest);
378   SIZE_T copy_size = REAL(strnlen)(src, n);
379   CHECK_UNPOISONED_STRING(dest + dest_size, 0);
380   char *res = REAL(strncat)(dest, src, n);  // NOLINT
381   CopyShadowAndOrigin(dest + dest_size, src, copy_size, &stack);
382   __msan_unpoison(dest + dest_size + copy_size, 1); // \0
383   return res;
384 }
385 
386 // Hack: always pass nptr and endptr as part of __VA_ARGS_ to avoid having to
387 // deal with empty __VA_ARGS__ in the case of INTERCEPTOR_STRTO.
388 #define INTERCEPTOR_STRTO_BODY(ret_type, func, ...) \
389   ENSURE_MSAN_INITED();                             \
390   ret_type res = REAL(func)(__VA_ARGS__);           \
391   __msan_unpoison(endptr, sizeof(*endptr));         \
392   return res;
393 
394 #define INTERCEPTOR_STRTO(ret_type, func, char_type)                       \
395   INTERCEPTOR(ret_type, func, const char_type *nptr, char_type **endptr) { \
396     INTERCEPTOR_STRTO_BODY(ret_type, func, nptr, endptr);                  \
397   }
398 
399 #define INTERCEPTOR_STRTO_BASE(ret_type, func, char_type)                \
400   INTERCEPTOR(ret_type, func, const char_type *nptr, char_type **endptr, \
401               int base) {                                                \
402     INTERCEPTOR_STRTO_BODY(ret_type, func, nptr, endptr, base);          \
403   }
404 
405 #define INTERCEPTOR_STRTO_LOC(ret_type, func, char_type)                 \
406   INTERCEPTOR(ret_type, func, const char_type *nptr, char_type **endptr, \
407               void *loc) {                                               \
408     INTERCEPTOR_STRTO_BODY(ret_type, func, nptr, endptr, loc);           \
409   }
410 
411 #define INTERCEPTOR_STRTO_BASE_LOC(ret_type, func, char_type)            \
412   INTERCEPTOR(ret_type, func, const char_type *nptr, char_type **endptr, \
413               int base, void *loc) {                                     \
414     INTERCEPTOR_STRTO_BODY(ret_type, func, nptr, endptr, base, loc);     \
415   }
416 
417 #if SANITIZER_NETBSD
418 #define INTERCEPTORS_STRTO(ret_type, func, char_type)      \
419   INTERCEPTOR_STRTO(ret_type, func, char_type)             \
420   INTERCEPTOR_STRTO_LOC(ret_type, func##_l, char_type)
421 
422 #define INTERCEPTORS_STRTO_BASE(ret_type, func, char_type)      \
423   INTERCEPTOR_STRTO_BASE(ret_type, func, char_type)             \
424   INTERCEPTOR_STRTO_BASE_LOC(ret_type, func##_l, char_type)
425 
426 #else
427 #define INTERCEPTORS_STRTO(ret_type, func, char_type)      \
428   INTERCEPTOR_STRTO(ret_type, func, char_type)             \
429   INTERCEPTOR_STRTO_LOC(ret_type, func##_l, char_type)     \
430   INTERCEPTOR_STRTO_LOC(ret_type, __##func##_l, char_type) \
431   INTERCEPTOR_STRTO_LOC(ret_type, __##func##_internal, char_type)
432 
433 #define INTERCEPTORS_STRTO_BASE(ret_type, func, char_type)      \
434   INTERCEPTOR_STRTO_BASE(ret_type, func, char_type)             \
435   INTERCEPTOR_STRTO_BASE_LOC(ret_type, func##_l, char_type)     \
436   INTERCEPTOR_STRTO_BASE_LOC(ret_type, __##func##_l, char_type) \
437   INTERCEPTOR_STRTO_BASE_LOC(ret_type, __##func##_internal, char_type)
438 #endif
439 
440 INTERCEPTORS_STRTO(double, strtod, char)                     // NOLINT
441 INTERCEPTORS_STRTO(float, strtof, char)                      // NOLINT
442 INTERCEPTORS_STRTO(long double, strtold, char)               // NOLINT
443 INTERCEPTORS_STRTO_BASE(long, strtol, char)                  // NOLINT
444 INTERCEPTORS_STRTO_BASE(long long, strtoll, char)            // NOLINT
445 INTERCEPTORS_STRTO_BASE(unsigned long, strtoul, char)        // NOLINT
446 INTERCEPTORS_STRTO_BASE(unsigned long long, strtoull, char)  // NOLINT
447 INTERCEPTORS_STRTO_BASE(u64, strtouq, char)                  // NOLINT
448 
449 INTERCEPTORS_STRTO(double, wcstod, wchar_t)                     // NOLINT
450 INTERCEPTORS_STRTO(float, wcstof, wchar_t)                      // NOLINT
451 INTERCEPTORS_STRTO(long double, wcstold, wchar_t)               // NOLINT
452 INTERCEPTORS_STRTO_BASE(long, wcstol, wchar_t)                  // NOLINT
453 INTERCEPTORS_STRTO_BASE(long long, wcstoll, wchar_t)            // NOLINT
454 INTERCEPTORS_STRTO_BASE(unsigned long, wcstoul, wchar_t)        // NOLINT
455 INTERCEPTORS_STRTO_BASE(unsigned long long, wcstoull, wchar_t)  // NOLINT
456 
457 #if SANITIZER_NETBSD
458 #define INTERCEPT_STRTO(func) \
459   INTERCEPT_FUNCTION(func); \
460   INTERCEPT_FUNCTION(func##_l);
461 #else
462 #define INTERCEPT_STRTO(func) \
463   INTERCEPT_FUNCTION(func); \
464   INTERCEPT_FUNCTION(func##_l); \
465   INTERCEPT_FUNCTION(__##func##_l); \
466   INTERCEPT_FUNCTION(__##func##_internal);
467 #endif
468 
469 
470 // FIXME: support *wprintf in common format interceptors.
471 INTERCEPTOR(int, vswprintf, void *str, uptr size, void *format, va_list ap) {
472   ENSURE_MSAN_INITED();
473   int res = REAL(vswprintf)(str, size, format, ap);
474   if (res >= 0) {
475     __msan_unpoison(str, 4 * (res + 1));
476   }
477   return res;
478 }
479 
480 INTERCEPTOR(int, swprintf, void *str, uptr size, void *format, ...) {
481   ENSURE_MSAN_INITED();
482   va_list ap;
483   va_start(ap, format);
484   int res = vswprintf(str, size, format, ap);
485   va_end(ap);
486   return res;
487 }
488 
489 #define INTERCEPTOR_STRFTIME_BODY(char_type, ret_type, func, s, ...) \
490   ENSURE_MSAN_INITED();                                              \
491   InterceptorScope interceptor_scope;                                \
492   ret_type res = REAL(func)(s, __VA_ARGS__);                         \
493   if (s) __msan_unpoison(s, sizeof(char_type) * (res + 1));          \
494   return res;
495 
496 INTERCEPTOR(SIZE_T, strftime, char *s, SIZE_T max, const char *format,
497             __sanitizer_tm *tm) {
498   INTERCEPTOR_STRFTIME_BODY(char, SIZE_T, strftime, s, max, format, tm);
499 }
500 
501 INTERCEPTOR(SIZE_T, strftime_l, char *s, SIZE_T max, const char *format,
502             __sanitizer_tm *tm, void *loc) {
503   INTERCEPTOR_STRFTIME_BODY(char, SIZE_T, strftime_l, s, max, format, tm, loc);
504 }
505 
506 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
507 INTERCEPTOR(SIZE_T, __strftime_l, char *s, SIZE_T max, const char *format,
508             __sanitizer_tm *tm, void *loc) {
509   INTERCEPTOR_STRFTIME_BODY(char, SIZE_T, __strftime_l, s, max, format, tm,
510                             loc);
511 }
512 #define MSAN_MAYBE_INTERCEPT___STRFTIME_L INTERCEPT_FUNCTION(__strftime_l)
513 #else
514 #define MSAN_MAYBE_INTERCEPT___STRFTIME_L
515 #endif
516 
517 INTERCEPTOR(SIZE_T, wcsftime, wchar_t *s, SIZE_T max, const wchar_t *format,
518             __sanitizer_tm *tm) {
519   INTERCEPTOR_STRFTIME_BODY(wchar_t, SIZE_T, wcsftime, s, max, format, tm);
520 }
521 
522 INTERCEPTOR(SIZE_T, wcsftime_l, wchar_t *s, SIZE_T max, const wchar_t *format,
523             __sanitizer_tm *tm, void *loc) {
524   INTERCEPTOR_STRFTIME_BODY(wchar_t, SIZE_T, wcsftime_l, s, max, format, tm,
525                             loc);
526 }
527 
528 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
529 INTERCEPTOR(SIZE_T, __wcsftime_l, wchar_t *s, SIZE_T max, const wchar_t *format,
530             __sanitizer_tm *tm, void *loc) {
531   INTERCEPTOR_STRFTIME_BODY(wchar_t, SIZE_T, __wcsftime_l, s, max, format, tm,
532                             loc);
533 }
534 #define MSAN_MAYBE_INTERCEPT___WCSFTIME_L INTERCEPT_FUNCTION(__wcsftime_l)
535 #else
536 #define MSAN_MAYBE_INTERCEPT___WCSFTIME_L
537 #endif
538 
539 INTERCEPTOR(int, mbtowc, wchar_t *dest, const char *src, SIZE_T n) {
540   ENSURE_MSAN_INITED();
541   int res = REAL(mbtowc)(dest, src, n);
542   if (res != -1 && dest) __msan_unpoison(dest, sizeof(wchar_t));
543   return res;
544 }
545 
546 INTERCEPTOR(SIZE_T, mbrtowc, wchar_t *dest, const char *src, SIZE_T n,
547             void *ps) {
548   ENSURE_MSAN_INITED();
549   SIZE_T res = REAL(mbrtowc)(dest, src, n, ps);
550   if (res != (SIZE_T)-1 && dest) __msan_unpoison(dest, sizeof(wchar_t));
551   return res;
552 }
553 
554 // wchar_t *wmemcpy(wchar_t *dest, const wchar_t *src, SIZE_T n);
555 INTERCEPTOR(wchar_t *, wmemcpy, wchar_t *dest, const wchar_t *src, SIZE_T n) {
556   ENSURE_MSAN_INITED();
557   GET_STORE_STACK_TRACE;
558   wchar_t *res = REAL(wmemcpy)(dest, src, n);
559   CopyShadowAndOrigin(dest, src, n * sizeof(wchar_t), &stack);
560   return res;
561 }
562 
563 #if !SANITIZER_NETBSD
564 INTERCEPTOR(wchar_t *, wmempcpy, wchar_t *dest, const wchar_t *src, SIZE_T n) {
565   ENSURE_MSAN_INITED();
566   GET_STORE_STACK_TRACE;
567   wchar_t *res = REAL(wmempcpy)(dest, src, n);
568   CopyShadowAndOrigin(dest, src, n * sizeof(wchar_t), &stack);
569   return res;
570 }
571 #define MSAN_MAYBE_INTERCEPT_WMEMPCPY INTERCEPT_FUNCTION(wmempcpy)
572 #else
573 #define MSAN_MAYBE_INTERCEPT_WMEMPCPY
574 #endif
575 
576 INTERCEPTOR(wchar_t *, wmemset, wchar_t *s, wchar_t c, SIZE_T n) {
577   CHECK(MEM_IS_APP(s));
578   ENSURE_MSAN_INITED();
579   wchar_t *res = REAL(wmemset)(s, c, n);
580   __msan_unpoison(s, n * sizeof(wchar_t));
581   return res;
582 }
583 
584 INTERCEPTOR(wchar_t *, wmemmove, wchar_t *dest, const wchar_t *src, SIZE_T n) {
585   ENSURE_MSAN_INITED();
586   GET_STORE_STACK_TRACE;
587   wchar_t *res = REAL(wmemmove)(dest, src, n);
588   MoveShadowAndOrigin(dest, src, n * sizeof(wchar_t), &stack);
589   return res;
590 }
591 
592 INTERCEPTOR(int, wcscmp, const wchar_t *s1, const wchar_t *s2) {
593   ENSURE_MSAN_INITED();
594   int res = REAL(wcscmp)(s1, s2);
595   return res;
596 }
597 
598 INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
599   ENSURE_MSAN_INITED();
600   int res = REAL(gettimeofday)(tv, tz);
601   if (tv)
602     __msan_unpoison(tv, 16);
603   if (tz)
604     __msan_unpoison(tz, 8);
605   return res;
606 }
607 
608 #if !SANITIZER_NETBSD
609 INTERCEPTOR(char *, fcvt, double x, int a, int *b, int *c) {
610   ENSURE_MSAN_INITED();
611   char *res = REAL(fcvt)(x, a, b, c);
612   __msan_unpoison(b, sizeof(*b));
613   __msan_unpoison(c, sizeof(*c));
614   if (res) __msan_unpoison(res, REAL(strlen)(res) + 1);
615   return res;
616 }
617 #define MSAN_MAYBE_INTERCEPT_FCVT INTERCEPT_FUNCTION(fcvt)
618 #else
619 #define MSAN_MAYBE_INTERCEPT_FCVT
620 #endif
621 
622 INTERCEPTOR(char *, getenv, char *name) {
623   if (msan_init_is_running)
624     return REAL(getenv)(name);
625   ENSURE_MSAN_INITED();
626   char *res = REAL(getenv)(name);
627   if (res) __msan_unpoison(res, REAL(strlen)(res) + 1);
628   return res;
629 }
630 
631 extern char **environ;
632 
633 static void UnpoisonEnviron() {
634   char **envp = environ;
635   for (; *envp; ++envp) {
636     __msan_unpoison(envp, sizeof(*envp));
637     __msan_unpoison(*envp, REAL(strlen)(*envp) + 1);
638   }
639   // Trailing NULL pointer.
640   __msan_unpoison(envp, sizeof(*envp));
641 }
642 
643 INTERCEPTOR(int, setenv, const char *name, const char *value, int overwrite) {
644   ENSURE_MSAN_INITED();
645   CHECK_UNPOISONED_STRING(name, 0);
646   int res = REAL(setenv)(name, value, overwrite);
647   if (!res) UnpoisonEnviron();
648   return res;
649 }
650 
651 INTERCEPTOR(int, putenv, char *string) {
652   ENSURE_MSAN_INITED();
653   int res = REAL(putenv)(string);
654   if (!res) UnpoisonEnviron();
655   return res;
656 }
657 
658 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
659 INTERCEPTOR(int, fstat, int fd, void *buf) {
660   ENSURE_MSAN_INITED();
661   int res = REAL(fstat)(fd, buf);
662   if (!res)
663     __msan_unpoison(buf, __sanitizer::struct_stat_sz);
664   return res;
665 }
666 #define MSAN_MAYBE_INTERCEPT_FSTAT INTERCEPT_FUNCTION(fstat)
667 #else
668 #define MSAN_MAYBE_INTERCEPT_FSTAT
669 #endif
670 
671 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
672 INTERCEPTOR(int, __fxstat, int magic, int fd, void *buf) {
673   ENSURE_MSAN_INITED();
674   int res = REAL(__fxstat)(magic, fd, buf);
675   if (!res)
676     __msan_unpoison(buf, __sanitizer::struct_stat_sz);
677   return res;
678 }
679 #define MSAN_MAYBE_INTERCEPT___FXSTAT INTERCEPT_FUNCTION(__fxstat)
680 #else
681 #define MSAN_MAYBE_INTERCEPT___FXSTAT
682 #endif
683 
684 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
685 INTERCEPTOR(int, __fxstat64, int magic, int fd, void *buf) {
686   ENSURE_MSAN_INITED();
687   int res = REAL(__fxstat64)(magic, fd, buf);
688   if (!res)
689     __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
690   return res;
691 }
692 #define MSAN_MAYBE_INTERCEPT___FXSTAT64 INTERCEPT_FUNCTION(__fxstat64)
693 #else
694 #define MSAN_MAYBE_INTERCEPT___FXSTAT64
695 #endif
696 
697 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
698 INTERCEPTOR(int, fstatat, int fd, char *pathname, void *buf, int flags) {
699   ENSURE_MSAN_INITED();
700   int res = REAL(fstatat)(fd, pathname, buf, flags);
701   if (!res) __msan_unpoison(buf, __sanitizer::struct_stat_sz);
702   return res;
703 }
704 # define MSAN_INTERCEPT_FSTATAT INTERCEPT_FUNCTION(fstatat)
705 #else
706 INTERCEPTOR(int, __fxstatat, int magic, int fd, char *pathname, void *buf,
707             int flags) {
708   ENSURE_MSAN_INITED();
709   int res = REAL(__fxstatat)(magic, fd, pathname, buf, flags);
710   if (!res) __msan_unpoison(buf, __sanitizer::struct_stat_sz);
711   return res;
712 }
713 # define MSAN_INTERCEPT_FSTATAT INTERCEPT_FUNCTION(__fxstatat)
714 #endif
715 
716 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
717 INTERCEPTOR(int, __fxstatat64, int magic, int fd, char *pathname, void *buf,
718             int flags) {
719   ENSURE_MSAN_INITED();
720   int res = REAL(__fxstatat64)(magic, fd, pathname, buf, flags);
721   if (!res) __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
722   return res;
723 }
724 #define MSAN_MAYBE_INTERCEPT___FXSTATAT64 INTERCEPT_FUNCTION(__fxstatat64)
725 #else
726 #define MSAN_MAYBE_INTERCEPT___FXSTATAT64
727 #endif
728 
729 INTERCEPTOR(int, pipe, int pipefd[2]) {
730   if (msan_init_is_running)
731     return REAL(pipe)(pipefd);
732   ENSURE_MSAN_INITED();
733   int res = REAL(pipe)(pipefd);
734   if (!res)
735     __msan_unpoison(pipefd, sizeof(int[2]));
736   return res;
737 }
738 
739 INTERCEPTOR(int, pipe2, int pipefd[2], int flags) {
740   ENSURE_MSAN_INITED();
741   int res = REAL(pipe2)(pipefd, flags);
742   if (!res)
743     __msan_unpoison(pipefd, sizeof(int[2]));
744   return res;
745 }
746 
747 INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int sv[2]) {
748   ENSURE_MSAN_INITED();
749   int res = REAL(socketpair)(domain, type, protocol, sv);
750   if (!res)
751     __msan_unpoison(sv, sizeof(int[2]));
752   return res;
753 }
754 
755 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
756 INTERCEPTOR(char *, fgets_unlocked, char *s, int size, void *stream) {
757   ENSURE_MSAN_INITED();
758   char *res = REAL(fgets_unlocked)(s, size, stream);
759   if (res)
760     __msan_unpoison(s, REAL(strlen)(s) + 1);
761   return res;
762 }
763 #define MSAN_MAYBE_INTERCEPT_FGETS_UNLOCKED INTERCEPT_FUNCTION(fgets_unlocked)
764 #else
765 #define MSAN_MAYBE_INTERCEPT_FGETS_UNLOCKED
766 #endif
767 
768 INTERCEPTOR(int, getrlimit, int resource, void *rlim) {
769   if (msan_init_is_running)
770     return REAL(getrlimit)(resource, rlim);
771   ENSURE_MSAN_INITED();
772   int res = REAL(getrlimit)(resource, rlim);
773   if (!res)
774     __msan_unpoison(rlim, __sanitizer::struct_rlimit_sz);
775   return res;
776 }
777 
778 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
779 INTERCEPTOR(int, getrlimit64, int resource, void *rlim) {
780   if (msan_init_is_running) return REAL(getrlimit64)(resource, rlim);
781   ENSURE_MSAN_INITED();
782   int res = REAL(getrlimit64)(resource, rlim);
783   if (!res) __msan_unpoison(rlim, __sanitizer::struct_rlimit64_sz);
784   return res;
785 }
786 
787 INTERCEPTOR(int, prlimit, int pid, int resource, void *new_rlimit,
788             void *old_rlimit) {
789   if (msan_init_is_running)
790     return REAL(prlimit)(pid, resource, new_rlimit, old_rlimit);
791   ENSURE_MSAN_INITED();
792   CHECK_UNPOISONED(new_rlimit, __sanitizer::struct_rlimit_sz);
793   int res = REAL(prlimit)(pid, resource, new_rlimit, old_rlimit);
794   if (!res) __msan_unpoison(old_rlimit, __sanitizer::struct_rlimit_sz);
795   return res;
796 }
797 
798 INTERCEPTOR(int, prlimit64, int pid, int resource, void *new_rlimit,
799             void *old_rlimit) {
800   if (msan_init_is_running)
801     return REAL(prlimit64)(pid, resource, new_rlimit, old_rlimit);
802   ENSURE_MSAN_INITED();
803   CHECK_UNPOISONED(new_rlimit, __sanitizer::struct_rlimit64_sz);
804   int res = REAL(prlimit64)(pid, resource, new_rlimit, old_rlimit);
805   if (!res) __msan_unpoison(old_rlimit, __sanitizer::struct_rlimit64_sz);
806   return res;
807 }
808 
809 #define MSAN_MAYBE_INTERCEPT_GETRLIMIT64 INTERCEPT_FUNCTION(getrlimit64)
810 #define MSAN_MAYBE_INTERCEPT_PRLIMIT INTERCEPT_FUNCTION(prlimit)
811 #define MSAN_MAYBE_INTERCEPT_PRLIMIT64 INTERCEPT_FUNCTION(prlimit64)
812 #else
813 #define MSAN_MAYBE_INTERCEPT_GETRLIMIT64
814 #define MSAN_MAYBE_INTERCEPT_PRLIMIT
815 #define MSAN_MAYBE_INTERCEPT_PRLIMIT64
816 #endif
817 
818 #if SANITIZER_FREEBSD
819 // FreeBSD's <sys/utsname.h> define uname() as
820 // static __inline int uname(struct utsname *name) {
821 //   return __xuname(SYS_NMLN, (void*)name);
822 // }
823 INTERCEPTOR(int, __xuname, int size, void *utsname) {
824   ENSURE_MSAN_INITED();
825   int res = REAL(__xuname)(size, utsname);
826   if (!res)
827     __msan_unpoison(utsname, __sanitizer::struct_utsname_sz);
828   return res;
829 }
830 #define MSAN_INTERCEPT_UNAME INTERCEPT_FUNCTION(__xuname)
831 #else
832 INTERCEPTOR(int, uname, struct utsname *utsname) {
833   ENSURE_MSAN_INITED();
834   int res = REAL(uname)(utsname);
835   if (!res)
836     __msan_unpoison(utsname, __sanitizer::struct_utsname_sz);
837   return res;
838 }
839 #define MSAN_INTERCEPT_UNAME INTERCEPT_FUNCTION(uname)
840 #endif
841 
842 INTERCEPTOR(int, gethostname, char *name, SIZE_T len) {
843   ENSURE_MSAN_INITED();
844   int res = REAL(gethostname)(name, len);
845   if (!res) {
846     SIZE_T real_len = REAL(strnlen)(name, len);
847     if (real_len < len)
848       ++real_len;
849     __msan_unpoison(name, real_len);
850   }
851   return res;
852 }
853 
854 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
855 INTERCEPTOR(int, epoll_wait, int epfd, void *events, int maxevents,
856     int timeout) {
857   ENSURE_MSAN_INITED();
858   int res = REAL(epoll_wait)(epfd, events, maxevents, timeout);
859   if (res > 0) {
860     __msan_unpoison(events, __sanitizer::struct_epoll_event_sz * res);
861   }
862   return res;
863 }
864 #define MSAN_MAYBE_INTERCEPT_EPOLL_WAIT INTERCEPT_FUNCTION(epoll_wait)
865 #else
866 #define MSAN_MAYBE_INTERCEPT_EPOLL_WAIT
867 #endif
868 
869 #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
870 INTERCEPTOR(int, epoll_pwait, int epfd, void *events, int maxevents,
871     int timeout, void *sigmask) {
872   ENSURE_MSAN_INITED();
873   int res = REAL(epoll_pwait)(epfd, events, maxevents, timeout, sigmask);
874   if (res > 0) {
875     __msan_unpoison(events, __sanitizer::struct_epoll_event_sz * res);
876   }
877   return res;
878 }
879 #define MSAN_MAYBE_INTERCEPT_EPOLL_PWAIT INTERCEPT_FUNCTION(epoll_pwait)
880 #else
881 #define MSAN_MAYBE_INTERCEPT_EPOLL_PWAIT
882 #endif
883 
884 INTERCEPTOR(void *, calloc, SIZE_T nmemb, SIZE_T size) {
885   GET_MALLOC_STACK_TRACE;
886   if (UNLIKELY(!msan_inited))
887     // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym.
888     return AllocateFromLocalPool(nmemb * size);
889   return msan_calloc(nmemb, size, &stack);
890 }
891 
892 INTERCEPTOR(void *, realloc, void *ptr, SIZE_T size) {
893   GET_MALLOC_STACK_TRACE;
894   if (UNLIKELY(IsInDlsymAllocPool(ptr))) {
895     uptr offset = (uptr)ptr - (uptr)alloc_memory_for_dlsym;
896     uptr copy_size = Min(size, kDlsymAllocPoolSize - offset);
897     void *new_ptr;
898     if (UNLIKELY(!msan_inited)) {
899       new_ptr = AllocateFromLocalPool(copy_size);
900     } else {
901       copy_size = size;
902       new_ptr = msan_malloc(copy_size, &stack);
903     }
904     internal_memcpy(new_ptr, ptr, copy_size);
905     return new_ptr;
906   }
907   return msan_realloc(ptr, size, &stack);
908 }
909 
910 INTERCEPTOR(void *, reallocarray, void *ptr, SIZE_T nmemb, SIZE_T size) {
911   GET_MALLOC_STACK_TRACE;
912   return msan_reallocarray(ptr, nmemb, size, &stack);
913 }
914 
915 INTERCEPTOR(void *, malloc, SIZE_T size) {
916   GET_MALLOC_STACK_TRACE;
917   if (UNLIKELY(!msan_inited))
918     // Hack: dlsym calls malloc before REAL(malloc) is retrieved from dlsym.
919     return AllocateFromLocalPool(size);
920   return msan_malloc(size, &stack);
921 }
922 
923 void __msan_allocated_memory(const void *data, uptr size) {
924   GET_MALLOC_STACK_TRACE;
925   if (flags()->poison_in_malloc) {
926     stack.tag = STACK_TRACE_TAG_POISON;
927     PoisonMemory(data, size, &stack);
928   }
929 }
930 
931 void __msan_copy_shadow(void *dest, const void *src, uptr n) {
932   GET_STORE_STACK_TRACE;
933   MoveShadowAndOrigin(dest, src, n, &stack);
934 }
935 
936 void __sanitizer_dtor_callback(const void *data, uptr size) {
937   GET_MALLOC_STACK_TRACE;
938   if (flags()->poison_in_dtor) {
939     stack.tag = STACK_TRACE_TAG_POISON;
940     PoisonMemory(data, size, &stack);
941   }
942 }
943 
944 template <class Mmap>
945 static void *mmap_interceptor(Mmap real_mmap, void *addr, SIZE_T length,
946                               int prot, int flags, int fd, OFF64_T offset) {
947   if (addr && !MEM_IS_APP(addr)) {
948     if (flags & map_fixed) {
949       errno = errno_EINVAL;
950       return (void *)-1;
951     } else {
952       addr = nullptr;
953     }
954   }
955   void *res = real_mmap(addr, length, prot, flags, fd, offset);
956   if (res != (void *)-1) __msan_unpoison(res, RoundUpTo(length, GetPageSize()));
957   return res;
958 }
959 
960 INTERCEPTOR(int, getrusage, int who, void *usage) {
961   ENSURE_MSAN_INITED();
962   int res = REAL(getrusage)(who, usage);
963   if (res == 0) {
964     __msan_unpoison(usage, __sanitizer::struct_rusage_sz);
965   }
966   return res;
967 }
968 
969 class SignalHandlerScope {
970  public:
971   SignalHandlerScope() {
972     if (MsanThread *t = GetCurrentThread())
973       t->EnterSignalHandler();
974   }
975   ~SignalHandlerScope() {
976     if (MsanThread *t = GetCurrentThread())
977       t->LeaveSignalHandler();
978   }
979 };
980 
981 // sigactions_mu guarantees atomicity of sigaction() and signal() calls.
982 // Access to sigactions[] is gone with relaxed atomics to avoid data race with
983 // the signal handler.
984 const int kMaxSignals = 1024;
985 static atomic_uintptr_t sigactions[kMaxSignals];
986 static StaticSpinMutex sigactions_mu;
987 
988 static void SignalHandler(int signo) {
989   SignalHandlerScope signal_handler_scope;
990   ScopedThreadLocalStateBackup stlsb;
991   UnpoisonParam(1);
992 
993   typedef void (*signal_cb)(int x);
994   signal_cb cb =
995       (signal_cb)atomic_load(&sigactions[signo], memory_order_relaxed);
996   cb(signo);
997 }
998 
999 static void SignalAction(int signo, void *si, void *uc) {
1000   SignalHandlerScope signal_handler_scope;
1001   ScopedThreadLocalStateBackup stlsb;
1002   UnpoisonParam(3);
1003   __msan_unpoison(si, sizeof(__sanitizer_sigaction));
1004   __msan_unpoison(uc, __sanitizer::ucontext_t_sz);
1005 
1006   typedef void (*sigaction_cb)(int, void *, void *);
1007   sigaction_cb cb =
1008       (sigaction_cb)atomic_load(&sigactions[signo], memory_order_relaxed);
1009   cb(signo, si, uc);
1010 }
1011 
1012 static void read_sigaction(const __sanitizer_sigaction *act) {
1013   CHECK_UNPOISONED(&act->sa_flags, sizeof(act->sa_flags));
1014   if (act->sa_flags & __sanitizer::sa_siginfo)
1015     CHECK_UNPOISONED(&act->sigaction, sizeof(act->sigaction));
1016   else
1017     CHECK_UNPOISONED(&act->handler, sizeof(act->handler));
1018   CHECK_UNPOISONED(&act->sa_mask, sizeof(act->sa_mask));
1019 }
1020 
1021 extern "C" int pthread_attr_init(void *attr);
1022 extern "C" int pthread_attr_destroy(void *attr);
1023 
1024 static void *MsanThreadStartFunc(void *arg) {
1025   MsanThread *t = (MsanThread *)arg;
1026   SetCurrentThread(t);
1027   return t->ThreadStart();
1028 }
1029 
1030 INTERCEPTOR(int, pthread_create, void *th, void *attr, void *(*callback)(void*),
1031             void * param) {
1032   ENSURE_MSAN_INITED(); // for GetTlsSize()
1033   __sanitizer_pthread_attr_t myattr;
1034   if (!attr) {
1035     pthread_attr_init(&myattr);
1036     attr = &myattr;
1037   }
1038 
1039   AdjustStackSize(attr);
1040 
1041   MsanThread *t = MsanThread::Create(callback, param);
1042 
1043   int res = REAL(pthread_create)(th, attr, MsanThreadStartFunc, t);
1044 
1045   if (attr == &myattr)
1046     pthread_attr_destroy(&myattr);
1047   if (!res) {
1048     __msan_unpoison(th, __sanitizer::pthread_t_sz);
1049   }
1050   return res;
1051 }
1052 
1053 INTERCEPTOR(int, pthread_key_create, __sanitizer_pthread_key_t *key,
1054             void (*dtor)(void *value)) {
1055   if (msan_init_is_running) return REAL(pthread_key_create)(key, dtor);
1056   ENSURE_MSAN_INITED();
1057   int res = REAL(pthread_key_create)(key, dtor);
1058   if (!res && key)
1059     __msan_unpoison(key, sizeof(*key));
1060   return res;
1061 }
1062 
1063 #if SANITIZER_NETBSD
1064 INTERCEPTOR(void, __libc_thr_keycreate, void *m, void (*dtor)(void *value)) \
1065   ALIAS(WRAPPER_NAME(pthread_key_create));
1066 #endif
1067 
1068 INTERCEPTOR(int, pthread_join, void *th, void **retval) {
1069   ENSURE_MSAN_INITED();
1070   int res = REAL(pthread_join)(th, retval);
1071   if (!res && retval)
1072     __msan_unpoison(retval, sizeof(*retval));
1073   return res;
1074 }
1075 
1076 extern char *tzname[2];
1077 
1078 INTERCEPTOR(void, tzset, int fake) {
1079   ENSURE_MSAN_INITED();
1080   InterceptorScope interceptor_scope;
1081   REAL(tzset)(fake);
1082   if (tzname[0])
1083     __msan_unpoison(tzname[0], REAL(strlen)(tzname[0]) + 1);
1084   if (tzname[1])
1085     __msan_unpoison(tzname[1], REAL(strlen)(tzname[1]) + 1);
1086   return;
1087 }
1088 
1089 struct MSanAtExitRecord {
1090   void (*func)(void *arg);
1091   void *arg;
1092 };
1093 
1094 struct InterceptorContext {
1095   BlockingMutex atexit_mu;
1096   Vector<struct MSanAtExitRecord *> AtExitStack;
1097 
1098   InterceptorContext()
1099       : AtExitStack() {
1100   }
1101 };
1102 
1103 static ALIGNED(64) char interceptor_placeholder[sizeof(InterceptorContext)];
1104 InterceptorContext *interceptor_ctx() {
1105   return reinterpret_cast<InterceptorContext*>(&interceptor_placeholder[0]);
1106 }
1107 
1108 void MSanAtExitWrapper() {
1109   MSanAtExitRecord *r;
1110   {
1111     BlockingMutexLock l(&interceptor_ctx()->atexit_mu);
1112 
1113     uptr element = interceptor_ctx()->AtExitStack.Size() - 1;
1114     r = interceptor_ctx()->AtExitStack[element];
1115     interceptor_ctx()->AtExitStack.PopBack();
1116   }
1117 
1118   UnpoisonParam(1);
1119   ((void(*)())r->func)();
1120   InternalFree(r);
1121 }
1122 
1123 void MSanCxaAtExitWrapper(void *arg) {
1124   UnpoisonParam(1);
1125   MSanAtExitRecord *r = (MSanAtExitRecord *)arg;
1126   // libc before 2.27 had race which caused occasional double handler execution
1127   // https://sourceware.org/ml/libc-alpha/2017-08/msg01204.html
1128   if (!r->func)
1129     return;
1130   r->func(r->arg);
1131   r->func = nullptr;
1132 }
1133 
1134 static int setup_at_exit_wrapper(void(*f)(), void *arg, void *dso);
1135 
1136 // Unpoison argument shadow for C++ module destructors.
1137 INTERCEPTOR(int, __cxa_atexit, void (*func)(void *), void *arg,
1138             void *dso_handle) {
1139   if (msan_init_is_running) return REAL(__cxa_atexit)(func, arg, dso_handle);
1140   return setup_at_exit_wrapper((void(*)())func, arg, dso_handle);
1141 }
1142 
1143 // Unpoison argument shadow for C++ module destructors.
1144 INTERCEPTOR(int, atexit, void (*func)()) {
1145   // Avoid calling real atexit as it is unrechable on at least on Linux.
1146   if (msan_init_is_running)
1147     return REAL(__cxa_atexit)((void (*)(void *a))func, 0, 0);
1148   return setup_at_exit_wrapper((void(*)())func, 0, 0);
1149 }
1150 
1151 static int setup_at_exit_wrapper(void(*f)(), void *arg, void *dso) {
1152   ENSURE_MSAN_INITED();
1153   MSanAtExitRecord *r =
1154       (MSanAtExitRecord *)InternalAlloc(sizeof(MSanAtExitRecord));
1155   r->func = (void(*)(void *a))f;
1156   r->arg = arg;
1157   int res;
1158   if (!dso) {
1159     // NetBSD does not preserve the 2nd argument if dso is equal to 0
1160     // Store ctx in a local stack-like structure
1161 
1162     BlockingMutexLock l(&interceptor_ctx()->atexit_mu);
1163 
1164     res = REAL(__cxa_atexit)((void (*)(void *a))MSanAtExitWrapper, 0, 0);
1165     if (!res) {
1166       interceptor_ctx()->AtExitStack.PushBack(r);
1167     }
1168   } else {
1169     res = REAL(__cxa_atexit)(MSanCxaAtExitWrapper, r, dso);
1170   }
1171   return res;
1172 }
1173 
1174 static void BeforeFork() {
1175   StackDepotLockAll();
1176   ChainedOriginDepotLockAll();
1177 }
1178 
1179 static void AfterFork() {
1180   ChainedOriginDepotUnlockAll();
1181   StackDepotUnlockAll();
1182 }
1183 
1184 INTERCEPTOR(int, fork, void) {
1185   ENSURE_MSAN_INITED();
1186   BeforeFork();
1187   int pid = REAL(fork)();
1188   AfterFork();
1189   return pid;
1190 }
1191 
1192 // NetBSD ships with openpty(3) in -lutil, that needs to be prebuilt explicitly
1193 // with MSan.
1194 #if SANITIZER_LINUX
1195 INTERCEPTOR(int, openpty, int *aparent, int *aworker, char *name,
1196             const void *termp, const void *winp) {
1197   ENSURE_MSAN_INITED();
1198   InterceptorScope interceptor_scope;
1199   int res = REAL(openpty)(aparent, aworker, name, termp, winp);
1200   if (!res) {
1201     __msan_unpoison(aparent, sizeof(*aparent));
1202     __msan_unpoison(aworker, sizeof(*aworker));
1203   }
1204   return res;
1205 }
1206 #define MSAN_MAYBE_INTERCEPT_OPENPTY INTERCEPT_FUNCTION(openpty)
1207 #else
1208 #define MSAN_MAYBE_INTERCEPT_OPENPTY
1209 #endif
1210 
1211 // NetBSD ships with forkpty(3) in -lutil, that needs to be prebuilt explicitly
1212 // with MSan.
1213 #if SANITIZER_LINUX
1214 INTERCEPTOR(int, forkpty, int *aparent, char *name, const void *termp,
1215             const void *winp) {
1216   ENSURE_MSAN_INITED();
1217   InterceptorScope interceptor_scope;
1218   int res = REAL(forkpty)(aparent, name, termp, winp);
1219   if (res != -1)
1220     __msan_unpoison(aparent, sizeof(*aparent));
1221   return res;
1222 }
1223 #define MSAN_MAYBE_INTERCEPT_FORKPTY INTERCEPT_FUNCTION(forkpty)
1224 #else
1225 #define MSAN_MAYBE_INTERCEPT_FORKPTY
1226 #endif
1227 
1228 struct MSanInterceptorContext {
1229   bool in_interceptor_scope;
1230 };
1231 
1232 namespace __msan {
1233 
1234 int OnExit() {
1235   // FIXME: ask frontend whether we need to return failure.
1236   return 0;
1237 }
1238 
1239 } // namespace __msan
1240 
1241 // A version of CHECK_UNPOISONED using a saved scope value. Used in common
1242 // interceptors.
1243 #define CHECK_UNPOISONED_CTX(ctx, x, n)                         \
1244   do {                                                          \
1245     if (!((MSanInterceptorContext *)ctx)->in_interceptor_scope) \
1246       CHECK_UNPOISONED_0(x, n);                                 \
1247   } while (0)
1248 
1249 #define MSAN_INTERCEPT_FUNC(name)                                        \
1250   do {                                                                   \
1251     if (!INTERCEPT_FUNCTION(name))                                       \
1252       VReport(1, "MemorySanitizer: failed to intercept '%s'\n'", #name); \
1253   } while (0)
1254 
1255 #define MSAN_INTERCEPT_FUNC_VER(name, ver)                                 \
1256   do {                                                                     \
1257     if (!INTERCEPT_FUNCTION_VER(name, ver))                                \
1258       VReport(1, "MemorySanitizer: failed to intercept '%s@@%s'\n", #name, \
1259               #ver);                                                       \
1260   } while (0)
1261 
1262 #define COMMON_INTERCEPT_FUNCTION(name) MSAN_INTERCEPT_FUNC(name)
1263 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver)                          \
1264   MSAN_INTERCEPT_FUNC_VER(name, ver)
1265 #define COMMON_INTERCEPTOR_UNPOISON_PARAM(count)  \
1266   UnpoisonParam(count)
1267 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
1268   __msan_unpoison(ptr, size)
1269 #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
1270   CHECK_UNPOISONED_CTX(ctx, ptr, size)
1271 #define COMMON_INTERCEPTOR_INITIALIZE_RANGE(ptr, size) \
1272   __msan_unpoison(ptr, size)
1273 #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...)                  \
1274   if (msan_init_is_running) return REAL(func)(__VA_ARGS__);       \
1275   ENSURE_MSAN_INITED();                                           \
1276   MSanInterceptorContext msan_ctx = {IsInInterceptorScope()};     \
1277   ctx = (void *)&msan_ctx;                                        \
1278   (void)ctx;                                                      \
1279   InterceptorScope interceptor_scope;                             \
1280   __msan_unpoison(__errno_location(), sizeof(int)); /* NOLINT */
1281 #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
1282   do {                                            \
1283   } while (false)
1284 #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
1285   do {                                         \
1286   } while (false)
1287 #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
1288   do {                                         \
1289   } while (false)
1290 #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
1291   do {                                                      \
1292   } while (false)
1293 #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
1294   do {                                                \
1295   } while (false)  // FIXME
1296 #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
1297   do {                                                         \
1298   } while (false)  // FIXME
1299 #define COMMON_INTERCEPTOR_BLOCK_REAL(name) REAL(name)
1300 #define COMMON_INTERCEPTOR_ON_EXIT(ctx) OnExit()
1301 #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle)                    \
1302   do {                                                                         \
1303     link_map *map = GET_LINK_MAP_BY_DLOPEN_HANDLE((handle));                   \
1304     if (filename && map)                                                       \
1305       ForEachMappedRegion(map, __msan_unpoison);                               \
1306   } while (false)
1307 
1308 #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end)                           \
1309   if (MsanThread *t = GetCurrentThread()) {                                    \
1310     *begin = t->tls_begin();                                                   \
1311     *end = t->tls_end();                                                       \
1312   } else {                                                                     \
1313     *begin = *end = 0;                                                         \
1314   }
1315 
1316 #define COMMON_INTERCEPTOR_MEMSET_IMPL(ctx, block, c, size) \
1317   {                                                         \
1318     (void)ctx;                                              \
1319     return __msan_memset(block, c, size);                   \
1320   }
1321 #define COMMON_INTERCEPTOR_MEMMOVE_IMPL(ctx, to, from, size) \
1322   {                                                          \
1323     (void)ctx;                                               \
1324     return __msan_memmove(to, from, size);                   \
1325   }
1326 #define COMMON_INTERCEPTOR_MEMCPY_IMPL(ctx, to, from, size) \
1327   {                                                         \
1328     (void)ctx;                                              \
1329     return __msan_memcpy(to, from, size);                   \
1330   }
1331 
1332 #define COMMON_INTERCEPTOR_COPY_STRING(ctx, to, from, size) \
1333   do {                                                      \
1334     GET_STORE_STACK_TRACE;                                  \
1335     CopyShadowAndOrigin(to, from, size, &stack);            \
1336     __msan_unpoison(to + size, 1);                          \
1337   } while (false)
1338 
1339 #define COMMON_INTERCEPTOR_MMAP_IMPL(ctx, mmap, addr, length, prot, flags, fd, \
1340                                      offset)                                   \
1341   do {                                                                         \
1342     return mmap_interceptor(REAL(mmap), addr, sz, prot, flags, fd, off);       \
1343   } while (false)
1344 
1345 #include "sanitizer_common/sanitizer_platform_interceptors.h"
1346 #include "sanitizer_common/sanitizer_common_interceptors.inc"
1347 
1348 static uptr signal_impl(int signo, uptr cb);
1349 static int sigaction_impl(int signo, const __sanitizer_sigaction *act,
1350                           __sanitizer_sigaction *oldact);
1351 
1352 #define SIGNAL_INTERCEPTOR_SIGACTION_IMPL(signo, act, oldact) \
1353   { return sigaction_impl(signo, act, oldact); }
1354 
1355 #define SIGNAL_INTERCEPTOR_SIGNAL_IMPL(func, signo, handler) \
1356   {                                                          \
1357     handler = signal_impl(signo, handler);                   \
1358     InterceptorScope interceptor_scope;                      \
1359     return REAL(func)(signo, handler);                       \
1360   }
1361 
1362 #include "sanitizer_common/sanitizer_signal_interceptors.inc"
1363 
1364 static int sigaction_impl(int signo, const __sanitizer_sigaction *act,
1365                           __sanitizer_sigaction *oldact) {
1366   ENSURE_MSAN_INITED();
1367   if (act) read_sigaction(act);
1368   int res;
1369   if (flags()->wrap_signals) {
1370     SpinMutexLock lock(&sigactions_mu);
1371     CHECK_LT(signo, kMaxSignals);
1372     uptr old_cb = atomic_load(&sigactions[signo], memory_order_relaxed);
1373     __sanitizer_sigaction new_act;
1374     __sanitizer_sigaction *pnew_act = act ? &new_act : nullptr;
1375     if (act) {
1376       REAL(memcpy)(pnew_act, act, sizeof(__sanitizer_sigaction));
1377       uptr cb = (uptr)pnew_act->sigaction;
1378       uptr new_cb = (pnew_act->sa_flags & __sanitizer::sa_siginfo)
1379                         ? (uptr)SignalAction
1380                         : (uptr)SignalHandler;
1381       if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) {
1382         atomic_store(&sigactions[signo], cb, memory_order_relaxed);
1383         pnew_act->sigaction = (decltype(pnew_act->sigaction))new_cb;
1384       }
1385     }
1386     res = REAL(SIGACTION_SYMNAME)(signo, pnew_act, oldact);
1387     if (res == 0 && oldact) {
1388       uptr cb = (uptr)oldact->sigaction;
1389       if (cb == (uptr)SignalAction || cb == (uptr)SignalHandler) {
1390         oldact->sigaction = (decltype(oldact->sigaction))old_cb;
1391       }
1392     }
1393   } else {
1394     res = REAL(SIGACTION_SYMNAME)(signo, act, oldact);
1395   }
1396 
1397   if (res == 0 && oldact) {
1398     __msan_unpoison(oldact, sizeof(__sanitizer_sigaction));
1399   }
1400   return res;
1401 }
1402 
1403 static uptr signal_impl(int signo, uptr cb) {
1404   ENSURE_MSAN_INITED();
1405   if (flags()->wrap_signals) {
1406     CHECK_LT(signo, kMaxSignals);
1407     SpinMutexLock lock(&sigactions_mu);
1408     if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) {
1409       atomic_store(&sigactions[signo], cb, memory_order_relaxed);
1410       cb = (uptr)&SignalHandler;
1411     }
1412   }
1413   return cb;
1414 }
1415 
1416 #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) CHECK_UNPOISONED(p, s)
1417 #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
1418   do {                                       \
1419   } while (false)
1420 #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
1421   do {                                       \
1422   } while (false)
1423 #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) __msan_unpoison(p, s)
1424 #include "sanitizer_common/sanitizer_common_syscalls.inc"
1425 #include "sanitizer_common/sanitizer_syscalls_netbsd.inc"
1426 
1427 struct dlinfo {
1428   char *dli_fname;
1429   void *dli_fbase;
1430   char *dli_sname;
1431   void *dli_saddr;
1432 };
1433 
1434 INTERCEPTOR(int, dladdr, void *addr, dlinfo *info) {
1435   void *ctx;
1436   COMMON_INTERCEPTOR_ENTER(ctx, dladdr, addr, info);
1437   int res = REAL(dladdr)(addr, info);
1438   if (res != 0) {
1439     __msan_unpoison(info, sizeof(*info));
1440     if (info->dli_fname)
1441       __msan_unpoison(info->dli_fname, REAL(strlen)(info->dli_fname) + 1);
1442     if (info->dli_sname)
1443       __msan_unpoison(info->dli_sname, REAL(strlen)(info->dli_sname) + 1);
1444   }
1445   return res;
1446 }
1447 
1448 INTERCEPTOR(char *, dlerror, int fake) {
1449   void *ctx;
1450   COMMON_INTERCEPTOR_ENTER(ctx, dlerror, fake);
1451   char *res = REAL(dlerror)(fake);
1452   if (res) __msan_unpoison(res, REAL(strlen)(res) + 1);
1453   return res;
1454 }
1455 
1456 typedef int (*dl_iterate_phdr_cb)(__sanitizer_dl_phdr_info *info, SIZE_T size,
1457                                   void *data);
1458 struct dl_iterate_phdr_data {
1459   dl_iterate_phdr_cb callback;
1460   void *data;
1461 };
1462 
1463 static int msan_dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
1464                                    void *data) {
1465   if (info) {
1466     __msan_unpoison(info, size);
1467     if (info->dlpi_phdr && info->dlpi_phnum)
1468       __msan_unpoison(info->dlpi_phdr, struct_ElfW_Phdr_sz * info->dlpi_phnum);
1469     if (info->dlpi_name)
1470       __msan_unpoison(info->dlpi_name, REAL(strlen)(info->dlpi_name) + 1);
1471   }
1472   dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
1473   UnpoisonParam(3);
1474   return cbdata->callback(info, size, cbdata->data);
1475 }
1476 
1477 INTERCEPTOR(void *, shmat, int shmid, const void *shmaddr, int shmflg) {
1478   ENSURE_MSAN_INITED();
1479   void *p = REAL(shmat)(shmid, shmaddr, shmflg);
1480   if (p != (void *)-1) {
1481     __sanitizer_shmid_ds ds;
1482     int res = REAL(shmctl)(shmid, shmctl_ipc_stat, &ds);
1483     if (!res) {
1484       __msan_unpoison(p, ds.shm_segsz);
1485     }
1486   }
1487   return p;
1488 }
1489 
1490 INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb callback, void *data) {
1491   void *ctx;
1492   COMMON_INTERCEPTOR_ENTER(ctx, dl_iterate_phdr, callback, data);
1493   dl_iterate_phdr_data cbdata;
1494   cbdata.callback = callback;
1495   cbdata.data = data;
1496   int res = REAL(dl_iterate_phdr)(msan_dl_iterate_phdr_cb, (void *)&cbdata);
1497   return res;
1498 }
1499 
1500 // wchar_t *wcschr(const wchar_t *wcs, wchar_t wc);
1501 INTERCEPTOR(wchar_t *, wcschr, void *s, wchar_t wc, void *ps) {
1502   ENSURE_MSAN_INITED();
1503   wchar_t *res = REAL(wcschr)(s, wc, ps);
1504   return res;
1505 }
1506 
1507 // wchar_t *wcscpy(wchar_t *dest, const wchar_t *src);
1508 INTERCEPTOR(wchar_t *, wcscpy, wchar_t *dest, const wchar_t *src) {
1509   ENSURE_MSAN_INITED();
1510   GET_STORE_STACK_TRACE;
1511   wchar_t *res = REAL(wcscpy)(dest, src);
1512   CopyShadowAndOrigin(dest, src, sizeof(wchar_t) * (REAL(wcslen)(src) + 1),
1513                       &stack);
1514   return res;
1515 }
1516 
1517 INTERCEPTOR(wchar_t *, wcsncpy, wchar_t *dest, const wchar_t *src,
1518             SIZE_T n) {  // NOLINT
1519   ENSURE_MSAN_INITED();
1520   GET_STORE_STACK_TRACE;
1521   SIZE_T copy_size = REAL(wcsnlen)(src, n);
1522   if (copy_size < n) copy_size++;           // trailing \0
1523   wchar_t *res = REAL(wcsncpy)(dest, src, n);  // NOLINT
1524   CopyShadowAndOrigin(dest, src, copy_size * sizeof(wchar_t), &stack);
1525   __msan_unpoison(dest + copy_size, (n - copy_size) * sizeof(wchar_t));
1526   return res;
1527 }
1528 
1529 // These interface functions reside here so that they can use
1530 // REAL(memset), etc.
1531 void __msan_unpoison(const void *a, uptr size) {
1532   if (!MEM_IS_APP(a)) return;
1533   SetShadow(a, size, 0);
1534 }
1535 
1536 void __msan_poison(const void *a, uptr size) {
1537   if (!MEM_IS_APP(a)) return;
1538   SetShadow(a, size, __msan::flags()->poison_heap_with_zeroes ? 0 : -1);
1539 }
1540 
1541 void __msan_poison_stack(void *a, uptr size) {
1542   if (!MEM_IS_APP(a)) return;
1543   SetShadow(a, size, __msan::flags()->poison_stack_with_zeroes ? 0 : -1);
1544 }
1545 
1546 void __msan_unpoison_param(uptr n) { UnpoisonParam(n); }
1547 
1548 void __msan_clear_and_unpoison(void *a, uptr size) {
1549   REAL(memset)(a, 0, size);
1550   SetShadow(a, size, 0);
1551 }
1552 
1553 void *__msan_memcpy(void *dest, const void *src, SIZE_T n) {
1554   if (!msan_inited) return internal_memcpy(dest, src, n);
1555   if (msan_init_is_running || __msan::IsInSymbolizer())
1556     return REAL(memcpy)(dest, src, n);
1557   ENSURE_MSAN_INITED();
1558   GET_STORE_STACK_TRACE;
1559   void *res = REAL(memcpy)(dest, src, n);
1560   CopyShadowAndOrigin(dest, src, n, &stack);
1561   return res;
1562 }
1563 
1564 void *__msan_memset(void *s, int c, SIZE_T n) {
1565   if (!msan_inited) return internal_memset(s, c, n);
1566   if (msan_init_is_running) return REAL(memset)(s, c, n);
1567   ENSURE_MSAN_INITED();
1568   void *res = REAL(memset)(s, c, n);
1569   __msan_unpoison(s, n);
1570   return res;
1571 }
1572 
1573 void *__msan_memmove(void *dest, const void *src, SIZE_T n) {
1574   if (!msan_inited) return internal_memmove(dest, src, n);
1575   if (msan_init_is_running) return REAL(memmove)(dest, src, n);
1576   ENSURE_MSAN_INITED();
1577   GET_STORE_STACK_TRACE;
1578   void *res = REAL(memmove)(dest, src, n);
1579   MoveShadowAndOrigin(dest, src, n, &stack);
1580   return res;
1581 }
1582 
1583 void __msan_unpoison_string(const char* s) {
1584   if (!MEM_IS_APP(s)) return;
1585   __msan_unpoison(s, REAL(strlen)(s) + 1);
1586 }
1587 
1588 namespace __msan {
1589 
1590 void InitializeInterceptors() {
1591   static int inited = 0;
1592   CHECK_EQ(inited, 0);
1593 
1594   new(interceptor_ctx()) InterceptorContext();
1595 
1596   InitializeCommonInterceptors();
1597   InitializeSignalInterceptors();
1598 
1599   INTERCEPT_FUNCTION(posix_memalign);
1600   MSAN_MAYBE_INTERCEPT_MEMALIGN;
1601   MSAN_MAYBE_INTERCEPT___LIBC_MEMALIGN;
1602   INTERCEPT_FUNCTION(valloc);
1603   MSAN_MAYBE_INTERCEPT_PVALLOC;
1604   INTERCEPT_FUNCTION(malloc);
1605   INTERCEPT_FUNCTION(calloc);
1606   INTERCEPT_FUNCTION(realloc);
1607   INTERCEPT_FUNCTION(reallocarray);
1608   INTERCEPT_FUNCTION(free);
1609   MSAN_MAYBE_INTERCEPT_CFREE;
1610   MSAN_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE;
1611   MSAN_MAYBE_INTERCEPT_MALLINFO;
1612   MSAN_MAYBE_INTERCEPT_MALLOPT;
1613   MSAN_MAYBE_INTERCEPT_MALLOC_STATS;
1614   INTERCEPT_FUNCTION(fread);
1615   MSAN_MAYBE_INTERCEPT_FREAD_UNLOCKED;
1616   INTERCEPT_FUNCTION(memccpy);
1617   MSAN_MAYBE_INTERCEPT_MEMPCPY;
1618   INTERCEPT_FUNCTION(bcopy);
1619   INTERCEPT_FUNCTION(wmemset);
1620   INTERCEPT_FUNCTION(wmemcpy);
1621   MSAN_MAYBE_INTERCEPT_WMEMPCPY;
1622   INTERCEPT_FUNCTION(wmemmove);
1623   INTERCEPT_FUNCTION(strcpy);  // NOLINT
1624   MSAN_MAYBE_INTERCEPT_STPCPY;  // NOLINT
1625   INTERCEPT_FUNCTION(strdup);
1626   MSAN_MAYBE_INTERCEPT___STRDUP;
1627   INTERCEPT_FUNCTION(strncpy);  // NOLINT
1628   MSAN_MAYBE_INTERCEPT_GCVT;
1629   INTERCEPT_FUNCTION(strcat);  // NOLINT
1630   INTERCEPT_FUNCTION(strncat);  // NOLINT
1631   INTERCEPT_STRTO(strtod);
1632   INTERCEPT_STRTO(strtof);
1633   INTERCEPT_STRTO(strtold);
1634   INTERCEPT_STRTO(strtol);
1635   INTERCEPT_STRTO(strtoul);
1636   INTERCEPT_STRTO(strtoll);
1637   INTERCEPT_STRTO(strtoull);
1638   INTERCEPT_STRTO(strtouq);
1639   INTERCEPT_STRTO(wcstod);
1640   INTERCEPT_STRTO(wcstof);
1641   INTERCEPT_STRTO(wcstold);
1642   INTERCEPT_STRTO(wcstol);
1643   INTERCEPT_STRTO(wcstoul);
1644   INTERCEPT_STRTO(wcstoll);
1645   INTERCEPT_STRTO(wcstoull);
1646 #ifdef SANITIZER_NLDBL_VERSION
1647   INTERCEPT_FUNCTION_VER(vswprintf, SANITIZER_NLDBL_VERSION);
1648   INTERCEPT_FUNCTION_VER(swprintf, SANITIZER_NLDBL_VERSION);
1649 #else
1650   INTERCEPT_FUNCTION(vswprintf);
1651   INTERCEPT_FUNCTION(swprintf);
1652 #endif
1653   INTERCEPT_FUNCTION(strftime);
1654   INTERCEPT_FUNCTION(strftime_l);
1655   MSAN_MAYBE_INTERCEPT___STRFTIME_L;
1656   INTERCEPT_FUNCTION(wcsftime);
1657   INTERCEPT_FUNCTION(wcsftime_l);
1658   MSAN_MAYBE_INTERCEPT___WCSFTIME_L;
1659   INTERCEPT_FUNCTION(mbtowc);
1660   INTERCEPT_FUNCTION(mbrtowc);
1661   INTERCEPT_FUNCTION(wcslen);
1662   INTERCEPT_FUNCTION(wcsnlen);
1663   INTERCEPT_FUNCTION(wcschr);
1664   INTERCEPT_FUNCTION(wcscpy);
1665   INTERCEPT_FUNCTION(wcsncpy);
1666   INTERCEPT_FUNCTION(wcscmp);
1667   INTERCEPT_FUNCTION(getenv);
1668   INTERCEPT_FUNCTION(setenv);
1669   INTERCEPT_FUNCTION(putenv);
1670   INTERCEPT_FUNCTION(gettimeofday);
1671   MSAN_MAYBE_INTERCEPT_FCVT;
1672   MSAN_MAYBE_INTERCEPT_FSTAT;
1673   MSAN_MAYBE_INTERCEPT___FXSTAT;
1674   MSAN_INTERCEPT_FSTATAT;
1675   MSAN_MAYBE_INTERCEPT___FXSTAT64;
1676   MSAN_MAYBE_INTERCEPT___FXSTATAT64;
1677   INTERCEPT_FUNCTION(pipe);
1678   INTERCEPT_FUNCTION(pipe2);
1679   INTERCEPT_FUNCTION(socketpair);
1680   MSAN_MAYBE_INTERCEPT_FGETS_UNLOCKED;
1681   INTERCEPT_FUNCTION(getrlimit);
1682   MSAN_MAYBE_INTERCEPT_GETRLIMIT64;
1683   MSAN_MAYBE_INTERCEPT_PRLIMIT;
1684   MSAN_MAYBE_INTERCEPT_PRLIMIT64;
1685   MSAN_INTERCEPT_UNAME;
1686   INTERCEPT_FUNCTION(gethostname);
1687   MSAN_MAYBE_INTERCEPT_EPOLL_WAIT;
1688   MSAN_MAYBE_INTERCEPT_EPOLL_PWAIT;
1689   INTERCEPT_FUNCTION(dladdr);
1690   INTERCEPT_FUNCTION(dlerror);
1691   INTERCEPT_FUNCTION(dl_iterate_phdr);
1692   INTERCEPT_FUNCTION(getrusage);
1693 #if defined(__mips__)
1694   INTERCEPT_FUNCTION_VER(pthread_create, "GLIBC_2.2");
1695 #else
1696   INTERCEPT_FUNCTION(pthread_create);
1697 #endif
1698   INTERCEPT_FUNCTION(pthread_key_create);
1699 
1700 #if SANITIZER_NETBSD
1701   INTERCEPT_FUNCTION(__libc_thr_keycreate);
1702 #endif
1703 
1704   INTERCEPT_FUNCTION(pthread_join);
1705   INTERCEPT_FUNCTION(tzset);
1706   INTERCEPT_FUNCTION(atexit);
1707   INTERCEPT_FUNCTION(__cxa_atexit);
1708   INTERCEPT_FUNCTION(shmat);
1709   INTERCEPT_FUNCTION(fork);
1710   MSAN_MAYBE_INTERCEPT_OPENPTY;
1711   MSAN_MAYBE_INTERCEPT_FORKPTY;
1712 
1713   inited = 1;
1714 }
1715 } // namespace __msan
1716