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